AccelerateArray
Swift 数组扩展用于 Apple Accelerate 框架。
这个包的目标是提供稍易于使用的访问 BLAS、LAPACK 和 vDSP 函数的方法,以便将这些函数应用于 Float 和 Double swift 数组。
此包的范围不包括作为矩阵处理数组的高级包装器,这将包括存储步长、形状和顺序(行/列主顺序)。这需要添加额外的类型,这些类型可以轻易地在本包之上构建。
目录
安装
Swift 包管理器
let package = Package(
dependencies: [
.package(url: "https://github.com/dastrobu/AccelerateArray.git", from: "0.4.0"),
]
)
Cocoa Pods
请确保在Podfile中设置了有效的部署目标,并添加
pod 'AccelerateArray', '~> 0'
依赖项
除默认安装的Accelerate框架外,macOS上没有其他依赖项。由于Accelerate也包含在iOS和其他Apple平台上,因此此包应在所有Apple平台上运行。
示例
BLAS (ATLAS)
缩放向量 (sscal, dscal)
向量可以通过以下方式放大
a = [1, 2, 3]
a.scal(2) // [2, 4, 6]
或通过提供所有参数,例如使用步长为两个的步长
a = [1, 2, 3]
a.scal(n: Int32(a.count), alpha: 2, incX: 2) // [2, 2, 6]
将向量设置为常量 (sset, dset)
将向量的所有元素设置为单个常量。
a = [1, 2, 3]
a.set(9) // [9, 9, 9]
或通过提供所有参数,例如使用步长为两个的步长
a = [1, 2, 3]
a.set(n: Int32(a.count), alpha: 2, incX: 2) // [9, 2, 9]
LAPACK
LU 分解
计算 LU 分解。
// A in row major
let A: [Float] = [
1.0, 2.0,
3.0, 4.0,
5.0, 6.0,
7.0, 8.0
]
// convert A to col major (for fortran)
var At = A.mtrans(m: 2, n: 4)
// compute factorization
let ipiv = try At.getrf(m: 4, n: 2)
// convert solution to row major
let X = At.mtrans(m: 4, n: 2)
// L in row major (pic lower triangular matrix)
let L: [Float] = [
1.0, 0.0,
X[2], 1.0,
X[4], X[5],
X[6], X[7],
]
// U in row major (pic upper triangular matrix)
let U: [Float] = [
X[0], X[1],
0.0, X[3],
]
// note, the indices in ipiv are one base (fortran)
// construct the permutation vector
// see: https://math.stackexchange.com/a/3112224/91477
var p = [0, 1, 2, 3]
for i in 0..<ipiv.count {
p.swapAt(i, Int(ipiv[i] - 1))
}
// construct the full permuation matrix
let n = 4
var P: [Float] = Array(repeating: 0, count: n * n)
for i in 0..<p.count {
// i iterates columns of P (in row major)
// p[i] indicates which element in the column must be set to one, to create the permutation matrix
P[i + p[i] * n] = 1.0
}
// now compute PLU (which should be equal to A within numerical accuracy)
let PLU = P.mmul(B: L.mmul(B: U, m: 4, n: 2, p: 2), m: 4, n: 2, p: 4)
// gives [
// 1.0 , 2.0,
// 3.0000002, 4.0,
// 5.0 , 6.0,
// 7.0 , 8.0
// ]
逆矩阵
通过以下方式求矩阵的逆
// inversion is independent of row/col major storage
var A: [Float] = [
1.0, 2.0,
3.0, 4.0,
]
try A.getri()
// gives [
// -2.0, 1.0,
// 1.5, -0.5,
// ]
文档
阅读文档。