sourcelibs/Matrix/src/Matrix.xtl

1⍝│ Matrix: matrices -- identity, diagonal, trace, product, 2⍝│ determinant, inverse, solving linear systems, orthonormal bases, 3⍝│ projection onto a subspace and coordinates in a basis, eigenvalues and 4⍝│ eigenvectors of a symmetric matrix, singular values and the best 5⍝│ rank-k approximation and principal angles between row spaces. 6⍝│ Import it with an alias of your choice: "mx:" u_se< "Matrix". 7⍝│ Put libs/Matrix/src on XETAL_PATH ("just path"); the reference is libs/Matrix/docs. 8⍝│ Names with l: are exported; those under h: are private to this file. 9⍝│ 10⍝│ A matrix is a rank-2 array, rows first. The numerical functions 11⍝│ (d_et, i_nverse, s_olve) work in Floats, by Gaussian elimination with 12⍝│ partial pivoting; compare their results with Check's ch:n_ear. The 13⍝│ transpose is the built-in o_\. 14 15⍝━━ Basics 16 17⍝│ i_dentity n: the n by n identity matrix (1 then n zeros, cycled). 18ˡi̲dentity ← { n → (n c̲at n) r̲eshape 1 c̲at n r̲eshape 0 } 19 20⍝│ d_iag m: the items on the main diagonal. 21ˡd̲iag ← { m → 22 k ← 'm̲in r̲/ s̲hape m 23 (1 + (o̲ffsets k) × 1 + f̲irst r̲ev s̲hape m) s̲elect r̲avel m 24} 25 26⍝│ t_race m: the sum of the diagonal. 27ˡt̲race ← { m → '+ r̲/ ˡd̲iag m } 28 29⍝│ a m_ul b: the matrix product (a matrix and a vector work too). 30ˡm̲ul ← { a b → a '+ '× i̲nner b } 31 32⍝━━ Solving 33 34⍝│ The permutation of 1..n that swaps i and j. 35ʰs̲wapping ← { n i j → 36 r ← r̲ange n 37 r + ((r = i) × j − i) + (r = j) × i − j 38} 39 40⍝│ The row (k..n) whose item in column k is largest in size. 41ʰp̲ivot ← { k m → 42 c ← a̲bs (k − 1) d̲rop k s̲elect₂ m 43 k + (f̲irst g̲rade n̲eg c) − 1 44} 45 46⍝│ Gauss-Jordan on m (Float) for columns k..n of its first n: each 47⍝│ column's pivot row moved up, scaled to 1, and the column cleared 48⍝│ from every other row. 49ʰg̲j ← { n k m → 50 k > n ? m 51 s ← ((n ʰs̲wapping k) k ʰp̲ivot m) s̲elect m 52 r ← r̲ange t̲ally s 53 v ← f̲irst k s̲elect k s̲elect₂ s ⍝ the pivot 54 0.000000000001 > a̲bs v ? @ p̲anic< "the matrix is singular: it has no inverse, and its system no unique solution"
p̲anic< expands to
(⎕P̲ANIC ("the matrix is singular: it has no inverse, and its system no unique solution"))
55 row ← (k s̲elect s) ÷ v 56 c ← (k s̲elect₂ s) − f̲loat r = k 57 ((n ʰg̲j k + 1) s − c '× t̲able row) 58} 59 60⍝│ b s_olve a: x with a m_ul x = b, for a square a; b is a vector or a 61⍝│ matrix of right-hand sides (one per column). A singular a stops 62⍝│ with error[panic] when a pivot is below 1e-12. 63ˡs̲olve ← { b a → 64 n ← t̲ally a 65 x ← n d̲rop₂ ((n ʰg̲j 1) f̲loat a c̲at₂ b) 66 (s̲hape b) r̲eshape x 67} 68 69⍝│ i_nverse a: the inverse of a square matrix. 70ˡi̲nverse ← { a → (ˡi̲dentity t̲ally a) ˡs̲olve a } 71 72⍝━━ Determinant 73 74⍝│ The determinant of a Float matrix m, by elimination: the first pivot 75⍝│ times the determinant of what is left, negated for a row swap. 76ʰd̲etF ← { m → 77 n ← t̲ally m 78 n = 1 ? f̲irst r̲avel m 79 p ← 1 ʰp̲ivot m 80 w ← ((n ʰs̲wapping 1) p) s̲elect m 81 v ← f̲irst r̲avel w 82 v = 0 ? 0.0 83 s ← f̲loat (p = 1) − p ≠ 1 84 r ← (1 d̲rop₂ 1 d̲rop w) − ((1 d̲rop f̲irst₂ w) ÷ v) '× t̲able 1 d̲rop f̲irst w 85 s × v × ʰd̲etF r 86} 87 88⍝│ d_et a: the determinant of a square matrix. 89ˡd̲et ← { a → ʰd̲etF f̲loat a } 90 91⍝━━ Subspaces 92 93⍝│ The tolerance of a dependent row: a remainder no longer than this 94⍝│ fraction of its row's own length is counted as 0. 95ʰt̲ol ← { u → 0.0000000001 } 96 97⍝│ The length of the vector v. 98ʰl̲ength ← { v → s̲qrt '+ r̲/ v × v } 99 100⍝│ q o_rth v: v less its projection onto the rows of q (orthonormal, 101⍝│ possibly none). 102ʰo̲rth ← { q v → v − (q '+ '× i̲nner v) '+ '× i̲nner q } 103 104⍝│ Modified Gram-Schmidt from row i of b on, the orthonormal rows so 105⍝│ far in q: each row's remainder taken twice (once leaves rounding of 106⍝│ the size of the projection; twice is orthogonal to the last digits) 107⍝│ and kept, made unit length, unless it is within the tolerance of 0. 108ʰg̲s ← { b i q → 109 i > t̲ally b ? q 110 v ← i s̲elect b 111 w ← q ʰo̲rth q ʰo̲rth v 112 r ← ʰl̲ength w 113 r ≤ (ʰt̲ol @) × ʰl̲ength v ? ((b ʰg̲s i + 1) q) 114 ((b ʰg̲s i + 1) q c̲at (1 c̲at t̲ally w) r̲eshape w ÷ r) 115} 116 117⍝│ o_rthonormal b: an orthonormal basis of the span of b's rows, as 118⍝│ rows: modified Gram-Schmidt, twice, in row order, so the first row 119⍝│ of the result is the first nonzero row of b made unit length. A row 120⍝│ within 1e-10 of its own length of the span of the rows before it is 121⍝│ dependent and dropped, so the result has as many rows as b's rank. 122ˡo̲rthonormal ← { b → 123 f ← f̲loat b 124 ((f ʰg̲s 1) (0 c̲at f̲irst r̲ev s̲hape f) r̲eshape 0.0) 125} 126 127⍝│ r_ank b: the dimension of the span of b's rows, the number of rows 128⍝│ of its orthonormal basis (to the same tolerance). 129ˡr̲ank ← { b → t̲ally ˡo̲rthonormal b } 130 131⍝│ b p_roject m: each row of m (or the vector m) projected onto the span 132⍝│ of b's rows: its nearest point there, m Q' Q for Q the orthonormal 133⍝│ basis of b's rows. b's rows need not be independent or orthonormal. 134ˡp̲roject ← { b m → 135 q ← ˡo̲rthonormal b 136 ((f̲loat m) '+ '× i̲nner o̲\ q) '+ '× i̲nner q 137} 138 139⍝│ b r_emainder m: what is left of m after its projection, m less 140⍝│ b p_roject m: orthogonal to every row of b. 141ˡr̲emainder ← { b m → (f̲loat m) − b ˡp̲roject m } 142 143⍝│ b c_oordinates m: the coordinates of each row of m (or the vector m) 144⍝│ in the rows of b: c with c mx:m_ul b equal to m, for m in the span; 145⍝│ for m outside it, the coordinates of its projection. b's rows must be 146⍝│ independent (else the coordinates are not unique): solved in b's 147⍝│ orthonormal basis Q, as c R = m Q' with R = b Q', so b b' is never 148⍝│ inverted. 149ˡc̲oordinates ← { b m → 150 q ← ˡo̲rthonormal b 151 (t̲ally q) < t̲ally b ? @ p̲anic< "the rows of the basis are dependent: coordinates in it are not unique"
p̲anic< expands to
(⎕P̲ANIC ("the rows of the basis are dependent: coordinates in it are not unique"))
152 r ← (f̲loat b) '+ '× i̲nner o̲\ q 153 a ← (f̲loat m) '+ '× i̲nner o̲\ q 154 o̲\ (o̲\ a) ˡs̲olve o̲\ r 155} 156 157⍝━━ Symmetric eigenvalues 158 159⍝│ Jacobi's stopping point: the off-diagonal part's length (Frobenius) at 160⍝│ most this fraction of the whole matrix's. 161ʰj̲acobiTol ← { u → 0.000000000000001 } 162 163⍝│ The most sweeps Jacobi makes before it stops with a message. 164ʰj̲acobiSweeps ← { u → 30 } 165 166⍝│ The length (Frobenius) of a matrix: every item squared, summed, rooted. 167ʰf̲robenius ← { a → s̲qrt '+ r̲/ r̲avel a × a } 168 169⍝│ The off-diagonal part of the square matrix a, the diagonal zeroed. 170ʰo̲ff ← { a → a × f̲loat 0 = ˡi̲dentity t̲ally a } 171 172⍝│ The rotation that zeroes item (p, q) of the symmetric a, as a full 173⍝│ n by n matrix j (j' a j has 0 there): from tau = (a_qq - a_pp) / 2 a_pq, 174⍝│ t = sign(tau) / (|tau| + sqrt(1 + tau^2)) (the smaller angle; an 175⍝│ overflowing tau^2 makes t 0, no rotation), c = 1 / sqrt(1 + t^2), 176⍝│ s = t c (Golub and Van Loan, sym.schur2). An item already 0 is left. 177ʰr̲otation ← { a p q → 178 n ← t̲ally a 179 i ← f̲loat ˡi̲dentity n 180 apq ← f̲irst q s̲elect p s̲elect a 181 0.0 = apq ? i 182 tau ← ((f̲irst q s̲elect q s̲elect a) − f̲irst p s̲elect p s̲elect a) ÷ 2.0 × apq 183 t ← (1.0 − 2.0 × f̲loat tau < 0.0) ÷ (a̲bs tau) + s̲qrt 1.0 + tau × tau 184 c ← 1.0 ÷ s̲qrt 1.0 + t × t 185 ep ← f̲loat (r̲ange n) = p 186 eq ← f̲loat (r̲ange n) = q 187 i + ((c − 1.0) × (ep '× t̲able ep) + eq '× t̲able eq) + (t × c) × (ep '× t̲able eq) − eq '× t̲able ep 188} 189 190⍝│ One cyclic sweep: a rotation for every pair p < q in row order, 191⍝│ applied to a (j' a j) and gathered in v (v j); the state (a, v). 192ʰs̲weep ← { (a, v) → 193 n ← t̲ally a 194 k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1 195 ps ← 1 + k d̲iv n 196 qs ← 1 + k m̲od n 197 r̲ot ← { (i, b, w) → 198 j ← ((b ʰr̲otation i s̲elect ps) i s̲elect qs) 199 (i + 1, (o̲\ j) ˡm̲ul b ˡm̲ul j, w ˡm̲ul j) 200 } 201 (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v) 202 (b, w) 203} 204 205⍝│ Sweeps until the off-diagonal part is within the tolerance of the 206⍝│ whole (or stop at the cap with a message); k sweeps made so far. 207ʰs̲weeps ← { k (a, v) → 208 (ʰf̲robenius ʰo̲ff a) ≤ (ʰj̲acobiTol @) × ʰf̲robenius a ? (a, v) 209 k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps"
p̲anic< expands to
(⎕P̲ANIC ("Jacobi did not converge in 30 sweeps"))
210 (k + 1) ʰs̲weeps ʰs̲weep (a, v) 211} 212 213⍝│ The eigenvalues of the symmetric s, descending, and its eigenvectors 214⍝│ as rows in the same order, each signed so its largest item (the first 215⍝│ of equal ones) is positive. s must be square and symmetric (to 1e-12 216⍝│ of its largest item); it is not symmetrized. 217ʰe̲igen ← { s → 218 a ← f̲loat s 219 n ← t̲ally a 220 n̲ot (n c̲at n) m̲atch s̲hape a ? @ p̲anic< "the matrix is not square"
p̲anic< expands to
(⎕P̲ANIC ("the matrix is not square"))
221 big ← 'm̲ax r̲/ 0.0 c̲at r̲avel a̲bs a 222 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"
p̲anic< expands to
(⎕P̲ANIC ("the matrix is not symmetric: eigenvalues here are for symmetric matrices only"))
223 (d, v) ← 0 ʰs̲weeps (a, f̲loat ˡi̲dentity n) 224 o ← g̲rade n̲eg ˡd̲iag d 225 w ← o s̲elect o̲\ v 226 ones ← n r̲eshape 1.0 227 hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones 228 first ← hit × f̲loat 1.0 = '+ s̲\₂ hit 229 sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first 230 (o s̲elect ˡd̲iag d, w × sg '× t̲able ones) 231} 232 233⍝│ e_igenvalues s: the eigenvalues of the symmetric matrix s, largest 234⍝│ first, by cyclic Jacobi. 235ˡe̲igenvalues ← { s → (vals, _) ← ʰe̲igen s◆ vals } 236 237⍝│ e_igenvectors s: the eigenvectors of the symmetric matrix s, one per 238⍝│ row, in the order of e_igenvalues; each of unit length, signed so its 239⍝│ largest item is positive: s is (o_\ v) times diag(values) times v. 240ˡe̲igenvectors ← { s → (_, vecs) ← ʰe̲igen s◆ vecs } 241 242⍝━━ Singular values 243 244⍝│ Whether the rows of a are orthogonal: every pair's dot product at most 245⍝│ the tolerance times the product of their lengths. 246ʰo̲rthogonal? ← { a → 247 g ← a ˡm̲ul o̲\ a 248 dg ← ˡd̲iag g 249 '∧ r̲/ r̲avel (a̲bs ʰo̲ff g) ≤ (ʰj̲acobiTol @) × s̲qrt dg '× t̲able dg 250} 251 252⍝│ One sweep of one-sided Jacobi on the rows of a: for every pair p < q, 253⍝│ the rotation that makes rows p and q orthogonal (the Jacobi rotation 254⍝│ of their Gram matrix, a a'), applied to a and gathered in v. 255ʰs̲vdSweep ← { (a, v) → 256 n ← t̲ally a 257 k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1 258 ps ← 1 + k d̲iv n 259 qs ← 1 + k m̲od n 260 r̲ot ← { (i, b, w) → 261 j ← (((b ˡm̲ul o̲\ b) ʰr̲otation i s̲elect ps) i s̲elect qs) 262 (i + 1, (o̲\ j) ˡm̲ul b, (o̲\ j) ˡm̲ul w) 263 } 264 (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v) 265 (b, w) 266} 267 268⍝│ Sweeps until the rows are orthogonal (or stop at the cap). 269ʰs̲vdSweeps ← { k (a, v) → 270 ʰo̲rthogonal? a ? (a, v) 271 k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps"
p̲anic< expands to
(⎕P̲ANIC ("Jacobi did not converge in 30 sweeps"))
272 (k + 1) ʰs̲vdSweeps ʰs̲vdSweep (a, v) 273} 274 275⍝│ The thin SVD of m with at least as many rows as columns: one-sided 276⍝│ Jacobi on the rows of m' (m itself is never squared), so the rows end 277⍝│ orthogonal, of lengths the singular values, along the left singular 278⍝│ vectors; v gathers the rotations, the right ones. Largest first, each 279⍝│ v row signed so its largest item is positive. 280ʰs̲vdTall ← { m → 281 n ← f̲irst r̲ev s̲hape m 282 (a, v) ← 0 ʰs̲vdSweeps (o̲\ m, f̲loat ˡi̲dentity n) 283 s ← s̲qrt '+ r̲/₂ a × a 284 o ← g̲rade n̲eg s 285 ones ← n r̲eshape 1.0 286 ss ← o s̲elect s 287 u ← (o s̲elect a) ÷ (ss + f̲loat ss = 0.0) '× t̲able (t̲ally f̲irst a) r̲eshape 1.0 288 w ← o s̲elect v 289 hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones 290 first ← hit × f̲loat 1.0 = '+ s̲\₂ hit 291 sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first 292 (u × sg '× t̲able (t̲ally f̲irst u) r̲eshape 1.0, ss, w × sg '× t̲able ones) 293} 294 295⍝│ s_vd m: the singular value decomposition, (u, s, v) with m equal to 296⍝│ (o_\ u) mx:m_ul diag(s) mx:m_ul v: s the singular values, largest 297⍝│ first, as many as m's smaller side; u's rows the left singular 298⍝│ vectors, v's the right ones (a zero singular value has a zero row in 299⍝│ u for tall/square m, in v for wide m). One-sided Jacobi on m or m'. 300ˡs̲vd ← { m → 301 f ← f̲loat m 302 (r, c) ← (f̲irst s̲hape f, f̲irst r̲ev s̲hape f) 303 r ≥ c ? ʰs̲vdTall f 304 (u, s, v) ← ʰs̲vdTall o̲\ f 305 (v, s, u) 306} 307 308⍝│ s_ingular m: the singular values of the matrix m, largest first, as 309⍝│ many as its smaller side. 310ˡs̲ingular ← { m → (_, s, _) ← ˡs̲vd m◆ s } 311 312⍝│ k t_runcate m: the best approximation of m of rank at most k (Eckart 313⍝│ and Young: nearest in both the Frobenius and the spectral norm), its 314⍝│ k largest singular values kept and the rest made 0; m itself when k 315⍝│ is at least its smaller side. 316ˡt̲runcate ← { k m → 317 (u, s, v) ← ˡs̲vd m 318 j ← k m̲in t̲ally s 319 (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 320} 321 322 323⍝━━ Principal angles 324 325⍝│ A finite rank-2 matrix for subspace comparison, converted to Float. 326⍝│ Scale each nonzero row by its largest magnitude before taking norms. 327ʰa̲ngleMatrix ← { a → 328 n̲ot 2 = t̲ally s̲hape a ? @ p̲anic< "principal angles require rank-2 matrices"
p̲anic< expands to
(⎕P̲ANIC ("principal angles require rank-2 matrices"))
329 f ← f̲loat a 330 n̲ot '∧ r̲/ r̲avel (f − f) = 0.0 ? @ p̲anic< "principal angles require finite input"
p̲anic< expands to
(⎕P̲ANIC ("principal angles require finite input"))
331 columns ← f̲irst r̲ev s̲hape f 332 0 = columns ? f 333 magnitude ← 'm̲ax r̲/₂ a̲bs f 334 divisor ← magnitude + f̲loat magnitude = 0.0 335 f ÷ divisor '× t̲able columns r̲eshape 1.0 336} 337 338⍝│ Principal angles for orthonormal rows p,q with dim(p) <= dim(q). 339⍝│ The right singular vectors of q p' give principal directions in p, 340⍝│ including zero cosine values. Their residuals off q give the sines. 341ʰa̲ngles ← { p q → 342 (_, cosines, right) ← ˡs̲vd q ˡm̲ul o̲\ p 343 directions ← right ˡm̲ul p 344 residual ← directions − (directions ˡm̲ul o̲\ q) ˡm̲ul q 345 sine ← s̲qrt '+ r̲/₂ residual × residual 346 cosine ← 0.0 m̲ax 1.0 m̲in cosines 347 ⍝ Nonnegative atan2 by its half-angle form, finite even at c=0. 348 angle ← 2.0 × a̲tan sine ÷ (s̲qrt (sine × sine) + cosine × cosine) + cosine 349 (g̲rade angle) s̲elect angle 350} 351 352⍝│ a a_ngles b: ascending principal angles in radians between row spaces, 353⍝│ as many as the smaller rank. Orthonormal bases use the 1e-10 relative 354⍝│ row-dependence tolerance. Zero-rank inputs give an empty Float vector. 355⍝│ SVD cosines plus residual sines preserve small angles without acos(1). 356ˡa̲ngles ← { a b → 357 x ← ʰa̲ngleMatrix a 358 y ← ʰa̲ngleMatrix b 359 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"
p̲anic< expands to
(⎕P̲ANIC ("principal-angle matrices must have the same column count"))
360 (0 = t̲ally x) ∨ (0 = t̲ally y) ∨ 0 = f̲irst r̲ev s̲hape x ? 0 r̲eshape 0.0 361 p ← ˡo̲rthonormal x 362 q ← ˡo̲rthonormal y 363 (0 = t̲ally p) ∨ 0 = t̲ally q ? 0 r̲eshape 0.0 364 (t̲ally p) ≤ t̲ally q ? p ʰa̲ngles q 365 q ʰa̲ngles p 366}