Back to godoc.org
github.com/maxvdkolk/sparse

Package sparse

v0.0.0-...-d6ed124
Latest Go to latest

The latest major version is .

Published: Jun 10, 2020 | License: MIT | Module: github.com/maxvdkolk/sparse

Overview

Package sparse provides implementations of selected sparse matrix formats. Matrices and linear algebra are used extensively in scientific computing and machine learning applications. Large datasets are analysed comprising vectors of numerical features that represent some object. The nature of feature encoding schemes, especially those like "one hot", tends to lead to vectors with mostly zero values for many of the features. In text mining applications, where features are typically terms from a vocabulary, it is not uncommon for 99% of the elements within these vectors to contain zero values.

Sparse matrix formats take advantage of this fact to optimise memory usage and processing performance by only storing and processing non-zero values.

Sparse matrix formats can broadly be divided into 3 main categories:

1. Creational - Sparse matrix formats suited to construction and building of matrices. Matrix formats in this category include DOK (Dictionary Of Keys) and COO (COOrdinate aka triplet).

2. Operational - Sparse matrix formats suited to arithmetic operations e.g. multiplication. Matrix formats in this category include CSR (Compressed Sparse Row aka CRS - Compressed Row Storage) and CSC (Compressed Sparse Column aka CCS - Compressed Column Storage)

3. Specialised - Specialised matrix formats suiting specific sparsity patterns. Matrix formats in this category include DIA (DIAgonal) for efficiently storing and manipulating symmetric diagonal matrices.

A common practice is to construct sparse matrices using a creational format e.g. DOK or COO and then convert them to an operational format e.g. CSR for arithmetic operations.

All sparse matrix implementations in this package implement the Matrix interface defined within the gonum/mat package and so may be used interchangeably with matrix types defined within the package e.g. mat.Dense, mat.VecDense, etc.

Example

Code:

package main

import (
	"fmt"
	"github.com/james-bowman/sparse"
)

func main() {
	// Construct a new 3x2 DOK (Dictionary Of Keys) matrix
	dokMatrix := sparse.NewDOK(3, 2)

	// Populate it with some non-zero values
	dokMatrix.Set(0, 0, 5)
	dokMatrix.Set(2, 1, 7)

	// Demonstrate accessing values (could use mat.Formatted() to
	// pretty print but this demonstrates element access)
	m, n := dokMatrix.Dims()
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%.0f,", dokMatrix.At(i, j))
		}
		fmt.Printf("\n")
	}

	// Convert DOK matrix to CSR (Compressed Sparse Row) matrix
	// just for fun (not required for upcoming multiplication operation)
	csrMatrix := dokMatrix.ToCSR()

	// Create a random 2x3 COO (COOrdinate) matrix with
	// density of 0.5 (half the elements will be non-zero)
	cooMatrix := sparse.Random(sparse.COOFormat, 2, 3, 0.5)

	// Convert CSR matrix to Gonum mat.Dense matrix just for fun
	// (not required for upcoming multiplication operation)
	// then transpose so it is the right shape/dimensions for
	// multiplication with the original CSR matrix
	denseMatrix := csrMatrix.ToDense().T()

	// Multiply the 2 matrices together and store the result in the
	// sparse receiver (multiplication with sparse product)
	var csrProduct sparse.CSR
	csrProduct.Mul(csrMatrix, cooMatrix)

	// As an alternative, use the sparse BLAS routines for efficient
	// sparse matrix multiplication with a Gonum mat.Dense product
	// (multiplication with dense product)
	denseProduct := sparse.MulMatMat(false, 1, csrMatrix, denseMatrix, nil)
	rows, cols := denseProduct.Dims()
	if rows != 2 && cols != 3 {
		fmt.Printf("Expected product 2x3 but received %dx%d\n", rows, cols)
	}

}
5,0,
0,0,
0,7,

Index

Examples

Constants

const (
	// DenseFormat is an enum value representing Dense matrix format
	DenseFormat DenseType = iota

	// DOKFormat is an enum value representing DOK matrix format
	DOKFormat DOKType = iota

	// COOFormat is an enum value representing COO matrix format
	COOFormat COOType = iota

	// CSRFormat is an enum value representing CSR matrix format
	CSRFormat CSRType = iota

	// CSCFormat is an enum value representing CSC matrix format
	CSCFormat CSCType = iota
)

func Dot

func Dot(a, b mat.Vector) float64

Dot returns the sum of the element-wise product (dot product) of a and b. Dot panics if the matrix sizes are unequal. For sparse vectors, Dot will only process non-zero elements otherwise this method simply delegates to mat.Dot()

func MulMatMat

func MulMatMat(transA bool, alpha float64, a BlasCompatibleSparser, b mat.Matrix, c *mat.Dense) *mat.Dense

MulMatMat (c = alpha * a * b + c) performs sparse matrix multiplication with another matrix and stores the result in a mat.Dense matrix. c is a *mat.Dense, if c is nil, a new mat.Dense of the correct dimensions (Ar x Bc) will be allocated and returned as the result from the function. b is an implementation of mat.Matrix and a is a sparse matrix of type CSR, CSC or a format that implements the BlasCompatibleSparser interface. Matrix A will be scaled by alpha. If transA is true, the matrix A will be transposed as part of the operation. The function will panic if Ac != Br or if (C != nil and (ar != Cr or Bc != Cc))

func MulMatRawVec

func MulMatRawVec(lhs *CSR, rhs []float64, out []float64)

MulMatRawVec computes the matrix vector product between lhs and rhs and stores the result in out

func MulMatSparseVec

func MulMatSparseVec(alpha float64, a mat.Matrix, v *Vector, c *mat.VecDense) *mat.VecDense

MulMatSparseVec (c = alpha * a * v + c) multiplies a dense matrix by a sparse vector and stores the result in mat.VecDense. c is a *mat.VecDense, if c is nil, a new mat.VecDense of the correct size will be allocated and returned as the result from the function. a*v will be scaled by alpha. The function will panic if ac != |v| or if (C != nil and |c| != ar). Note this is not a Sparse BLAS routine -- that library does not cover this case. This is a lookalike function in the Sparse BLAS style. As a and c are dense there is limited benefit to including alpha and c; this is done for consistency rather than performance.

func MulMatVec

func MulMatVec(transA bool, alpha float64, a BlasCompatibleSparser, x mat.Vector, y *mat.VecDense) *mat.VecDense

MulMatVec (y = alpha * a * x + y) performs sparse matrix multiplication with a vector and stores the result in a mat.VecDense vector. y is a *mat.VecDense, if c is nil, a new mat.VecDense of the correct dimensions (Ac x 1) will be allocated and returned as the result of the function. x is an implementation of mat.Vector and a is a sparse matri of type CSR, CSC or a format that implements the BlasCompatibleSparser interface. Matrix A will be scaled by alpha. If transA is true, the matrix A will be transposed as part of the operation. The function will panic Ac != len(x) or if (y != nil and (Ac != len(y)))

