Repository Public
1import Foundation2import CAccelShim34/// Dense real matrix, row-major storage.5public struct Matrix: Sendable, Hashable, Codable {6 public let rows: Int7 public let cols: Int8 public var data: [Double]910 public init(rows: Int, cols: Int, repeating v: Double = 0) {11 precondition(rows >= 0 && cols >= 0)12 self.rows = rows; self.cols = cols13 self.data = Array(repeating: v, count: rows * cols)14 }1516 public init(rows: Int, cols: Int, data: [Double]) {17 precondition(data.count == rows * cols, "Matrix shape mismatch")18 self.rows = rows; self.cols = cols; self.data = data19 }2021 /// Builds from rows; all rows must have the same length.22 public init(_ rowsIn: [[Double]]) {23 let c = rowsIn.first?.count ?? 024 precondition(rowsIn.allSatisfy { $0.count == c }, "Ragged matrix")25 self.init(rows: rowsIn.count, cols: c, data: rowsIn.flatMap { $0 })26 }2728 /// Builds from columns (each inner array is one variable).29 public init(columns: [[Double]]) {30 let r = columns.first?.count ?? 031 precondition(columns.allSatisfy { $0.count == r }, "Columns of unequal length")32 var m = Matrix(rows: r, cols: columns.count)33 for (j, col) in columns.enumerated() { for i in 0..<r { m.data[i * columns.count + j] = col[i] } }34 self = m35 }3637 public static func identity(_ n: Int) -> Matrix {38 var m = Matrix(rows: n, cols: n)39 for i in 0..<n { m.data[i * n + i] = 1 }40 return m41 }4243 public static func diagonal(_ d: [Double]) -> Matrix {44 var m = Matrix(rows: d.count, cols: d.count)45 for i in d.indices { m.data[i * d.count + i] = d[i] }46 return m47 }4849 @inlinable public subscript(r: Int, c: Int) -> Double {50 get { data[r * cols + c] }51 set { data[r * cols + c] = newValue }52 }5354 public func row(_ r: Int) -> [Double] { Array(data[(r * cols)..<((r + 1) * cols)]) }55 public func column(_ c: Int) -> [Double] { (0..<rows).map { data[$0 * cols + c] } }56 public var rowArrays: [[Double]] { (0..<rows).map { row($0) } }57 public var columnArrays: [[Double]] { (0..<cols).map { column($0) } }58 public var diagonalValues: [Double] { (0..<min(rows, cols)).map { data[$0 * cols + $0] } }5960 public var transposed: Matrix {61 var t = Matrix(rows: cols, cols: rows)62 for r in 0..<rows { for c in 0..<cols { t.data[c * rows + r] = data[r * cols + c] } }63 return t64 }6566 /// Column-major copy of the storage (what LAPACK expects).67 var columnMajor: [Double] { transposed.data }6869 init(columnMajor d: [Double], rows: Int, cols: Int) {70 self = Matrix(rows: cols, cols: rows, data: d).transposed71 }7273 public static func * (a: Matrix, b: Matrix) -> Matrix {74 precondition(a.cols == b.rows, "Matrix product shape mismatch")75 var c = [Double](repeating: 0, count: a.rows * b.cols)76 let am = a.columnMajor, bm = b.columnMajor77 orix_dgemm(Int32(a.rows), Int32(b.cols), Int32(a.cols), am, bm, &c)78 return Matrix(columnMajor: c, rows: a.rows, cols: b.cols)79 }8081 public static func * (a: Matrix, v: [Double]) -> [Double] {82 precondition(a.cols == v.count, "Matrix-vector shape mismatch")83 var out = [Double](repeating: 0, count: a.rows)84 for r in 0..<a.rows {85 var s = 0.086 let base = r * a.cols87 for c in 0..<a.cols { s += a.data[base + c] * v[c] }88 out[r] = s89 }90 return out91 }9293 public static func * (s: Double, a: Matrix) -> Matrix { Matrix(rows: a.rows, cols: a.cols, data: a.data.map { $0 * s }) }94 public static func + (a: Matrix, b: Matrix) -> Matrix {95 precondition(a.rows == b.rows && a.cols == b.cols)96 return Matrix(rows: a.rows, cols: a.cols, data: zip(a.data, b.data).map(+))97 }98 public static func - (a: Matrix, b: Matrix) -> Matrix {99 precondition(a.rows == b.rows && a.cols == b.cols)100 return Matrix(rows: a.rows, cols: a.cols, data: zip(a.data, b.data).map(-))101 }102103 /// Xᵀ X computed directly (symmetric).104 public var gram: Matrix { transposed * self }105}106107/// LAPACK-backed linear algebra (Accelerate).108public enum LinearAlgebra {109 /// Thin QR factorisation A = Q R of an m×n matrix with m ≥ n (Householder, LAPACK `dgeqrf`/`dorgqr`).110 /// Q is m×n with orthonormal columns, R is n×n upper triangular.111 public static func qr(_ a: Matrix) throws -> (q: Matrix, r: Matrix) {112 let m = a.rows, n = a.cols113 guard m >= n, n > 0 else { throw StatError.invalidInput("QR needs rows ≥ columns ≥ 1") }114 var cm = a.columnMajor115 var tau = [Double](repeating: 0, count: n)116 guard orix_dgeqrf(Int32(m), Int32(n), &cm, &tau) == 0 else { throw StatError.singular("QR factorisation failed") }117 var r = Matrix(rows: n, cols: n)118 for j in 0..<n { for i in 0...j { r[i, j] = cm[j * m + i] } }119 guard orix_dorgqr(Int32(m), Int32(n), Int32(n), &cm, tau) == 0 else { throw StatError.singular("QR factorisation failed") }120 return (Matrix(columnMajor: cm, rows: m, cols: n), r)121 }122123 /// Thin singular value decomposition A = U diag(s) Vᵀ (LAPACK `dgesdd`); singular values descending.124 public static func svd(_ a: Matrix) throws -> (u: Matrix, s: [Double], vt: Matrix) {125 let m = a.rows, n = a.cols, k = min(m, n)126 guard k > 0 else { throw StatError.invalidInput("SVD of an empty matrix") }127 var cm = a.columnMajor128 var s = [Double](repeating: 0, count: k)129 var u = [Double](repeating: 0, count: m * k)130 var vt = [Double](repeating: 0, count: k * n)131 guard orix_dgesdd(Int32(m), Int32(n), &cm, &s, &u, &vt) == 0 else { throw StatError.notConverged("SVD") }132 return (Matrix(columnMajor: u, rows: m, cols: k), s, Matrix(columnMajor: vt, rows: k, cols: n))133 }134135 /// Eigen-decomposition of a symmetric matrix (LAPACK `dsyev`). Eigenvalues ascending; eigenvectors in the columns of `vectors`.136 public static func symmetricEigen(_ a: Matrix) throws -> (values: [Double], vectors: Matrix) {137 guard a.rows == a.cols, a.rows > 0 else { throw StatError.invalidInput("Eigen-decomposition needs a square matrix") }138 let n = a.rows139 var cm = a.columnMajor140 var w = [Double](repeating: 0, count: n)141 guard orix_dsyev(Int32(n), &cm, &w) == 0 else { throw StatError.notConverged("symmetric eigen-decomposition") }142 return (w, Matrix(columnMajor: cm, rows: n, cols: n))143 }144145 /// Lower Cholesky factor L (A = L Lᵀ) of a symmetric positive-definite matrix (LAPACK `dpotrf`).146 public static func cholesky(_ a: Matrix) throws -> Matrix {147 guard a.rows == a.cols, a.rows > 0 else { throw StatError.invalidInput("Cholesky needs a square matrix") }148 let n = a.rows149 var cm = a.columnMajor150 guard orix_dpotrf(Int32(n), &cm) == 0 else { throw StatError.singular("matrix is not positive definite") }151 var l = Matrix(rows: n, cols: n)152 for j in 0..<n { for i in j..<n { l[i, j] = cm[j * n + i] } }153 return l154 }155156 /// Solves A X = B (LU with partial pivoting, LAPACK `dgesv`).157 public static func solve(_ a: Matrix, _ b: Matrix) throws -> Matrix {158 guard a.rows == a.cols, a.rows == b.rows, a.rows > 0 else { throw StatError.invalidInput("solve: shape mismatch") }159 var am = a.columnMajor, bm = b.columnMajor160 guard orix_dgesv(Int32(a.rows), Int32(b.cols), &am, &bm) == 0 else { throw StatError.singular("matrix is singular") }161 return Matrix(columnMajor: bm, rows: b.rows, cols: b.cols)162 }163164 public static func solve(_ a: Matrix, _ b: [Double]) throws -> [Double] {165 try solve(a, Matrix(rows: b.count, cols: 1, data: b)).data166 }167168 /// Inverse of a general square matrix (LAPACK `dgetrf`/`dgetri`).169 public static func inverse(_ a: Matrix) throws -> Matrix {170 guard a.rows == a.cols, a.rows > 0 else { throw StatError.invalidInput("inverse needs a square matrix") }171 var cm = a.columnMajor172 guard orix_dgetri(Int32(a.rows), &cm) == 0 else { throw StatError.singular("matrix is singular") }173 return Matrix(columnMajor: cm, rows: a.rows, cols: a.cols)174 }175176 /// 2-norm condition number (ratio of extreme singular values); `.infinity` when singular.177 public static func conditionNumber(_ a: Matrix) throws -> Double {178 let s = try svd(a).s179 guard let mx = s.first, let mn = s.last else { return .nan }180 return mn > 0 ? mx / mn : .infinity181 }182183 /// Solves R x = b by back substitution for an upper-triangular R.184 public static func backSubstitute(_ r: Matrix, _ b: [Double]) throws -> [Double] {185 let n = r.rows186 guard r.cols == n, b.count == n else { throw StatError.invalidInput("backSubstitute: shape mismatch") }187 var x = b188 for i in stride(from: n - 1, through: 0, by: -1) {189 var s = x[i]190 for j in (i + 1)..<max(n, i + 1) { s -= r[i, j] * x[j] }191 guard r[i, i] != 0 else { throw StatError.singular("zero pivot in triangular solve") }192 x[i] = s / r[i, i]193 }194 return x195 }196197 /// Determinant via LU is not exposed by the shim; for symmetric positive-definite matrices use the Cholesky factor.198 public static func logDeterminantSPD(_ a: Matrix) throws -> Double {199 let l = try cholesky(a)200 return 2 * l.diagonalValues.reduce(0) { $0 + Foundation.log($1) }201 }202}203