This repository has been archived by the owner on Oct 17, 2021. It is now read-only.
forked from Jounce/Surge
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Matrix.swift
298 lines (220 loc) · 9.76 KB
/
Matrix.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Hyperbolic.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Accelerate
public struct Matrix<T where T: FloatingPointType, T: FloatLiteralConvertible> {
typealias Element = T
let rows: Int
let columns: Int
var grid: [Element]
public init(rows: Int, columns: Int, repeatedValue: Element) {
self.rows = rows
self.columns = columns
self.grid = [Element](count: rows * columns, repeatedValue: repeatedValue)
}
public init(_ contents: [[Element]]) {
let m: Int = contents.count
let n: Int = contents[0].count
let repeatedValue: Element = 0.0
self.init(rows: m, columns: n, repeatedValue: repeatedValue)
for (index, row) in enumerate(contents) {
grid.replaceRange((index * n)..<(index * n + min(m, row.count)), with: row)
}
}
public subscript(row: Int, column: Int) -> Element {
get {
assert(indexIsValidForRow(row, column: column))
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column))
grid[(row * columns) + column] = newValue
}
}
private func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
}
// MARK: - Printable
extension Matrix: Printable {
public var description: String {
var description = ""
for row in 0..<rows {
let contents = join("\t", map(0..<columns){"\(self[row, $0])"})
switch (row, rows) {
case (0, 1):
description += "(\t\(contents)\t)"
case (0, _):
description += "⎛\t\(contents)\t⎞"
case (rows - 1, _):
description += "⎝\t\(contents)\t⎠"
default:
description += "⎜\t\(contents)\t⎥"
}
description += "\n"
}
return description
}
}
// MARK: - SequenceType
extension Matrix: SequenceType {
public func generate() -> GeneratorOf<ArraySlice<Element>> {
let endIndex = rows * columns
var nextRowStartIndex = 0
return GeneratorOf<ArraySlice<Element>> {
if nextRowStartIndex == endIndex {
return nil
}
let currentRowStartIndex = nextRowStartIndex
nextRowStartIndex += self.columns
return self.grid[currentRowStartIndex..<nextRowStartIndex]
}
}
}
// MARK: -
public func add(x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition")
var results = y
cblas_saxpy(Int32(x.grid.count), 1.0, x.grid, 1, &(results.grid), 1)
return results
}
public func add(x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition")
var results = y
cblas_daxpy(Int32(x.grid.count), 1.0, x.grid, 1, &(results.grid), 1)
return results
}
public func mul(alpha: Float, x: Matrix<Float>) -> Matrix<Float> {
var results = x
cblas_sscal(Int32(x.grid.count), alpha, &(results.grid), 1)
return results
}
public func mul(alpha: Double, x: Matrix<Double>) -> Matrix<Double> {
var results = x
cblas_dscal(Int32(x.grid.count), alpha, &(results.grid), 1)
return results
}
public func mul(x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication")
var results = Matrix<Float>(rows: x.rows, columns: y.columns, repeatedValue: 0.0)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, &(results.grid), Int32(results.columns))
return results
}
public func mul(x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication")
var results = Matrix<Double>(rows: x.rows, columns: y.columns, repeatedValue: 0.0)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, &(results.grid), Int32(results.columns))
return results
}
public func inv(x : Matrix<Float>) -> Matrix<Float> {
precondition(x.rows == x.columns, "Matrix must be square")
var results = x
var ipiv = [__CLPK_integer](count: x.rows * x.rows, repeatedValue: 0)
var lwork = __CLPK_integer(x.columns * x.columns)
var work = [CFloat](count: Int(lwork), repeatedValue: 0.0)
var error: __CLPK_integer = 0
var nc = __CLPK_integer(x.columns)
sgetrf_(&nc, &nc, &(results.grid), &nc, &ipiv, &error)
sgetri_(&nc, &(results.grid), &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
return results
}
public func inv(x : Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == x.columns, "Matrix must be square")
var results = x
var ipiv = [__CLPK_integer](count: x.rows * x.rows, repeatedValue: 0)
var lwork = __CLPK_integer(x.columns * x.columns)
var work = [CDouble](count: Int(lwork), repeatedValue: 0.0)
var error: __CLPK_integer = 0
var nc = __CLPK_integer(x.columns)
dgetrf_(&nc, &nc, &(results.grid), &nc, &ipiv, &error)
dgetri_(&nc, &(results.grid), &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
return results
}
public func transpose(x: Matrix<Float>) -> Matrix<Float> {
var results = Matrix<Float>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtrans(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
public func transpose(x: Matrix<Double>) -> Matrix<Double> {
var results = Matrix<Double>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtransD(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
public func eigendecompostion(x: Matrix<Float>) ->(Matrix<Float>, [Float]) {
var input = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
input.grid = map(x.grid) {return Double($0)}
let (eigenVectors, components) = eigendecompostion(input)
var output = Matrix<Float>(rows: eigenVectors.rows, columns: eigenVectors.columns, repeatedValue: 0.0)
output.grid = map(eigenVectors.grid) {return Float($0)}
return (output, map(components) {return Float($0)})
}
public func eigendecompostion(x: Matrix<Double>) ->(Matrix<Double>, [Double]) {
precondition(x.rows == x.columns, "Matrix must be square")
var mat: [__CLPK_doublereal] = x.grid
var N = __CLPK_integer(sqrt(Double(x.grid.count)))
var pivots = [__CLPK_integer](count: Int(N), repeatedValue: 0)
var workspaceQuery: Double = 0.0
var error : __CLPK_integer = 0
var lwork = __CLPK_integer(-1)
var wr = [Double](count: Int(N), repeatedValue: 0)
var wi = [Double](count: Int(N), repeatedValue: 0)
var vl = [Double](count: Int(N * N), repeatedValue: 0)
var vr = [Double](count: Int(N * N), repeatedValue: 0)
"V".withCString { (V) -> Void in
dgeev_(UnsafeMutablePointer(V), UnsafeMutablePointer(V), &N, &mat, &N, &wr, &wi, &vl, &N, &vr, &N, &workspaceQuery, &lwork, &error)
}
var workspace = [Double](count: Int(workspaceQuery), repeatedValue: 0.0)
lwork = __CLPK_integer(workspaceQuery)
"V".withCString { (V) -> Void in
dgeev_(UnsafeMutablePointer(V), UnsafeMutablePointer(V), &N, &mat, &N, &wr, &wi, &vl, &N, &vr, &N, &workspace, &lwork, &error)
}
var eigenVectors: Matrix<Double> = Matrix(rows: Int(N), columns: Int(N), repeatedValue: 0.0)
eigenVectors.grid = vr
return (eigenVectors, wr)
}
// MARK: - Operators
public func + (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> {
return add(lhs, rhs)
}
public func + (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return add(lhs, rhs)
}
public func * (lhs: Float, rhs: Matrix<Float>) -> Matrix<Float> {
return mul(lhs, rhs)
}
public func * (lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, rhs)
}
public func * (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> {
return mul(lhs, rhs)
}
public func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, rhs)
}
postfix operator ′ {}
public postfix func ′ (value: Matrix<Float>) -> Matrix<Float> {
return transpose(value)
}
public postfix func ′ (value: Matrix<Double>) -> Matrix<Double> {
return transpose(value)
}