clojure.core.matrix.protocols
Namespace for core.matrix protocols. These protocols are intended to be implemented by
core.matrix array implemntations.
End users should normally avoid using this namespace directly
and instead use the functions in the main clojure.core.matrix API
broadcast-compatible
(broadcast-compatible a b)
Broadcasts two matrices into identical shapes, coercing to the type of the first matrix.
Intended to prepare for elementwise operations.
Returns a vector containing the two broadcasted matrices.
Throws an error if not possible.
broadcast-same-shape
(broadcast-same-shape a b)
Broadcasts two matrices into identical shapes. Intended to prepare for elementwise operations.
Returns a vector containing the two broadcasted matrices.
Throws an error if not possible.
common-shape
(common-shape shapes)
Returns the common shape that can be broadcast to from all the shapes specified,
or nil if such a shape does not exist.
ensure-type
(ensure-type m klass)
Checks if an array can contain a specified Java type, if so returns the orifginal array, otherwise
returns a copy of the array that can support the specified type.
PAddInnerProductMutable
protocol
Protocol to support the mutable add-inner-product! operation. This is a common operation that may be
optimised by the underlying implementation. Implementations should consider extra optimisations for
specific constant factors e.g. 0.0 and 1.0 but this is not mandatory.
members
add-inner-product!
(add-inner-product! m a b)
(add-inner-product! m a b factor)
Adds the inner product of a, b and an optional scalar factor to m
PAddProduct
protocol
Optional protocol for add-product operation.
Intended to support optimised implementations for result = m + a * b
members
add-product
(add-product m a b)
PAddProductMutable
protocol
Optional protocol for mutable add-product! operation.
Intended to support optimised implementations for m = m + a * b
members
add-product!
(add-product! m a b)
Adds the elementwise product of a and b to m
PAddScaled
protocol
Protocol for add-scaled operation.
Implementations may assume that factor is a scalar.
Intended to support optimised implementations for result = m + a * factor
members
add-scaled
(add-scaled m a factor)
PAddScaledMutable
protocol
Protocol for mutable add-scaled! operation.
Implementations may assume that factor is a scalar.
Intended to support optimised implementations for m = m + a * factor
members
add-scaled!
(add-scaled! m a factor)
PAddScaledProduct
protocol
Protocol for add-product operation.
Intended to support optimised implementations for result = m + a * b * factor
members
add-scaled-product
(add-scaled-product m a b factor)
Adds the elementwise product of a, b and a scalar factor to m
PAddScaledProductMutable
protocol
Protocol for mutable add-product! operation.
Intended to support optimised implementations for m = m + a * b * factor
members
add-scaled-product!
(add-scaled-product! m a b factor)
PArrayMetrics
protocol
Option protocol for quick determination of array matrics
members
nonzero-count
(nonzero-count m)
Returns the number of non-zero values in a numerical array. May throw an exception if the array is not numerical.
PAssignment
protocol
Protocol for assigning values element-wise to mutable arrays.
members
assign!
(assign! m source)
Sets all the values in an array from a given source. Source may be a scalar
or any smaller array that can be broadcast to the shape of m.
assign-array!
(assign-array! m arr)
(assign-array! m arr start length)
Sets the elements in an array from a Java array source, in row-major order.
PBlockDiagonalMatrix
protocol
Protocol for construction of a block diagonal matrix.
members
block-diagonal-matrix
(block-diagonal-matrix m blocks)
PBroadcast
protocol
Protocol to support broadcasting over one or more dimensions.
members
broadcast
(broadcast m target-shape)
Broadcasts an array over a desired target shape, which should be larger than the current matrix.
Dimensions should be matched up according to the last dimension.
In order to broadcast sucessfully, the current dimension of the array must be either:
- of size 1
- equal to the size of the dimension in the target shape
- not included in the array (i.e. the target shape has more leading dimensions)
If broadcasting is not possible, an exception must be thrown.
Broadcasting may return either a view with replicated element or a new immutable matrix.
PBroadcastCoerce
protocol
Protocol to broadcast into a given matrix shape and perform coercion in one step.
Equivalent to (coerce m (broadcast-like m a)) but likely to be more efficient.
members
broadcast-coerce
(broadcast-coerce m a)
Broacasts and coerces a to the same shape and implementation as m
PBroadcastLike
protocol
Protocol to broadcast into a given matrix shape. May also perform coercion if needed by the implementation.
members
broadcast-like
(broadcast-like m a)
PCholeskyDecomposition
protocol
Procotol for Cholesky decomposition
members
cholesky
(cholesky m options)
PCoercion
protocol
Protocol to coerce a parameter to a format used by a specific implementation. It is
up to the implementation to determine what parameter types they support.
If the implementation is unable to perform coercion, it must return nil.
Implementations are encouraged to avoid taking a full copy of the data, for performance reasons.
It is preferable to use structural sharing with the original data if possible.
If coercion is impossible (e.g. param has an invalid shape or element types) then the
implementation *may* throw an exception, though it may also return nil to get default behaviour,
which should implement any expected exceptions.
If an implementation implements coercion via copying, then it is recommended that conversion
should be to the most efficient packed representation (i.e. as defined by 'pack')
Implementations must also be able to coerce valid scalar values (presumably via the identity function)
members
coerce-param
(coerce-param m param)
Attempts to coerce param into a matrix format supported by the implementation of matrix m.
May return nil if unable to do so, in which case a default implementation can be used.
PColumnSetting
protocol
Protocol for column setting. Should set a dimension 1 (column) slice to the given column value.
members
set-column
(set-column m i column)
set-column!
(set-column! m i column)
PCompare
protocol
Protocol to allow element-wise comparison of elements in an array or matrix.
members
element-compare
(element-compare a b)
Return the sign (signum) of the element-wise substraction of two scalars,
arrays or matrices i.e., must satisfy (signum (sub A B).
element-eq
(element-eq m a)
Return a binary array or matrix where elements of m equal to a are
represented by 1 and elements not-equal to a are represented as 0.
element-ge
(element-ge m a)
Return a binary array or matrix where elements of m greater-than-or-equal
to a are represented by 1 and elements less than a are represented as 0.
element-gt
(element-gt m a)
Return a binary array or matrix where elements of m greater-than a are
represented by 1 and elements less-than a are represented as 0.
element-if
(element-if m a b)
Element-wise if statement.
Traverse each element, x, of a array or matrix, m. If:
- x > 0, return a (if scalar) or corresponding element of a (if a is an
array or matrix with same shape shape as m).
- x <= 0, return b (if scalar) or corresponding element in b (if b is an
array or matrix with same shape shape as m).
Return an array or matrix with the same shape as m.
element-le
(element-le m a)
Return a binary array or matrix where elements of m less-than-or-equal
to a are represented by 1 and elements greater-than a are represented as 0.
element-lt
(element-lt m a)
Return a binary array or matrix where elements of m less-than a are
represented by 1 and elements greater-than a are represented as 0.
element-ne
(element-ne m a)
Return a binary array or matrix where elements of m not-equal to a are
represented by 1 and elements equal to a are represented as 0.
PComputeMatrix
protocol
Protocol to compute a matrix by calling a function on each indexed location. The function f will be called
as (f x y z ...) for all index values.
members
compute-matrix
(compute-matrix m shape f)
PConversion
protocol
Protocol to allow conversion to Clojure-friendly vector format. Optional for implementers,
however providing an efficient implementation is strongly encouraged to enable fast interop
with Clojure vectors.
members
convert-to-nested-vectors
(convert-to-nested-vectors m)
Converts an array to nested Clojure persistent vectors
PDatasetImplementation
protocol
Protocol for general dataset functionality
members
add-column
(add-column ds col-name col)
Adds column to the dataset
column-names
(column-names ds)
Returns a persistent vector containing column names in the same order as they are placed in the dataset
columns
(columns ds)
Returns a persistent vector containing columns in the same order they are placed in the dataset
join-columns
(join-columns ds1 ds2)
Returns a dataset created by combining the columns of the given datasets
join-rows
(join-rows ds1 ds2)
Returns a dataset created by combining the rows of the given datasets
merge-datasets
(merge-datasets ds1 ds2)
Returns a dataset created by combining columns of the given datasets. In case of columns with duplicate names, last-one-wins strategy is applied
rename-columns
(rename-columns ds col-map)
Renames columns based on map of old new column name pairs
replace-column
(replace-column ds col-name vs)
Replaces column in a dataset with new values
row-maps
(row-maps ds)
Returns seq of maps with row values
select-columns
(select-columns ds cols)
Produces a new dataset with the columns in the specified order
select-rows
(select-rows ds rows)
Produces a new dataset with specified rows
to-map
(to-map ds)
Returns map of columns with associated list of values
PDense
protocol
Protocol for constructing a dense array from the given data.
members
dense
(dense m)
Attempts to make array into a dense format. Must return the same array unchanged if not possible.
dense-coerce
(dense-coerce m data)
Attempts to coerce data to a dense array of implementation m. May return nil if not supported
PDimensionImplementation
protocol
EXPERIMENTAL: Protocol for querying multi-dimensioned datasets
members
column-name
(column-name ds idx)
returns the name of the column (dimension 1) at a specified column index
dimension-name
(dimension-name ds idx dim)
Returns the name of the specified index along a given numbered dimension
row-name
(row-name ds idx)
Returns the name of the row (dimension 0) at a specified index
PDimensionInfo
protocol
Protocol to return standard dimension information about an array.
dimensionality and dimension-count are mandatory for implementations
members
dimension-count
(dimension-count m dimension-number)
Returns the size of a specific dimension. Must throw an exception if the array does not
have the specified dimension.
dimensionality
(dimensionality m)
Returns the number of dimensions of an array, as an integer (greater than or equal to zero).
get-shape
(get-shape m)
Returns the shape of the array, typically as a Java array or sequence of dimension sizes.
Implementations are free to choose what type is used to represent the shape, but it must
contain only integer values and be traversable as a sequence via clojure.core/seq
is-scalar?
(is-scalar? m)
Tests whether an object is a scalar value, i.e. a value that can exist at a
specific position in an array.
is-vector?
(is-vector? m)
Tests whether an object is a vector (1D array)
PDimensionLabels
protocol
Protocol for arrays supporting labelled dimensions
members
label
(label m dim i)
Returns the label at a specific index along the given dimension
labels
(labels m dim)
Returns all labels along a given dimension, as a vector
PDoubleArrayOutput
protocol
Protocol for getting element data as a flattened double array
members
as-double-array
(as-double-array m)
Returns the internal double array used by m. If no such array is used, returns nil.
Provides an opportunity to avoid copying the internal array.
to-double-array
(to-double-array m)
Returns a double array containing the values of m in row-major order. May or may not be
the internal double array used by m, depending on the implementation.
PEigenDecomposition
protocol
Procotol for Eigenvalue decomposition
PElementCount
protocol
Protocol to return the total count of elements in matrix. Result may be any integer type,
typically a java.lang.Long
members
element-count
(element-count m)
PElementMinMax
protocol
Protocol to return the minimum and maximum elements in a numerical array. Must throw an exception
if the array is not numerical.
members
element-clamp
(element-clamp m a b)
Returns a matrix where the elements are clamped to be within lower and
upper bounds specified by a and b, respectively.
element-max
(element-max m)
element-min
(element-min m)
persistent-vector-coerce
(persistent-vector-coerce x)
Coerces a data structure to nested persistent vectors
PExponent
protocol
Protocol to support the 'pow' function. Should raise every element of a matrix to a
given exponent. Default implementation uses Java's Math/pow function which is appropriate for
double values: arrays supporting arbitrary precision numbers or complex types will need to
provide their own implementation.
members
element-pow
(element-pow m exponent)
PFunctionalOperations
protocol
Protocol to allow functional-style operations on matrix elements.
members
element-map
(element-map m f)
(element-map m f a)
(element-map m f a more)
Maps f over all elements of m (and optionally other matrices), returning a new matrix.
f is expected to produce elements of a type supported by the implementation of m - failure
to do so may cause an error.
element-map!
(element-map! m f)
(element-map! m f a)
(element-map! m f a more)
Maps f over all elements of m (and optionally other matrices), mutating the elements of m in place.
Must throw an exception if m is not mutable.
f is expected to produce elements of a type supported by the implementation of m - failure
to do so may cause an error.
element-reduce
(element-reduce m f)
(element-reduce m f init)
Reduces with the function f over all elements of m.
element-seq
(element-seq m)
Must return a seqable object containing all elements of the matrix, in row-major order.
PGenericOperations
protocol
Protocol for returning the generic numerical functions of a matrix implementation
members
generic-add
(generic-add m)
Generic 'add' function for numerical values. Must satisfy (equals x (add zero x)).
generic-div
(generic-div m)
Generic 'div' function for numerical values.
generic-mul
(generic-mul m)
Generic 'mul' function for numerical values. Must satisfy (equals x (mul one x)).
generic-negate
(generic-negate m)
Generic 'negate' function for numerical values.
PGenericValues
protocol
Protocol for returning the generic/default values of a matrix implementation
members
generic-one
(generic-one m)
Generic 'one' value for numerical arrays. Must satisfy (equals m (mul m one)).
generic-value
(generic-value m)
Generic value for a new array. Likely to be zero or nil.
generic-zero
(generic-zero m)
Generic 'zero' value for numerical arrays. Must satisfy (equals m (add m zero)).
PImmutableAssignment
protocol
Protocol for assigning values element-wise to an array, broadcasting as needed.
members
assign
(assign m source)
Sets all the values in an array from a given source. Source may be a scalar
or a smaller array that can be broadcast to the shape of m.
PImmutableMatrixConstruction
protocol
Protocol for creating an immutable copy of a matrix. If implemented, must return a fully immutable
copy of the given matrix.
The default implementation will attempt to choose a suitable immutable matrix implementation.
members
immutable-matrix
(immutable-matrix m)
PImplementation
protocol
Protocol for general implementation functionality. Required to support implementation metadata and
matrix construction.
members
construct-matrix
(construct-matrix m data)
Returns a new n-dimensional array containing the given data. data should be in the form of either
nested sequences or a valid existing array.
The return value should be in the preferred format of the given implementation. If the implementation
does not support the required dimensionality or element type then it may either:
- Throw an error
- Return nil to indicate that a default implementation should be used instead
0-dimensional arrays / scalars are permitted.
implementation-key
(implementation-key m)
Returns a keyword representing this implementation, that can be used to request array instances or
look up implementation metadata etc.
Each implementation should have one unique key. Official mapping of implementation keywords is
maintained in the var clojure.core.matrix.implementations/KNOWN-IMPLEMENTATIONS.
new-matrix
(new-matrix m rows columns)
Returns a new matrix (regular 2D matrix) with the given number of rows and columns, filled with numeric zero.
new-matrix-nd
(new-matrix-nd m shape)
Returns a new general matrix of the given shape.
Must return nil if the shape is not supported by the implementation.
Shape can be any sequence of integer dimension sizes (including 0 dimensions).
new-vector
(new-vector m length)
Returns a new vector (1D column matrix) of the given length, filled with numeric zero.
supports-dimensionality?
(supports-dimensionality? m dimensions)
Returns true if the implementation supports matrices with the given number of dimensions.
PIndexedAccess
protocol
Protocol for indexed read access to arrays, matrices and vectors. Indexing values can
be assumed to be integers. indexes may be any sequence or Java array of index values.
members
get-2d
(get-2d m row column)
PIndexedSetting
protocol
Protocol for indexed 'setter' operations. These are like Clojure's 'assoc'
function, i.e. they return an updated copy of the original array, which is itself unchanged.
Should be supported for any immutable array type.
members
is-mutable?
(is-mutable? m)
Returns true if the matrix is mutable and therefore supports direct mutable operations, e.g. add!
set-2d
(set-2d m row column v)
set-nd
(set-nd m indexes v)
PIndexedSettingMutable
protocol
Protocol for indexed mutable setter access to matrices and vectors.
Must be supported for any mutable matrix type.
members
set-2d!
(set-2d! m row column v)
set-nd!
(set-nd! m indexes v)
PIndexImplementation
protocol
Protocol for determining if an object is a valid index. Implementations may implement this protocol to support their own index types.
members
index-coerce
(index-coerce m a)
index-from-ints
(index-from-ints m xs)
index-from-longs
(index-from-longs m xs)
index-to-ints
(index-to-ints m)
index-to-longs
(index-to-longs m)
index?
(index? m)
Returns true if the argument is a valid index, false otherwise
PIndicesAccess
protocol
Protocol for getting elements of an array at the specified indices.
members
get-indices
(get-indices a indices)
returns a 1-d array with the elements of a at indices
PIndicesSetting
protocol
Protocol for setting elements of an array at the specified indices
members
set-indices
(set-indices a indices values)
sets the elements from a at indices to values
set-indices!
(set-indices! a indices values)
destructively sets the elements from a at indices to values
PLeastSquares
protocol
Protocol for computing least-square solution to a linear matrix equation
members
least-squares
(least-squares a b)
PLogistic
protocol
Protocol to support element-wise logistic function on a numerical array.
PLogisticMutable
protocol
Protocol to support mutable element-wise logistic function on a numerical array.
PLUDecomposition
protocol
Protocol for LU decomposition
PMapIndexed
protocol
Protocol for map-indexed operation on matrices
members
element-map-indexed
(element-map-indexed m f)
(element-map-indexed m f a)
(element-map-indexed m f a more)
Maps f over all elements of m (and optionally other matrices), returning a new matrix.
f is expected to accept an index vector and the current element value, and produce
elements of a type supported by the implementation of m - failure
to do so may cause an error.
element-map-indexed!
(element-map-indexed! m f)
(element-map-indexed! m f a)
(element-map-indexed! m f a more)
Maps f over all elements of m (and optionally other matrices), mutating the elements of m in place.
Must throw an exception if m is not mutable.
f is expected to accept an index vector and the current element value, and produce
elements of a type supported by the implementation of m - failure
to do so may cause an error.
PMathsFunctions
protocol
Protocol to support mathematical functions applied element-wise to a numerical array.
PMathsFunctionsMutable
protocol
Protocol to support mutable mathematical functions applied element-wise to a numerical array.
members
to-degrees!
(to-degrees! m)
to-radians!
(to-radians! m)
PMatrixAdd
protocol
Protocol to support addition and subtraction on arbitrary matrices.
These are elementwise operations that should support broadcasting.
members
matrix-add
(matrix-add m a)
matrix-sub
(matrix-sub m a)
PMatrixAddMutable
protocol
Protocol to support mutable addition and subtraction
members
matrix-add!
(matrix-add! m a)
matrix-sub!
(matrix-sub! m a)
PMatrixCloning
protocol
Protocol for cloning a matrix value. The new clone must be mutable if the original
matrix is mutable, i.e. mutating the clone must not affect the original. The copy should be shallow, if applicable.
members
clone
(clone m)
Returns a clone of an array. Must be a new independent (non-view)
instance if the array is mutable.
PMatrixColumns
protocol
Protocol for accessing columns of a matrix
members
get-columns
(get-columns m)
Returns the columns of a matrix, as a sequence
PMatrixDivide
protocol
Protocol to support element-wise division operator.
One-arg version returns the reciprocal of all elements.
members
element-divide
(element-divide m)
(element-divide m a)
PMatrixDivideMutable
protocol
Protocol to support mutable element-wise division operater.
One-arg version computes the reciprocal of all elements.
members
element-divide!
(element-divide! m)
(element-divide! m a)
PMatrixEquality
protocol
Protocol for numerical array equality operations.
members
matrix-equals
(matrix-equals a b)
Return true if a equals b, i.e. if a and b have the same shape and all elements are equal.
Must use numerical value comparison on numbers (==) to account for matrices that may hold a mix of
numercial types (e.g. java.lang.Long and java.lang.Double). Implementations that only support doubles
should use Number.doubleValue() to get a numeric value to compare.
May throw an exception if the matrices are non-numeric
PMatrixEqualityEpsilon
protocol
Protocol for numerical array equality operations with a specified tolerance. Arrays are defined as equal
if the array shapes are the same and and for all corresponding elements ai and bi we have: |ai-bi|<=eps
Should be equivalent to PMatrixEquality when eps is zero.
members
matrix-equals-epsilon
(matrix-equals-epsilon a b eps)
As matrix-equals, but provides a numerical tolerance for equality testing.
PMatrixMultiply
protocol
Protocol to support matrix multiplication on numerical arrays.
Implementation may return nil if the implementation does not support one of the parameters, in
which case a more general operation will be attempted.
members
element-multiply
(element-multiply m a)
matrix-multiply
(matrix-multiply m a)
PMatrixMultiplyMutable
protocol
Protocol to support mutable matrix multiplication on an arbitrary matrix, vector or scalar
members
element-multiply!
(element-multiply! m a)
matrix-multiply!
(matrix-multiply! m a)
PMatrixMutableScaling
protocol
Protocol to support mutable array scaling by scalar values.
members
pre-scale!
(pre-scale! m factor)
PMatrixOps
protocol
Protocol to support common 2D numerical matrix operations
members
determinant
(determinant m)
Returns the determinant of a matrix. May return nil if the implementation is unable
to compute determinants.
Must throw an error if the matrix is not square (i.e. different number of rows and columns)
inverse
(inverse m)
Returns the invese of a matrix. Should return nil if m is not invertible.
trace
(trace m)
Returns the trace of a matrix (sum of elements on main diagonal.
Must throw an error if the matrix is not square (i.e. different number of rows and columns)
PMatrixPredicates
protocol
Protocol for matrix predicates like identity-matrix? or zero-matrix?
members
identity-matrix?
(identity-matrix? m)
Returns true if the matrix m is an identity matrix
symmetric?
(symmetric? m)
Returns true if matrix m is symmetric
zero-matrix?
(zero-matrix? m)
Returns true if all the elements of matrix m are zeros
PMatrixProducts
protocol
Protocol for general inner and outer products of numerical arrays.
Products should use + and * as normally defined for numerical types
members
inner-product
(inner-product m a)
Returns the inner product of two numerical arrays.
outer-product
(outer-product m a)
Returns the outer product of two numerical arrays.
PMatrixRank
protocol
Protocol to support computing the rank (number of linearly independent rows) in a matrix
members
rank
(rank m)
Returns the rank of a matrix
PMatrixRows
protocol
Protocol for accessing rows of a matrix
members
get-rows
(get-rows m)
Returns the rows of a matrix, as a sequence
PMatrixScaling
protocol
Protocol to support numerical array scaling by scalar values. Provided because array classes may have
efficient specialised scaling operaions.
Works according the the default definition of multiplication for the matrix class
(usually numerical, i.e. equivalent to clojure.core/+)
members
pre-scale
(pre-scale m constant)
Pre-multiplies the array with the scalar constant. This is the same as scale for arrays
where multiplication is commutative, but may be different for special kinds of scalars.
scale
(scale m constant)
Multiplies a array by the scalar constant,
PMatrixSlices
protocol
Protocol to support getting slices of an array. If implemented, must return either a view, a scalar
or an immutable sub-matrix: it must *not* return copied data. i.e. making a full copy must be avoided.
members
get-column
(get-column m i)
Gets a column of a matrix with the given row index.
get-major-slice
(get-major-slice m i)
Gets the major slice of an array with the given index. For a 2D matrix, equivalent to get-row
get-row
(get-row m i)
Gets a row of a matrix with the given row index.
get-slice
(get-slice m dimension i)
Gets a slice of an array along a specified dimension with the given index.
PMatrixSubComponents
protocol
Protocol for picking out subsections of a 2D matrix. Should return a mutable view if possible.
The default implementation creates a new vector containing the diagonal values.
members
main-diagonal
(main-diagonal m)
Returns the main (leading) diagonal of a matrix.
PMatrixTypes
protocol
members
diagonal?
(diagonal? m)
Returns true if the matrix is diagonal, i.e. zero everywhere except the main diagonal
lower-triangular?
(lower-triangular? m)
Returns true if the matrix m is lower triangualar
orthogonal?
(orthogonal? m eps)
Returns true if the matrix is orthogonal
positive-definite?
(positive-definite? m)
Returns true if the matrix is positive definite
positive-semidefinite?
(positive-semidefinite? m)
Returns true if the matrix is positive semidefinite
upper-triangular?
(upper-triangular? m)
Returns true if the matrix m is upper triangualar
PMutableCoercion
protocol
Protocol for coercing to a mutable format. May return the original array, if it is already fully mutable,
otherwise should return a fully mutable copy of the array.
May return nil to indicate that a default implementation should be used.
The default implementation will attempt to choose a suitable mutable matrix implementation.
members
ensure-mutable
(ensure-mutable m)
PMutableFill
protocol
members
fill!
(fill! m value)
Fills the array with the given scalar value.
PMutableMatrixConstruction
protocol
Protocol for creating a mutable copy of a matrix. If implemented, must return either a fully mutable
copy of the given matrix, or nil if not possible.
The default implementation will attempt to choose a suitable mutable matrix implementation.
members
mutable-matrix
(mutable-matrix m)
PMutableVectorOps
protocol
Protocol for mutable versions of common vector operations
PNative
protocol
Protocol for creating and handling native arrays. Implementations must return a native format array if they
are able to, or nil otherwise.
members
native
(native m)
Attempts to coerce data to a native array of implementation m. May return nil if not supported
native?
(native? m)
Returns true if an array is in a native format, false otherwise.
PNegation
protocol
members
negate
(negate m)
Returns a new numerical array with all elements negated.
PNewSparseArray
protocol
Protocol for constructing sparse arrays. Should return nil if the sparse array shape is not supported.
members
new-sparse-array
(new-sparse-array m shape)
Creates a new sparse array with the given shape.
PNonZeroIndices
protocol
Protocol for getting non-zero indices of an array
members
non-zero-indices
(non-zero-indices m)
Gets the non-zero indices of an array.
- For a 1D vector, returns an ordered index list.
- For a higher dimensional array, returns the non-zero-indices for each slice in row-major order.
PNorm
protocol
Protocol for matrix and vector norms
PNumerical
protocol
Protocol for identifying numerical arrays. Should return true if every element in the
array is guaranteed to be a valid numerical value.
members
numerical?
(numerical? m)
Returns true if the array is numerical.
PObjectArrayOutput
protocol
Protocol for getting element data as a flattened object array
members
as-object-array
(as-object-array m)
Returns the internal object array used by m. If no such array is used, returns nil.
Provides an opportunity to avoid copying the internal array.
to-object-array
(to-object-array m)
Returns an object array containing the values of m in row-major order. May or may not be
the internal object array used by m, depending on the implementation.
POrder
protocol
Protocol for matrix reorder.
By default, re-orders along the first (major) dimension, but may reorder along any dimension by
specifiying the dimension argument.
Indicies can be any seqable object containing the indices along the specified dimension to select.
An index can be selected multiple times (which created repreated slices), or not at all (which excludes
the slice from the result).
Some implementation may implement re-ordering using lightweight or mutable views over the original array
data.
members
order
(order m indices)
(order m dimension indices)
PPack
protocol
Protocol to efficiently pack an array, according to the most efficient representation for a given
implementation.
Definition of pack is up to the implementation to interpret, but the general rules are:
1. Must not change the value of the array for comparison purposes
2. Must not change the shape of the array
3. May preserve sparse representation
4. Should convert to most efficient format for common operations (e.g. mget, inner-product)
PPermutationMatrix
protocol
Protocol for construction of a permutation matrix.
members
permutation-matrix
(permutation-matrix m permutation)
PQRDecomposition
protocol
Protocol for QR decomposition
PReshaping
protocol
Protocol to reshape matrices. Should support any new shape allowed by the implementation.
Must preserve row-major ordering of matrix elements.
If the original matrix is mutable, must return a new mutable copy of data.
If the new shape has less elements than the original shape, it is OK to truncate the remaining elements.
If the new shape requires more elements than the original shape, should throw an exception.
PRotate
protocol
Rotates an array along a specified dimension by the given number of places.
Rotating a dimension that does not exist has no effect on the array.
members
rotate
(rotate m dim places)
PRotateAll
protocol
Rotates an array using the specified shifts for each dimension.
shifts may be any sequence of integer shift amounts.
members
rotate-all
(rotate-all m shifts)
PRowColMatrix
protocol
Protocol to support construction of row and column matrices from 1D vectors.
A vector of length N should be converted to a 1xN or Nx1 matrix respectively.
Should throw an error if the data is not a 1D vector
members
column-matrix
(column-matrix m data)
row-matrix
(row-matrix m data)
PRowOperations
protocol
Protocol for elementary row operations
members
add-row
(add-row m i j k)
Returns a new matrix with row i added to row j times k
multiply-row
(multiply-row m i k)
Returns a new matrix with row i multiplied by k
swap-rows
(swap-rows m i j)
Returns a new matrix with rows i and j swapped
PRowSetting
protocol
Protocol for row setting. Should set a dimension 0 (row) slice to thegiven row value.
members
set-row!
(set-row! m i row)
PSameShape
protocol
Protocol to test if two arrays have the same shape. Implementations may have an optimised
method for shape equality tests, and this is a frequently required operations so it may
make sense to provide an optimised implementation.
members
same-shape?
(same-shape? a b)
PScaleAdd
protocol
Protocol to support the mutable scale-add! operation. This is a common operation that may be
optimised by the underlying implementation. Implementations should consider extra optimisations for
specific constant values e.g. 0.0 and 1.0 but this is not mandatory.
members
scale-add!
(scale-add! m1 a m2 b constant)
Scales array m1 in place by factor b, then adds array m2 scaled by factor b, then adds the constant
PSelect
protocol
Protocol for the sel function. See the docstring for clojure.core.matrix/select for
more information on possible argument values.
members
select
(select a args)
selects all elements at indices which are in the cartesian product of args
PSelectView
protocol
Protocol for the sel function. Like PSelect, but guarantees an mutable view.
If not supported by the implementation, may return nil to indicate that a default mutable view
should be created.
members
select-view
(select-view a args)
selects all elements at indices which are in the cartesian product of args
PSetSelection
protocol
Protocol for setting the elements of an array returned by (select a args) to values.
See the docstring for clojure.core.matrix/select for more information on possible argument values.
members
set-selection
(set-selection a args values)
sets the elements in the selection of a to values
PShift
protocol
Rotates an array using the specified shifts for each dimension. Newly shifted in elements
should be filled with the default scalar value (usually zero).
members
shift
(shift m dim places)
Shift along a single specified dimension
shift-all
(shift-all m shifts)
Shift along all specified dimensions as a single operation.
`shifts` may be any sequence of integer shift amounts.
PSliceJoin
protocol
Protocol for concatenating / joining arrays.
members
join
(join m a)
Concatenates a to m, along the major slice dimension
PSliceJoinAlong
protocol
Protocol for concatenating / joining arrays.
members
join-along
(join-along m a dim)
Concatenates a to m, along the slice dimension dim
PSliceSeq
protocol
Returns the row-major slices of the array as a sequence.
These must be views or immutable sub-arrays for higher order slices, or scalars
for the slices of a 1D vector.
The default implementation uses get-major-slice-view to obtain the slices.
members
get-major-slice-seq
(get-major-slice-seq m)
Gets a sequence of all major array slices
PSliceSeq2
protocol
Returns slices of the array as a sequence.
These must be views or immutable sub-arrays for higher order slices, or scalars
for the slices of a 1D vector.
members
get-slice-seq
(get-slice-seq m dim)
Gets a sequence of all array slices
PSliceView
protocol
Protocol for quick view access into a row-major slices of an array. If implemented, must return
either a view or an immutable sub-matrix: it must *not* return copied data.
If the matrix is mutable, it must return a mutable view.
The default implementation creates a wrapper view.
members
get-major-slice-view
(get-major-slice-view m i)
Gets a view of a major array slice
PSliceView2
protocol
Protocol for quick view access into a slices of an array. If implemented, must return
either a view or an immutable sub-matrix: it must *not* return copied data.
If the matrix is mutable, it must return a mutable view.
The default implementation creates a wrapper view.
members
get-slice-view
(get-slice-view m dim i)
Gets a view of an array slice along the specified dimension.
PSliceViewSeq
protocol
Returns the row-major slice views of the array.
These must be arrays if the array is mutable, i.e. slices of a 1D vector
must be 0-dimensional mutable arrays.
members
get-major-slice-view-seq
(get-major-slice-view-seq m)
Gets a sequence of all major array slices
PSolveLinear
protocol
Protocol for solving linear matrix equation or system of linear scalar equations
PSparse
protocol
Protocol for constructing a sparse array from the given data. Implementations should
consider the possibility that data may be a large lazy sequence, possibly larger than memory, so should ideally
attempt to construct the sparse matrix incrementally without realising the whole sequence at once.
May return nil if no sparse conversion is available.
members
sparse
(sparse m)
Attempts to make array into a sparse format. Must return the same array unchanged if not possible.
sparse-coerce
(sparse-coerce m data)
Attempts to coerce data to a sparse array of implementation m. May return nil if not supported
PSparseArray
protocol
Protocol for determining if an array is in a sparse format. It is up to the implementation to define
its own sparse formats, but in general the intention should be that a sparse array uses significantly
less storage than an equivalent dense array, assuming a high proportion of zero values in the array.
members
is-sparse?
(is-sparse? m)
Returns true if the array is in a sparse format, as defined by the implementation.
PSpecialisedConstructors
protocol
Protocol for construction of special matrices.
members
diagonal-matrix
(diagonal-matrix m diagonal-values)
Create a diagonal matrix with the specified leading diagonal values
identity-matrix
(identity-matrix m dims)
Create a 2D identity matrix with the given number of dimensions
PSquare
protocol
Protocol to support element-wise squaring of a numerical array.
PSubMatrix
protocol
Protocol to get a subarray of another array. dim-ranges should be a sequence of [start len]
pairs, one for each dimension. If a pair is nil, it should be interpreted to take the whole dimension.
Returning a mutable view is preferred, if the implementation supports this.
members
submatrix
(submatrix d dim-ranges)
PSubVector
protocol
Protocol for getting a sub-vector view of a vector. Must return a mutable view
if the original vector is mutable. Should throw an exception if the specified
subvector is out of bounds for the target vector.
members
subvector
(subvector m start length)
Gets a sub-vector of a vector. Must return a view if the vector is mutable.
PSummable
protocol
Protocol to support the summing of all elements in an array.
The array must hold numeric values only, or an exception will be thrown.
members
element-sum
(element-sum m)
PSVDDecomposition
protocol
Protocol for SVD decomposition
PTranspose
protocol
Protocol for array transpose operation
members
transpose
(transpose m)
Returns the transpose of a matrix. Equivalent to reversing the "shape".
Note that:
- The transpose of a scalar is the same scalar
- The transpose of a 1D vector is the same 1D vector
- The transpose of a 2D matrix swaps rows and columns
PTransposeInPlace
protocol
Protocol for mutable 2D matrix transpose in place
members
transpose!
(transpose! m)
Transposes a mutable 2D matrix in place
PTypeInfo
protocol
Protocol for querying the type of matrix elements. If not provided, the default implementation will
return java.lang.Object, and the matrix object is assumed to accept any type of value.
If a matrix is primitive-backed, it should return the appropriate primitive type e.g. Double/TYPE.
members
element-type
(element-type m)
PValidateShape
protocol
Optional protocol to validate the shape of a matrix. If the matrix has an incorrect shape, should
throw an error. Otherwise it should return the correct shape.
members
validate-shape
(validate-shape m)
Returns the shape of the array, performing validation and throwing an error if the shape is inconsistent
PValueEquality
protocol
Protocol for comparing two arrays, with the semantics of clojure.core/=.
Must return false if the arrays are not of equal shape, or if any elements are not equal.
members
value-equals
(value-equals m a)
Returns true if two arrays are equal both in shape and according to clojure.core/= for each element.
PVectorCross
protocol
members
cross-product
(cross-product a b)
Cross product of two vectors
cross-product!
(cross-product! a b)
Calculate cross product of two vectors, storing the result in the first vector
PVectorDistance
protocol
members
distance
(distance a b)
Euclidean distance of two vectors.
PVectorisable
protocol
Protocol to return an array as a flattened vector of all elements.
Implementations are encouraged to avoid taking a full copy of all data
(e.g. by using structural sharing or views).
members
to-vector
(to-vector m)
Returns an array as a single flattened vector
PVectorOps
protocol
Protocol to support common numerical vector operations.
members
length
(length a)
Euclidian length of a vector.
length-squared
(length-squared a)
Squared Euclidean length of a vector.
normalise
(normalise a)
Returns a new vector, normalised to length 1.0
vector-dot
(vector-dot a b)
Numerical dot product of two vectors. Must return a scalar value if the two parameters are
vectors of equal length.
If the vectors are of unequal length, should throw an exception (however returning nil is
also acceptable).
Otherwise the implementation may optionally either return nil or compute a higher dimensional
inner-product (if it is able to do so).
PVectorView
protocol
members
as-vector
(as-vector m)
Returns a view of an array as a single flattened vector. May return the vector itself
if it is already a 1D vector.
PZeroCount
protocol
Protocol for counting the number of zeros in a numerical array. Must return an integer value
representing the precise number of zeros.
members
zero-count
(zero-count m)
Returns the number of zeros in the array
PZeroDimensionAccess
protocol
Protocol for accessing the scalar value in zero-dimensional arrays. Zero dimensional arrays differ
from scalar values in the following two senses:
- They may be mutable (in which case set-0d! is expected to work)
- They are not considered themselves to be scalars. Hence you must use get-0d to access the
contained scalar value
members
get-0d
(get-0d m)
Gets the scalar value in an 0d array.
set-0d!
(set-0d! m value)
Sets the scalar value in the 0d array to a given value. Throws an error if not mutable.
PZeroDimensionConstruction
protocol
members
new-scalar-array
(new-scalar-array m)
(new-scalar-array m value)
Construct a new zero-dimensional array with the specified scalar value (zero if not specified)
PZeroDimensionSet
protocol
Protocol for setting the scalar value in zero-dimensional arrays.
members
set-0d
(set-0d m value)
Sets the scalar value in a 0-d array, returning a new 0-d array
same-shapes?
(same-shapes? arrays)
Returns truthy if a sequence of arrays all have the same shape.
supports-type?
(supports-type? m klass)
Checks if an array can contain a specified Java type.