func Norm

func Norm(m mat.Matrix, L float64) float64

Norm returns the norm of the matrix as a scalar value. This implementation is able to take advantage of sparse matrix types and only process non-zero values providing the supplied matrix implements the Normer interface. If the supplied matrix does not implement Normer then the function will invoke mat.Norm() to process the matrix.

func Random

func Random(t MatrixType, r int, c int, density float32) mat.Matrix

Random constructs a new matrix of the specified type e.g. Dense, COO, CSR, etc. It is constructed with random values randomly placed through the matrix according to the matrix size, specified by dimensions r * c (rows * columns), and the specified density of non zero values. Density is a value between 0 and 1 (0 >= density >= 1) where a density of 1 will construct a matrix entirely composed of non zero values and a density of 0 will have only zero values.

type Binary

type Binary struct {
	// contains filtered or unexported fields
}

Binary is a Binary Matrix or Bit Matrix type. Although part of the sparse package, this type is not sparse itself and stores all bits even 0s. However, as it makes use of 64 bit integers to store each set of 64 bits and then bitwise operators to manipulate the elements it will be more efficient in terms of both storage requirements and performance than a slice of bool values (8 bits per element) or even a typical Dense matrix of float64 elements. A compressed bitmap scheme could be used to take advantage of sparseness but may have an associated overhead.

func NewBinary

func NewBinary(r, c int, vecs []BinaryVec) *Binary

NewBinary constructs a new Binary matrix or r rows and c columns. If vecs is not nil, it will be used as the underlying binary column vectors. If vecs is nil, new storage will be allocated.

func (*Binary) At

func (b *Binary) At(i int, j int) float64

At returns the value of the element at row i and column k. i (row) and j (col) must be within the dimensions of the matrix otherwise the method panics. This method is part of the Gonum mat.Matrix interface.

func (*Binary) ColView

func (b *Binary) ColView(j int) mat.Vector

ColView returns the mat.Vector representing the column j. This vector will be a BinaryVec and will share the same storage as the matrix so any changes to the vector will be reflected in the matrix and vice versa. if j is outside the dimensions of the matrix the method will panic.

func (*Binary) Dims

func (b *Binary) Dims() (int, int)

Dims returns the dimensions of the matrix as the number of rows, columns. This method is part of the Gonum mat.Matrix interface

func (*Binary) T

func (b *Binary) T() mat.Matrix

T performs an implicit transpose by returning the receiver inside a Transpose. This method is part of the Gonum mat.Matrix interface

type BinaryVec

type BinaryVec struct {
	// contains filtered or unexported fields
}

BinaryVec is a Binary Vector or Bit Vector type. This is useful for representing vectors of features with a binary state (1 or 0). Although part of the sparse package, this type is not sparse itself and stores all bits even 0s. However, as it makes use of 64 bit integers to store each set of 64 bits and then bitwise operators to manipulate the elements it will be more efficient in terms of both storage requirements and performance than a slice of bool values (8 bits per element) or even a typical Dense matrix of float64 elements. A compressed bitmap scheme could be used to take advantage of sparseness but may have an associated overhead.

func NewBinaryVec

func NewBinaryVec(length int) *BinaryVec

NewBinaryVec creates a new BitSet with a hint that length bits will be required

func (*BinaryVec) At

func (b *BinaryVec) At(i, j int) float64

At returns the value of the element at row i and column j. As this is a vector (only one column), j must be 0 otherwise the method panics. This method is part of the Gonum mat.Matrix interface.

func (*BinaryVec) AtVec

func (b *BinaryVec) AtVec(i int) float64

AtVec returns the value of the element at row i. This method will panic if i > Len(). This method is part of the Gonum mat.Vector interface.

func (*BinaryVec) BitIsSet

func (b *BinaryVec) BitIsSet(i int) bool

BitIsSet tests whether the element (bit) at position i is set (equals 1) and returns true if so. If the element (bit) is not set or has been unset (equal to 0) the the method will return false. The method will panic if i is greater than Len().

func (*BinaryVec) Dims

func (b *BinaryVec) Dims() (int, int)

Dims returns the dimensions of the matrix as the number of rows, columns. As this is a vector, the second value representing the number of columns will be 1. This method is part of the Gonum mat.Matrix interface

func (*BinaryVec) DistanceFrom

func (b *BinaryVec) DistanceFrom(rhs *BinaryVec) int

DistanceFrom is the number of bits that are different between the receiver and rhs i.e.

recevier 	= 1001001
rhs 		= 1010101
Distance	= 3

because there are three bits that are different between the 2 binary vectors. This is sometimes referred to as the `Hamming distance` or `Matching distance`. In this case, the distance is not normalised and is simply the raw count of differences. To normalise the value simply divide this value by the vector's length.

func (BinaryVec) Format

func (b BinaryVec) Format(f fmt.State, c rune)

