Defines the shape of a matrix using rows and columns properties.
public struct Shape {
public let rows: Int
public let columns: Int
}
This includes a number of convenience properties like count, length and breadth; as well as convenience initializers .row(length:), .column(length:) and .square(length:).
Generic matrix struct with Scalar type argument and shape and elements properties. Elements are stored as a single array in row-major format.
public struct Matrix<Scalar> {
public let shape: Shape
public var elements: [Scalar]
}
This also includes a large number of convenience initializers and implementations of typical typeclasses such as Codable and ExpressibleByArrayLiteral.
The elements property is directly mutable but this is ideally to be avoided; matrix regularity is not enforced, except during encoding to or decoding from a serialization format.
There is a computed property state which can be used to check if the matrix is considered to be malformed:
Generic complex matrix struct encapsulating two separate matrices for the real and imaginary parts.
public struct ComplexMatrix<Scalar> where Scalar: Real {
public var real: Matrix<Scalar>
public var imaginary: Matrix<Scalar>
}
This also includes a large number of convenience initializers and implementations of typical typeclasses such as Codable and ExpressibleByArrayLiteral.
The real and imaginary properties are also directly mutable; ComplexMatrix has its own state property which can be used to check if the parts are mismatched or malformed.
+ and - prefix operators and +, -, *, / infix operators.
Implements fast pointwise arithmetic for combinations of Scalar, Complex<Scalar>, Matrix<Scalar> and ComplexMatrix<Scalar>, where Scalar is Float or Double.
Implements fast pointwise power operations for Scalar and Matrix.
Includes special functions for taking integer powers of matrices, for use when recursive application of vDSP.multiply will be faster than vForce.pow (which is quite an expensive operation).
This also supports negative integers by applying vForce.reciprocal to the result.
Calculate the eigendecomposition of a matrix. Includes support for only calculating the necessary components. Also includes support for sorting the eigenvectors by properties of the eigenvalues.
Uses LAPACK’s sgeev_/dgeev_.
Swift implementation cribbed from Surge.
Plinth
Hardware-accelerated matrix/numeric programming library for Swift.
Installation
Swift Package Manager
Simply add Plinth to your
Package.swift
file:Then import Plinth into your Swift files:
Or for full
ComplexMatrix
support you should also importswift-numerics
, as that’s where theComplex
type lives.Links
Dependencies
References/prior art
ShapedArray
type toswift-numerics
)Todo
.zeros
and.ones
initializersvDSP.fill
,vDSP.clear
,vDSP.window
,vDSP.ramp
,vDSP.stereoRamp
vDSP.convolve
Eigendecomposition.sorted
, is sorting the eigenvalues by real component or the magnitude preferable?Add Cocoapods supportCan’t do this,swift-numerics
only supports SPM. Perhaps I should make my ownComplex
type.Documentation
Types
Shape
Defines the shape of a matrix using
rows
andcolumns
properties.This includes a number of convenience properties like
count
,length
andbreadth
; as well as convenience initializers.row(length:)
,.column(length:)
and.square(length:)
.Matrix
Generic matrix struct with
Scalar
type argument andshape
andelements
properties. Elements are stored as a single array in row-major format.This also includes a large number of convenience initializers and implementations of typical typeclasses such as
Codable
andExpressibleByArrayLiteral
.The
elements
property is directly mutable but this is ideally to be avoided; matrix regularity is not enforced, except during encoding to or decoding from a serialization format.There is a computed property
state
which can be used to check if the matrix is considered to be malformed:ComplexMatrix
Generic complex matrix struct encapsulating two separate matrices for the
real
andimaginary
parts.This also includes a large number of convenience initializers and implementations of typical typeclasses such as
Codable
andExpressibleByArrayLiteral
.The
real
andimaginary
properties are also directly mutable;ComplexMatrix
has its ownstate
property which can be used to check if the parts are mismatched or malformed.Core
Arithmetic
+
and-
prefix operators and+
,-
,*
,/
infix operators.Implements fast pointwise arithmetic for combinations of
Scalar
,Complex<Scalar>
,Matrix<Scalar>
andComplexMatrix<Scalar>
, whereScalar
isFloat
orDouble
.Conversions
Fast type conversions between the integer types
UInt8
,UInt16
,UInt32
,Int8
,Int16
,Int32
and the floating point typesFloat
andDouble
.Functors
Higher-order functions for shape-preserving operations on a matrix’s elements.
Includes support for complex matrix operations on
DSPSplitComplex
/DSPDoubleSplitComplex
.Submatrix
Fast submatrix read/write access using a Swift subscript interface.
Wrappers
Wrappers over most of the basic
vDSP
andvForce
functions in Accelerate.Transformations
Center
Find the center point of a matrix, given a rounding rule.
Crop
Crop a matrix towards the center, given a rounding rule.
Pad
Zero-pad a matrix away from the center, given a rounding rule.
Reshape
Apply a new shape to a matrix, or reshape it as a single row or column.
This also supports both
.rowMajor
and.columnMajor
orderings.Shift
Apply a circular shift to a matrix.
Concatenate
Concatentate multiple matrices together, row-wise or column-wise.
Comparisons
Comparisons
<
,<=
,>
,>=
,==
,!==
infix operators.Pointwise comparison or equality checks, returning
0.0
forfalse
and1.0
fortrue
.Mathematics
Powers
**
infix operator.Implements fast pointwise power operations for
Scalar
andMatrix
.Includes special functions for taking integer powers of matrices, for use when recursive application of
vDSP.multiply
will be faster thanvForce.pow
(which is quite an expensive operation).This also supports negative integers by applying
vForce.reciprocal
to the result.Interpolation
Linear interpolate values from a given range to/from
0.0...1.0
.Statistics
Random
Generate matrices populated with random noise.
Gaussian
Generate matrices populated with Gaussian noise.
Moments
Calculate central and standardized moments; convenience methods for
variance
,standardDeviation
,skewness
, andkurtosis
.Normalization
Normalize a matrix to
0.0...1.0
using itsminimum()
andmaximum()
values; or shift it so that itsmean()
is centered on zero.Linear Algebra
Zeros
Generate matrices populated by zeros.
Ones
Generate matrices populated by ones.
Identity
Generate identity matrices.
Diagonal
Generate diagonal matrices.
Transposition
Transpose a matrix.
Inversion
Calculate the inverse of a matrix.
Multiplication
<*>
infix operator.Implements matrix multiplication.
Division
/>
and</
infix operators.Implements left and right matrix division (multiplying by the inverse of a matrix).
Square Root
Complex square roots.
Exponentiation
Complex exponentials.
Products
Inner and outer products.
Eigendecomposition
Calculate the eigendecomposition of a matrix. Includes support for only calculating the necessary components. Also includes support for sorting the eigenvectors by properties of the eigenvalues.
Roots
Calculate the roots of a polynomial by taking the eigenvalues of a companion matrix.
Image Processing
Bitmaps
Conversion to and from floating point formats in the range
0.0...1.0
to 8-bit bitmaps in the range0...255
.Images
Conversion to and from 8-bit bitmaps and
CGImage
,CIImage
,NSImage
, andUIImage
.Signal Processing
FFT
Forward and inverse two-dimensional fourier transforms.
Includes support for creating, reusing, and destroying your own
FFTSetup
/FFTSetupD
structure.Some of the inverse fourier transform methods implement energy conservation by dividing by the size of the matrix.
FFTShift
Apply a circular rotation to a frequency-domain matrix so that the DC/DC signal is at the top left of the lower right quadrant.
Autocorrelation
Calculate the autocorrelation of a matrix by taking the square magnitudes in the frequency domain.