Format outputs the vector to f and allows the output format to be specified. Supported values of c are `x`, `X`, `b`` and `s` to format the bits of the vector as a hex digit or binary digit string. `s` (the default format) will output as binary digits. Please refer to the fmt package documentation for more information. This method implements the fmt.Formatter interface.

func (*BinaryVec) Len

func (b *BinaryVec) Len() int

Len returns the length of the vector or the total number of elements. This method is part of the Gonum mat.Vector interface

func (*BinaryVec) NNZ

func (b *BinaryVec) NNZ() int

NNZ returns the Number of Non-Zero elements (bits). This is the number of set bits (represented by 1s rather than 0s) in the vector. This is also known as the `Hamming weight` or `population count` (popcount).

func (*BinaryVec) Set

func (b *BinaryVec) Set(i int, j int, v float64)

Set sets the element of the matrix located at row i and column j to 1 if v != 0 or 0 otherwise. Set will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*BinaryVec) SetBit

func (b *BinaryVec) SetBit(i int)

SetBit sets the bit at the specified index (i) to 1. If the bit is already set there are no adverse effects. The method will panic if index is larger than Len()

func (*BinaryVec) SetVec

func (b *BinaryVec) SetVec(i int, v float64)

SetVec sets the element of the vector located at row i to 1 if v != 0 or 0 otherwise. The method will panic if i is greater than Len().

func (*BinaryVec) SliceToUint64

func (b *BinaryVec) SliceToUint64(from, to int) uint64

SliceToUint64 returns a new uint64. The returned matrix starts at element from of the receiver and extends to - from rows. The final row in the resulting matrix is to-1. Slice panics with ErrIndexOutOfRange if the slice is outside the capacity of the receiver.

func (BinaryVec) String

func (b BinaryVec) String() string

String will output the vector as a string representation of its bits This method implements the fmt.Stringer interface.

func (*BinaryVec) T

func (b *BinaryVec) T() mat.Matrix

T performs an implicit transpose by returning the receiver inside a Transpose. This method is part of the Gonum mat.Matrix interface

func (*BinaryVec) UnsetBit

func (b *BinaryVec) UnsetBit(i int)

UnsetBit unsets the bit at the specified index (i) (sets it to 0). If the bit is already unset or has simply never been set (default bit values are 0) there are no adverse effects. The method will panic if index is larger than Len()

type BlasCompatibleSparser

type BlasCompatibleSparser interface {
	Sparser
	RawMatrix() *blas.SparseMatrix
}

BlasCompatibleSparser is an interface which represents Sparse matrices compatible with sparse BLAS routines i.e. implementing the RawMatrix() method as a means of obtaining a BLAS sparse matrix representation of the matrix.

type COO

type COO struct {
	// contains filtered or unexported fields
}

COO is a COOrdinate format sparse matrix implementation (sometimes called `Tiplet` format) and implements the Matrix interface from gonum/matrix. This allows large sparse (mostly zero values) matrices to be stored efficiently in memory (only storing non-zero values). COO matrices are good for constructing sparse matrices initially and very good at converting to CSR and CSC formats but poor for arithmetic operations. As this type implements the gonum mat.Matrix interface, it may be used with any of the Gonum mat functions that accept Matrix types as parameters in place of other matrix types included in the Gonum mat package e.g. mat.Dense.

func NewCOO

func NewCOO(r int, c int, rows []int, cols []int, data []float64) *COO

NewCOO creates a new DIAgonal format sparse matrix. The matrix is initialised to the size of the specified r * c dimensions (rows * columns) with the specified slices containing either nil or containing rows and cols indexes of non-zero elements and the non-zero data values themselves respectively. If not nil, the supplied slices will be used as the backing storage to the matrix so changes to values of the slices will be reflected in the created matrix and vice versa.

func (*COO) At

func (c *COO) At(i, j int) float64

At returns the element of the matrix located at row i and column j. At will panic if specified values for i or j fall outside the dimensions of the matrix. As the COO format allows duplicate elements, any duplicate values will be summed together.

func (*COO) Dims

func (c *COO) Dims() (int, int)

Dims returns the size of the matrix as the number of rows and columns

func (*COO) DoNonZero

func (c *COO) DoNonZero(fn func(i, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j). The order of visiting to each non-zero element is not guaranteed.

func (*COO) MarshalBinary

func (c *COO) MarshalBinary() ([]byte, error)

MarshalBinary binary serialises the receiver into a []byte and returns the result.

compressedSparse is little-endian encoded as follows:

 0 -  7  number of rows    (int64)
 8 - 15  number of columns (int64)
16 - 23  number of indptr  (int64)
24 - 31  number of ind     (int64)
32 - 39  number of non zero elements (int64)
40 - ..  data elements for indptr, ind, and data (float64)

func (*COO) MarshalBinaryTo

func (c *COO) MarshalBinaryTo(w io.Writer) (int, error)

MarshalBinaryTo binary serialises the receiver and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the serialised layout.

func (*COO) MulVecTo

func (c *COO) MulVecTo(dst []float64, trans bool, x []float64)

MulVecTo performs matrix vector multiplication (dst+=A*x or dst+=A^T*x), where A is the receiver, and stores the result in dst. MulVecTo panics if ac != len(x) or ar != len(dst)

func (*COO) NNZ

func (c *COO) NNZ() int

NNZ returns the Number of Non Zero elements in the sparse matrix.

func (*COO) RawMatrix

func (c *COO) RawMatrix() *blas.SparseMatrix

RawMatrix converts the matrix into a CSR matrix and returns a pointer to the underlying blas sparse matrix.

func (*COO) Set

func (c *COO) Set(i, j int, v float64)

Set sets the element of the matrix located at row i and column j to equal the specified value, v. Set will panic if specified values for i or j fall outside the dimensions of the matrix. Duplicate values are allowed and will be added.

func (*COO) T

func (c *COO) T() mat.Matrix

T transposes the matrix creating a new COO matrix, reusing the same underlying storage, but switching column and row sizes and index slices i.e. rows become columns and columns become rows.

func (*COO) ToCOO

func (c *COO) ToCOO() *COO

ToCOO returns the receiver

func (*COO) ToCSC

func (c *COO) ToCSC() *CSC

ToCSC returns a CSC (Compressed Sparse Column)(AKA CCS (Compressed Column Storage)) sparse format version of the matrix. The returned CSC matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*COO) ToCSCReuseMem

func (c *COO) ToCSCReuseMem() *CSC

ToCSCReuseMem returns a CSC (Compressed Sparse Column)(AKA CCS (Compressed Column Storage)) sparse format version of the matrix. Unlike with ToCSC(), The returned CSC matrix WILL share underlying storage with the receiver and the receiver will be modified by this call.

func (*COO) ToCSR

func (c *COO) ToCSR() *CSR

ToCSR returns a CSR (Compressed Sparse Row)(AKA CRS (Compressed Row Storage)) sparse format version of the matrix. The returned CSR matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*COO) ToCSRReuseMem

func (c *COO) ToCSRReuseMem() *CSR

ToCSRReuseMem returns a CSR (Compressed Sparse Row)(AKA CRS (Compressed Row Storage)) sparse format version of the matrix. Unlike with ToCSR(), The returned CSR matrix WILL share underlying storage with the receiver and the receiver will be modified by this call.

func (*COO) ToDOK

func (c *COO) ToDOK() *DOK

ToDOK returns a DOK (Dictionary Of Keys) sparse format version of the matrix. The returned DOK matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*COO) ToDense

func (c *COO) ToDense() *mat.Dense

ToDense returns a mat.Dense dense format version of the matrix. The returned mat.Dense matrix will not share underlying storage with the receiver. nor is the receiver modified by this call

func (*COO) ToType

func (c *COO) ToType(matType MatrixType) mat.Matrix

ToType returns an alternative format version fo the matrix in the format specified.

func (*COO) UnmarshalBinary

func (c *COO) UnmarshalBinary(data []byte) error

UnmarshalBinary binary deserialises the []byte into the receiver. It panics if the receiver is a non-zero DIA matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sprase matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

func (*COO) UnmarshalBinaryFrom

func (c *COO) UnmarshalBinaryFrom(r io.Reader) (int, error)

UnmarshalBinaryFrom binary deserialises the []byte into the receiver and returns the number of bytes read and an error if any.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sparse matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

type COOType

type COOType int

COOType represents the COOrdinate matrix type format

func (COOType) Convert

func (s COOType) Convert(from TypeConverter) mat.Matrix

Convert converts the specified TypeConverter to COOrdinate format

type CSC

type CSC struct {
	// contains filtered or unexported fields
}

CSC is a Compressed Sparse Column format sparse matrix implementation (sometimes called Compressed Column Storage (CCS) format) and implements the Matrix interface from gonum/matrix. This allows large sparse (mostly zero values) matrices to be stored efficiently in memory (only storing non-zero values). CSC matrices are poor for constructing sparse matrices incrementally but very good for arithmetic operations. CSC, and their sibling CSR, matrices are similar to COOrdinate matrices except the column index slice is compressed. Rather than storing the column indices of each non zero values (length == NNZ) each element, i, of the slice contains the cumulative count of non zero values in the matrix up to column i-1 of the matrix. In this way, it is possible to address any element, j i, in the matrix with the following:

for k := c.indptr[i]; k < c.indptr[i+1]; k++ {
	if c.ind[k] == j {
		return c.data[k]
	}
}

It should be clear that CSC is like CSR except the slices are column major order rather than row major and CSC is essentially the transpose of a CSR. As this type implements the gonum mat.Matrix interface, it may be used with any of the Gonum mat functions that accept Matrix types as parameters in place of other matrix types included in the Gonum mat package e.g. mat.Dense.

func NewCSC

func NewCSC(r int, c int, indptr []int, ind []int, data []float64) *CSC

NewCSC creates a new Compressed Sparse Column format sparse matrix. The matrix is initialised to the size of the specified r * c dimensions (rows * columns) with the specified slices containing column pointers and row indexes of non-zero elements and the non-zero data values themselves respectively. The supplied slices will be used as the backing storage to the matrix so changes to values of the slices will be reflected in the created matrix and vice versa.

func (*CSC) At

func (c *CSC) At(m, n int) float64

At returns the element of the matrix located at row i and column j. At will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*CSC) ColNNZ

func (c *CSC) ColNNZ(i int) int

ColNNZ returns the Number of Non Zero values in the specified col i. ColNNZ will panic if i is out of range.

func (*CSC) ColView

func (c *CSC) ColView(j int) mat.Vector

ColView slices the Compressed Sparse Column matrix along its primary axis. Returns a VecCOO sparse Vector that shares the same underlying storage as column i of the receiver.

func (*CSC) Dims

func (c *CSC) Dims() (int, int)

Dims returns the size of the matrix as the number of rows and columns

func (*CSC) DoColNonZero

func (c *CSC) DoColNonZero(j int, fn func(i, j int, v float64))

DoColNonZero calls the function fn for each of the non-zero elements of column j in the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j).

func (*CSC) DoNonZero

func (c *CSC) DoNonZero(fn func(i, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j). The order of visiting to each non-zero element is column major.

func (*CSC) MarshalBinary

func (c *CSC) MarshalBinary() ([]byte, error)

MarshalBinary binary serialises the receiver into a []byte and returns the result.

SparseMatrix is little-endian encoded as follows:

 0 -  7  number of rows    (int64)
 8 - 15  number of columns (int64)
16 - 23  number of indptr  (int64)
24 - 31  number of ind     (int64)
32 - 39  number of non zero elements (int64)
40 - ..  data elements for indptr, ind, and data (float64)

func (*CSC) MarshalBinaryTo

func (c *CSC) MarshalBinaryTo(w io.Writer) (int, error)

MarshalBinaryTo binary serialises the receiver and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the serialised layout.

func (*CSC) MulVecTo

func (c *CSC) MulVecTo(dst []float64, trans bool, x []float64)

MulVecTo performs matrix vector multiplication (dst+=A*x or dst+=A^T*x), where A is the receiver, and stores the result in dst. MulVecTo panics if ac != len(x) or ar != len(dst)

func (*CSC) NNZ

func (c *CSC) NNZ() int

NNZ returns the Number of Non Zero elements in the sparse matrix.

func (*CSC) RawMatrix

func (c *CSC) RawMatrix() *blas.SparseMatrix

RawMatrix returns a pointer to the underlying blas sparse matrix.

func (*CSC) ScatterCol

func (c *CSC) ScatterCol(j int, col []float64) []float64

ScatterCol returns a slice representing column j of the matrix in dense format. Col is used as the storage for the operation unless it is nil in which case, new storage of the correct length will be allocated. This method will panic if j is out of range or col is not the same length as the number of rows in the matrix i.e. the correct size to receive the dense representation of the column.

func (*CSC) Set

func (c *CSC) Set(m, n int, v float64)

Set sets the element of the matrix located at row i and column j to value v. Set will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*CSC) T

func (c *CSC) T() mat.Matrix

T transposes the matrix creating a new CSR matrix sharing the same backing data storage but switching column and row sizes and index & index pointer slices i.e. rows become columns and columns become rows.

func (*CSC) ToCOO

func (c *CSC) ToCOO() *COO

ToCOO returns a COOrdinate sparse format version of the matrix. The returned COO matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSC) ToCSC

func (c *CSC) ToCSC() *CSC

ToCSC returns the receiver

func (*CSC) ToCSR

func (c *CSC) ToCSR() *CSR

ToCSR returns a Compressed Sparse Row sparse format version of the matrix. The returned CSR matrix will not share underlying storage with the receiver nor is the receiver modified by this call. NB, the current implementation uses COO as an intermediate format so converts to COO before converting to CSR but attempts to reuse memory in the intermediate formats.

func (*CSC) ToDOK

func (c *CSC) ToDOK() *DOK

ToDOK returns a DOK (Dictionary Of Keys) sparse format version of the matrix. The returned DOK matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSC) ToDense

func (c *CSC) ToDense() *mat.Dense

ToDense returns a mat.Dense dense format version of the matrix. The returned mat.Dense matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSC) ToType

func (c *CSC) ToType(matType MatrixType) mat.Matrix

ToType returns an alternative format version fo the matrix in the format specified.

func (*CSC) Trace

func (c *CSC) Trace() float64

Trace returns the trace.

func (*CSC) UnmarshalBinary

func (c *CSC) UnmarshalBinary(data []byte) error

UnmarshalBinary binary deserialises the []byte into the receiver. It panics if the receiver is a non-zero DIA matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sprase matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

func (*CSC) UnmarshalBinaryFrom

func (c *CSC) UnmarshalBinaryFrom(r io.Reader) (int, error)

UnmarshalBinaryFrom binary deserialises the []byte into the receiver and returns the number of bytes read and an error if any.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sparse matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

type CSCType

type CSCType int

CSCType represents the CSC (Compressed Sparse Column) matrix type format

func (CSCType) Convert

func (s CSCType) Convert(from TypeConverter) mat.Matrix

Convert converts the specified TypeConverter to CSC (Compressed Sparse Column) format

type CSR

type CSR struct {
	// contains filtered or unexported fields
}

CSR is a Compressed Sparse Row format sparse matrix implementation (sometimes called Compressed Row Storage (CRS) format) and implements the Matrix interface from gonum/matrix. This allows large sparse (mostly zero values) matrices to be stored efficiently in memory (only storing non-zero values). CSR matrices are poor for constructing sparse matrices incrementally but very good for arithmetic operations. CSR, and their sibling CSC, matrices are similar to COOrdinate matrices except the row index slice is compressed. Rather than storing the row indices of each non zero values (length == NNZ) each element, i, of the slice contains the cumulative count of non zero values in the matrix up to row i-1 of the matrix. In this way, it is possible to address any element, i j, in the matrix with the following:

for k := c.indptr[i]; k < c.indptr[i+1]; k++ {
	if c.ind[k] == j {
		return c.data[k]
	}
}

It should be clear that CSR is like CSC except the slices are row major order rather than column major and CSC is essentially the transpose of a CSR. As this type implements the gonum mat.Matrix interface, it may be used with any of the Gonum mat functions that accept Matrix types as parameters in place of other matrix types included in the Gonum mat package e.g. mat.Dense.

func NewCSR

func NewCSR(r int, c int, ia []int, ja []int, data []float64) *CSR

NewCSR creates a new Compressed Sparse Row format sparse matrix. The matrix is initialised to the size of the specified r * c dimensions (rows * columns) with the specified slices containing row pointers and cols indexes of non-zero elements and the non-zero data values themselves respectively. The supplied slices will be used as the backing storage to the matrix so changes to values of the slices will be reflected in the created matrix and vice versa.

func (*CSR) Add

func (c *CSR) Add(a, b mat.Matrix)

Add adds matrices a and b together and stores the result in the receiver. If matrices a and b are not the same shape then the method will panic.

func (*CSR) At

func (c *CSR) At(m, n int) float64

At returns the element of the matrix located at row i and column j. At will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*CSR) Clone

func (c *CSR) Clone(b mat.Matrix)

Clone copies the specified matrix into the receiver

func (*CSR) Dims

func (c *CSR) Dims() (int, int)

Dims returns the size of the matrix as the number of rows and columns

func (*CSR) DoNonZero

func (c *CSR) DoNonZero(fn func(i, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j). The order of visiting to each non-zero element is row major.

func (*CSR) DoRowNonZero

func (c *CSR) DoRowNonZero(i int, fn func(i, j int, v float64))

DoRowNonZero calls the function fn for each of the non-zero elements of row i in the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j).

func (*CSR) IsZero

func (c *CSR) IsZero() bool

IsZero returns whether the receiver is zero-sized. Zero-sized matrices can be the receiver for size-restricted operations. CSR matrices can be zeroed using the Reset method.

func (*CSR) MarshalBinary

func (c *CSR) MarshalBinary() ([]byte, error)

MarshalBinary binary serialises the receiver into a []byte and returns the result.

SparseMatrix is little-endian encoded as follows:

 0 -  7  number of rows    (int64)
 8 - 15  number of columns (int64)
16 - 23  number of indptr  (int64)
24 - 31  number of ind     (int64)
32 - 39  number of non zero elements (int64)
40 - ..  data elements for indptr, ind, and data (float64)

func (*CSR) MarshalBinaryTo

func (c *CSR) MarshalBinaryTo(w io.Writer) (int, error)

MarshalBinaryTo binary serialises the receiver and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the serialised layout.

func (*CSR) Mul

func (c *CSR) Mul(a, b mat.Matrix)

Mul takes the matrix product of the supplied matrices a and b and stores the result in the receiver. Some specific optimisations are available for operands of certain sparse formats e.g. CSR * CSR uses Gustavson Algorithm (ACM 1978) for fast sparse matrix multiplication. If the number of columns does not equal the number of rows in b, Mul will panic.

func (*CSR) MulVecTo

func (c *CSR) MulVecTo(dst []float64, trans bool, x []float64)

MulVecTo performs matrix vector multiplication (dst+=A*x or dst+=A^T*x), where A is the receiver, and stores the result in dst. MulVecTo panics if ac != len(x) or ar != len(dst)

func (*CSR) NNZ

func (c *CSR) NNZ() int

NNZ returns the Number of Non Zero elements in the sparse matrix.

func (*CSR) RawMatrix

func (c *CSR) RawMatrix() *blas.SparseMatrix

RawMatrix returns a pointer to the underlying blas sparse matrix.

func (*CSR) Reset

func (c *CSR) Reset()

Reset zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Gonum mat.Reseter interface for more information.

func (*CSR) RowNNZ

func (c *CSR) RowNNZ(i int) int

RowNNZ returns the Number of Non Zero values in the specified row i. RowNNZ will panic if i is out of range.

func (*CSR) RowView

func (c *CSR) RowView(i int) mat.Vector

RowView slices the Compressed Sparse Row matrix along its primary axis. Returns a VecCOO sparse Vector that shares the same storage with the receiver for row i.

func (*CSR) ScatterRow

func (c *CSR) ScatterRow(i int, row []float64) []float64

ScatterRow returns a slice representing row i of the matrix in dense format. Row is used as the storage for the operation unless it is nil in which case, new storage of the correct length will be allocated. This method will panic if i is out of range or row is not the same length as the number of columns in the matrix i.e. the correct size to receive the dense representation of the row.

func (*CSR) Set

func (c *CSR) Set(m, n int, v float64)

Set sets the element of the matrix located at row i and column j to value v. Set will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*CSR) Sub

func (c *CSR) Sub(a, b mat.Matrix)

Sub subtracts matrix b from a and stores the result in the receiver. If matrices a and b are not the same shape then the method will panic.

func (*CSR) T

func (c *CSR) T() mat.Matrix

T transposes the matrix creating a new CSC matrix sharing the same backing data storage but switching column and row sizes and index & index pointer slices i.e. rows become columns and columns become rows.

func (*CSR) ToCOO

func (c *CSR) ToCOO() *COO

ToCOO returns a COOrdinate sparse format version of the matrix. The returned COO matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSR) ToCSC

func (c *CSR) ToCSC() *CSC

ToCSC returns a Compressed Sparse Column sparse format version of the matrix. The returned CSC matrix will not share underlying storage with the receiver nor is the receiver modified by this call. NB, the current implementation uses COO as an intermediate format so converts to COO before converting to CSC but attempts to reuse memory in the intermediate formats.

func (*CSR) ToCSR

func (c *CSR) ToCSR() *CSR

ToCSR returns the receiver

func (*CSR) ToDOK

func (c *CSR) ToDOK() *DOK

ToDOK returns a DOK (Dictionary Of Keys) sparse format version of the matrix. The returned DOK matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSR) ToDense

func (c *CSR) ToDense() *mat.Dense

ToDense returns a mat.Dense dense format version of the matrix. The returned mat.Dense matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*CSR) ToType

func (c *CSR) ToType(matType MatrixType) mat.Matrix

ToType returns an alternative format version fo the matrix in the format specified.

func (*CSR) Trace

func (c *CSR) Trace() float64

Trace returns the trace.

func (*CSR) UnmarshalBinary

func (c *CSR) UnmarshalBinary(data []byte) error

UnmarshalBinary binary deserialises the []byte into the receiver. It panics if the receiver is a non-zero DIA matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sprase matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

func (*CSR) UnmarshalBinaryFrom

func (c *CSR) UnmarshalBinaryFrom(r io.Reader) (int, error)

UnmarshalBinaryFrom binary deserialises the []byte into the receiver and returns the number of bytes read and an error if any.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sparse matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

type CSRType

type CSRType int

CSRType represents the CSR (Compressed Sparse Row) matrix type format

func (CSRType) Convert

func (s CSRType) Convert(from TypeConverter) mat.Matrix

Convert converts the specified TypeConverter to CSR (Compressed Sparse Row) format

type Cholesky

type Cholesky struct {
	// contains filtered or unexported fields
}

Cholesky shadows the gonum mat.Cholesly type

func (*Cholesky) At

func (ch *Cholesky) At(i, j int) float64

At from the matrix

func (*Cholesky) Det

func (ch *Cholesky) Det() float64

Det returns the determinant of the factored matrix

func (*Cholesky) Dims

func (ch *Cholesky) Dims() (r, c int)

Dims of the matrix

func (*Cholesky) Factorize

func (ch *Cholesky) Factorize(a *CSR)

Factorize a CSR the CSR must be symmetric positive-definite or this won't work FIXME: enforce sym positive definite

func (*Cholesky) LTo

func (ch *Cholesky) LTo(dst *CSR)

LTo returns the factored matrix in lower-triangular form as a CSR

func (*Cholesky) LogDet

func (ch *Cholesky) LogDet() float64

LogDet returns ln(determinant) of the factored matrix

func (*Cholesky) SolveTo

func (ch *Cholesky) SolveTo(dst *mat.Dense, b mat.Matrix) error

SolveTo goes column-by-column and applies SolveVecTo

func (*Cholesky) SolveVecTo

func (ch *Cholesky) SolveVecTo(dst *mat.VecDense, b mat.Vector) error

SolveVecTo shadows Cholesky.SolveVecTo dst is Dense as this doesn't make any sense with sparse solutions

func (*Cholesky) Symmetric

func (ch *Cholesky) Symmetric() int

Symmetric of matrix

func (*Cholesky) T

func (ch *Cholesky) T() mat.Matrix

T is the same as symmetric

type DIA

type DIA struct {
	// contains filtered or unexported fields
}

DIA matrix type is a specialised matrix designed to store DIAgonal values of square symmetrical matrices (all zero values except along the diagonal running top left to bottom right). The DIA matrix type is specifically designed to take advantage of the sparsity pattern of square symmetrical matrices.

func NewDIA

func NewDIA(m int, n int, diagonal []float64) *DIA

NewDIA creates a new DIAgonal format sparse matrix. The matrix is initialised to the size of the specified m * m dimensions (rows * columns) (creating a square) with the specified slice containing it's diagonal values. The diagonal slice will be used as the backing slice to the matrix so changes to values of the slice will be reflected in the matrix.

func (*DIA) At

func (d *DIA) At(i, j int) float64

At returns the element of the matrix located at row i and column j. At will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*DIA) ColView

func (d *DIA) ColView(j int) mat.Vector

ColView slices the matrix and returns a Vector containing a copy of elements of column j.

func (*DIA) Diagonal

func (d *DIA) Diagonal() []float64

Diagonal returns the diagonal values of the matrix from top left to bottom right. The values are returned as a slice backed by the same array as backing the receiver so changes to values in the returned slice will be reflected in the receiver.

func (*DIA) Dims

func (d *DIA) Dims() (int, int)

Dims returns the size of the matrix as the number of rows and columns

func (*DIA) DoNonZero

func (d *DIA) DoNonZero(fn func(i, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j). The order of visiting to each non-zero element is from top left to bottom right.

func (DIA) MarshalBinary

func (m DIA) MarshalBinary() ([]byte, error)

MarshalBinary binary serialises the receiver into a []byte and returns the result.

DIA is little-endian encoded as follows:

  0 -  7  number of rows    (int64)
  8 - 15  number of columns (int64)
	16 - 23  number of non zero elements (along the diagonal) (int64)
 24 - ..  diagonal matrix data elements (float64)

func (DIA) MarshalBinaryTo

func (m DIA) MarshalBinaryTo(w io.Writer) (int, error)

MarshalBinaryTo binary serialises the receiver and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the serialised layout.

func (*DIA) MulVecTo

func (d *DIA) MulVecTo(dst []float64, trans bool, x []float64)

MulVecTo performs matrix vector multiplication (dst+=A*x or dst+=A^T*x), where A is the receiver, and stores the result in dst. MulVecTo panics if ac != len(x) or ar != len(dst)

func (*DIA) NNZ

func (d *DIA) NNZ() int

NNZ returns the Number of Non Zero elements in the sparse matrix.

func (*DIA) RowView

func (d *DIA) RowView(i int) mat.Vector

RowView slices the matrix and returns a Vector containing a copy of elements of row i.

func (*DIA) ScatterCol

func (d *DIA) ScatterCol(j int, col []float64) []float64

ScatterCol returns a slice representing column j of the matrix in dense format. Col is used as the storage for the operation unless it is nil in which case, new storage of the correct length will be allocated. This method will panic if j is out of range or col is not the same length as the number of rows in the matrix i.e. the correct size to receive the dense representation of the column.

func (*DIA) ScatterRow

func (d *DIA) ScatterRow(i int, row []float64) []float64

ScatterRow returns a slice representing row i of the matrix in dense format. row is used as the storage for the operation unless it is nil in which case, new storage of the correct length will be allocated. This method will panic if i is out of range or row is not the same length as the number of columns in the matrix i.e. the correct size to receive the dense representation of the row.

func (*DIA) T

func (d *DIA) T() mat.Matrix

T returns the matrix transposed. In the case of a DIA (DIAgonal) sparse matrix this method returns a new DIA matrix with the m and n values transposed.

func (*DIA) Trace

func (d *DIA) Trace() float64

Trace returns the trace.

func (*DIA) UnmarshalBinary

func (m *DIA) UnmarshalBinary(data []byte) error

UnmarshalBinary binary deserialises the []byte into the receiver. It panics if the receiver is a non-zero DIA matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting DIA matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

func (*DIA) UnmarshalBinaryFrom

func (m *DIA) UnmarshalBinaryFrom(r io.Reader) (int, error)

UnmarshalBinaryFrom binary deserialises the []byte into the receiver and returns the number of bytes read and an error if any.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting DIA matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

type DOK

type DOK struct {
	// contains filtered or unexported fields
}

DOK is a Dictionary Of Keys sparse matrix implementation and implements the Matrix interface from gonum/matrix. This allows large sparse (mostly zero values) matrices to be stored efficiently in memory (only storing non-zero values). DOK matrices are good for incrementally constructing sparse matrices but poor for arithmetic operations or other operations that require iterating over elements of the matrix sequentially. As this type implements the gonum mat.Matrix interface, it may be used with any of the Gonum mat functions that accept Matrix types as parameters in place of other matrix types included in the Gonum mat package e.g. mat.Dense.

func NewDOK

func NewDOK(r, c int) *DOK

NewDOK creates a new Dictionary Of Keys format sparse matrix initialised to the size of the specified r * c dimensions (rows * columns)

func (*DOK) At

func (d *DOK) At(i, j int) float64

At returns the element of the matrix located at row i and column j. At will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*DOK) Dims

func (d *DOK) Dims() (r, c int)

Dims returns the size of the matrix as the number of rows and columns

func (*DOK) DoNonZero

func (d *DOK) DoNonZero(fn func(i, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j). The order of visiting to each non-zero element in the receiver is random.

func (*DOK) MarshalBinary

func (c *DOK) MarshalBinary() ([]byte, error)

MarshalBinary binary serialises the receiver into a []byte and returns the result.

DOK is little-endian encoded as follows:

 0 -  7  number of rows    (int64)
 8 - 15  number of columns (int64)
16 - ..  data elements     (key + float64)

func (*DOK) MarshalBinaryTo

func (c *DOK) MarshalBinaryTo(w io.Writer) (int, error)

MarshalBinaryTo binary serialises the receiver and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the serialised layout.

func (*DOK) MulVecTo

func (d *DOK) MulVecTo(dst []float64, trans bool, x []float64)

MulVecTo performs matrix vector multiplication (dst+=A*x or dst+=A^T*x), where A is the receiver, and stores the result in dst. MulVecTo panics if ac != len(x) or ar != len(dst)

func (*DOK) NNZ

func (d *DOK) NNZ() int

NNZ returns the Number of Non Zero elements in the sparse matrix.

func (*DOK) RawMatrix

func (d *DOK) RawMatrix() *blas.SparseMatrix

RawMatrix converts the matrix to a CSR matrix and returns a pointer to the underlying blas sparse matrix.

func (*DOK) Set

func (d *DOK) Set(i, j int, v float64)

Set sets the element of the matrix located at row i and column j to equal the specified value, v. Set will panic if specified values for i or j fall outside the dimensions of the matrix.

func (*DOK) T

func (d *DOK) T() mat.Matrix

T transposes the matrix. This is an implicit transpose, wrapping the matrix in a mat.Transpose type.

func (*DOK) ToCOO

func (d *DOK) ToCOO() *COO

ToCOO returns a COOrdinate sparse format version of the matrix. The returned COO matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*DOK) ToCSC

func (d *DOK) ToCSC() *CSC

ToCSC returns a CSC (Compressed Sparse Column)(AKA CCS (Compressed Column Storage)) sparse format version of the matrix. The returned CSC matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*DOK) ToCSR

func (d *DOK) ToCSR() *CSR

ToCSR returns a CSR (Compressed Sparse Row)(AKA CRS (Compressed Row Storage)) sparse format version of the matrix. The returned CSR matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*DOK) ToDOK

func (d *DOK) ToDOK() *DOK

ToDOK returns the receiver

func (*DOK) ToDense

func (d *DOK) ToDense() *mat.Dense

ToDense returns a mat.Dense dense format version of the matrix. The returned mat.Dense matrix will not share underlying storage with the receiver nor is the receiver modified by this call.

func (*DOK) ToType

func (d *DOK) ToType(matType MatrixType) mat.Matrix

ToType returns an alternative format version fo the matrix in the format specified.

func (*DOK) UnmarshalBinary

func (c *DOK) UnmarshalBinary(data []byte) error

UnmarshalBinary binary deserialises the []byte into the receiver. It panics if the receiver is a non-zero DIA matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sprase matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

func (*DOK) UnmarshalBinaryFrom

func (c *DOK) UnmarshalBinaryFrom(r io.Reader) (int, error)

UnmarshalBinaryFrom binary deserialises the []byte into the receiver and returns the number of bytes read and an error if any.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- an error is returned if the resulting compressed sparse matrix is too
big for the current architecture (e.g. a 16GB matrix written by a
64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

type DOKType

type DOKType int

DOKType represents the DOK (Dictionary Of Keys) matrix type format

func (DOKType) Convert

func (s DOKType) Convert(from TypeConverter) mat.Matrix

Convert converts the specified TypeConverter to DOK (Dictionary of Keys) format

type DenseType

type DenseType int

DenseType represents the mat.Dense matrix type format

func (DenseType) Convert

func (d DenseType) Convert(from TypeConverter) mat.Matrix

Convert converts the specified TypeConverter to mat.Dense format

type MatrixType

type MatrixType interface {
	// Convert converts to the type of matrix format represented by the receiver from the specified TypeConverter.
	Convert(from TypeConverter) mat.Matrix
}

MatrixType represents a type of Matrix format. This is used to specify target format types for conversion, etc.

type Normer

type Normer interface {
	Norm(L float64) float64
}

Normer is an interface for calculating the Norm of a matrix. This allows matrices to implement format specific Norm implementations optimised for each format processing only non-zero elements for different sparsity patterns across sparse matrix formats.

type SPA

type SPA struct {
	// contains filtered or unexported fields
}

SPA is a SParse Accumulator used to construct the results of sparse arithmetic operations in linear time.

func NewSPA

func NewSPA(n int) *SPA

NewSPA creates a new SParse Accumulator of length n. If accumulating rows for a CSR matrix then n should be equal to the number of columns in the resulting matrix.

func (*SPA) AccumulateDense

func (s *SPA) AccumulateDense(x []float64, alpha float64, ind *[]int)

AccumulateDense accumulates the dense vector x by multiplying the non-zero elements by alpha and adding them to the corresponding elements in the SPA (SPA += alpha * x) This is the dense version of the Scatter method for sparse vectors.

func (SPA) Gather

func (s SPA) Gather(data *[]float64, ind *[]int)

Gather gathers the non-zero values from the SPA and appends them to end of the supplied sparse vector.

func (*SPA) GatherAndZero

func (s *SPA) GatherAndZero(data *[]float64, ind *[]int)

GatherAndZero gathers the non-zero values from the SPA and appends them to the end of the supplied sparse vector. The SPA is also zeroed ready to start accumulating the next row/column vector.

func (*SPA) Scatter

func (s *SPA) Scatter(x []float64, indx []int, alpha float64, ind *[]int)

Scatter accumulates the sparse vector x by multiplying the elements by alpha and adding them to the corresponding elements in the SPA (SPA += alpha * x)

func (*SPA) ScatterValue

func (s *SPA) ScatterValue(val float64, index int, alpha float64, ind *[]int)

ScatterValue accumulates a single value by multiplying the value by alpha and adding it to the corresponding element in the SPA (SPA += alpha * x)

func (*SPA) ScatterVec

func (s *SPA) ScatterVec(x *Vector, alpha float64, ind *[]int)

ScatterVec accumulates the sparse vector x by multiplying the elements by alpha and adding them to the corresponding elements in the SPA (SPA += alpha * x)

type Sparser

type Sparser interface {
	mat.Matrix
	mat.NonZeroDoer

	// NNZ returns the Number of Non Zero elements in the sparse matrix.
	NNZ() int
}

Sparser is the interface for Sparse matrices. Sparser contains the mat.Matrix interface so automatically exposes all mat.Matrix methods.

type TypeConverter

type TypeConverter interface {
	// ToDense returns a mat.Dense dense format version of the matrix.
	ToDense() *mat.Dense

	// ToDOK returns a Dictionary Of Keys (DOK) sparse format version of the matrix.
	ToDOK() *DOK

	// ToCOO returns a COOrdinate sparse format version of the matrix.
	ToCOO() *COO

	// ToCSR returns a Compressed Sparse Row (CSR) sparse format version of the matrix.
	ToCSR() *CSR

	// ToCSC returns a Compressed Sparse Row (CSR) sparse format version of the matrix.
	ToCSC() *CSC

	// ToType returns an alternative format version fo the matrix in the format specified.
	ToType(matType MatrixType) mat.Matrix
}

TypeConverter interface for converting to other matrix formats

type Vector

type Vector struct {
	// contains filtered or unexported fields
}

Vector is a sparse vector format. It implements the mat.Vector interface but is optimised for sparsely populated vectors where most of the elements contain zero values by only storing and processing the non-zero values. The format is similar to the triplet format used by COO matrices (and CSR/CSC) but only uses 2 arrays because the vector is 1 dimensional rather than 2.

func NewVector

func NewVector(len int, ind []int, data []float64) *Vector

NewVector returns a new sparse vector of length len with elements specified by ind[] containing the values conatined within data. Vector will reuse the same storage as the slices passed in and so any changes to the vector will be reflected in the slices and vice versa.

func (*Vector) AddScaledVec

func (v *Vector) AddScaledVec(a mat.Vector, alpha float64, b mat.Vector)

AddScaledVec adds the vectors a and alpha*b, placing the result in the receiver. AddScaledVec will panic if a and b are not the same length.

func (*Vector) AddVec

func (v *Vector) AddVec(a, b mat.Vector)

AddVec adds the vectors a and b, placing the result in the receiver. AddVec will panic if a and b are not the same length. If a and b are both sparse Vector vectors then AddVec will only process the non-zero elements.

func (*Vector) At

func (v *Vector) At(r, c int) float64

At returns the element at r, c. At will panic if c != 0.

func (*Vector) AtVec

func (v *Vector) AtVec(i int) float64

AtVec returns the i'th element of the Vector.

func (*Vector) CloneVec

func (v *Vector) CloneVec(a mat.Vector)

CloneVec clones the supplied mat.Vector, a into the receiver, overwriting the previous values of the receiver. If the receiver is of a different length from a, it will be resized to accommodate the values from a.

func (*Vector) Dims

func (v *Vector) Dims() (r, c int)

Dims returns the dimensions of the vector. This will be equivalent to Len(), 1

func (*Vector) DoNonZero

func (v *Vector) DoNonZero(fn func(i int, j int, v float64))

DoNonZero calls the function fn for each of the non-zero elements of the receiver. The function fn takes a row/column index and the element value of the receiver at (i, j).

func (*Vector) Gather

func (v *Vector) Gather(denseVector *mat.VecDense)

Gather gathers the entries from the supplied mat.VecDense structure that have corresponding non-zero entries in the receiver into the receiver. The method will panic if denseVector is not the same length as the receiver.

func (*Vector) GatherAndZero

func (v *Vector) GatherAndZero(denseVector *mat.VecDense)

GatherAndZero gathers the entries from the supplied mat.VecDense structure that have corresponding non-zero entries in the receiver into the receiver and then zeros those entries in denseVector. The method will panic if denseVector is not the same length as the receiver.

func (*Vector) IsSorted

func (v *Vector) IsSorted() bool

IsSorted checks if the vector is stored in sorted order

func (*Vector) IsZero

func (v *Vector) IsZero() bool

IsZero returns whether the receiver is zero-sized. Zero-sized vectors can be the receiver for size-restricted operations. Vectors can be zeroed using the Reset method.

func (*Vector) Len

func (v *Vector) Len() int

Len returns the length of the vector

func (*Vector) NNZ

func (v *Vector) NNZ() int

NNZ returns the number of non-zero elements in the vector.

func (*Vector) Norm

func (v *Vector) Norm(L float64) float64

Norm calculates the Norm of the vector only processing the non-zero elements. See Normer interface for more details.

func (*Vector) RawVector

func (v *Vector) RawVector() ([]float64, []int)

RawVector returns the underlying sparse vector data and indices respectively for raw manipulation or use in sparse BLAS routines.

func (*Vector) Reset

func (v *Vector) Reset()

Reset zeros the dimensions of the vector so that it can be reused as the receiver of a dimensionally restricted operation.

See the Gonum mat.Reseter interface for more information.

func (*Vector) ScaleVec

func (v *Vector) ScaleVec(alpha float64, a mat.Vector)

ScaleVec scales the vector a by alpha, placing the result in the receiver.

func (*Vector) Scatter

func (v *Vector) Scatter(denseVector *mat.VecDense) *mat.VecDense

Scatter scatters elements from the receiver into the supplied mat.VecDense structure, denseVector and returns a pointer to it. The method will panic if denseVector is not the same length as the receiver (unless it is nil)

func (*Vector) Set

func (v *Vector) Set(r, c int, val float64)

Set sets the element at row r, column c to the value val. Set will panic if c != 0.

func (*Vector) SetVec

func (v *Vector) SetVec(i int, val float64)

SetVec sets the i'th element to the value val. It panics if i is out of bounds.

func (*Vector) Sort

func (v *Vector) Sort()

Sort the entries in a vector.

func (*Vector) T

func (v *Vector) T() mat.Matrix

T returns the transpose of the receiver.

func (*Vector) ToDense

func (v *Vector) ToDense() *mat.VecDense

ToDense converts the sparse vector to a dense vector The returned dense matrix is a new copy of the receiver.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier