matrix

package
Version: v0.0.0-...-df3259c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2015 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

The matrix package contains various utilities for dealing with raw matrices. The interface is loosely based on the NumPy package in Python. At present, all arrays store float64 values.

NDArray

The NDArray interface describes a multidimensional array. Both dense and (2D-only) sparse implementations are available, with handy constructors for various array types. In general, the methods in NDArray are those methods which would make sense for an array of any dimensionality.

The following constructors all create dense arrays. For sparse representations, see the Matrix constructors below.

To create a one dimensional, initialized array:

a0 := A1(1.0, 2.0, 3.0)

To create a 2x3 array containing all zeros, use one of:

a1 := Dense(2, 3)
a2 := Zeros(2, 3)

To create a 2x3 array containing all ones, use:

a3 := Ones(2, 3)

To create a 2x3 array with initialized values:

a4 := A([]int{2,3},
        1.0, 2.0, 3.0,
        4.0, 5.0, 6.0)
a5 := A2([]float64{1.0, 2.0, 3.0},
         []float64{4.0, 5.0, 6.0})

To create a 2x3 array initialized to some arbitrary value:

a6 := WithValue(0.1, 2, 3)

To create a 2x3 array with random values uniformly distributed in [0, 1):

a7 := Rand(2, 3)

To create a 2x3 array with random values on the standard normal distribution:

a8 := RandN(2, 3)

Matrix

The Matrix interface describes operations suited to a two-dimensional array. Note that a two-dimensional NDArray can be trivially converted to the Matrix type by calling arr.M(). The resulting object will generally be the same, but converted to the Matrix type.

The following representations are available. A dense matrix stores all values in a []float64. A sparse diagonal matrix stores the elements of the main diagonal in a []float64, and assumes off-diagonal elements are zero. A sparse coo matrix stores nonzero items by position in a map[[2]int]float64.

When possible, function implementations take advantage of matrix sparsity. For instance, MProd(), the matrix multiplication function, performs the minimum amount of work required based on the types of its arguments.

To create a 2x3 matrix with initialized values:

m0 := M([]int{2,3},
        1.0, 2.0, 3.0,
        4.0, 5.0, 6.0)

To create a 4x4 matrix with sparse diagonal representation:

m1 := Diag(1.0, 2.0, 3.0, 4.0)

To create a 4x6 matrix with sparse diagonal representation:

m2 := SparseDiag(4, 6, 1.0, 2.0, 3.0, 4.0)

To create a 4x4 identity matrix with sparse diagonal representation:

m3 := Eye(4)

To create an unpopulated 3x4 sparse coo matrix:

m4 := SparseCoo(3, 4)

To create a 3x4 sparse coo with half the items randomly populated:

m5 := SparseRand(3, 4, 0.5)
m6 := SparseRandN(3, 4, 0.5)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All(array NDArray) bool

Returns true if and only if all items are nonzero

func AllF

func AllF(array NDArray, f func(v float64) bool) bool

Returns true if f is true for all array elements

func AllF2

func AllF2(array NDArray, f func(v1, v2 float64) bool, other NDArray) bool

Returns true if f is true for all pairs of array elements in the same position

func Any

func Any(array NDArray) bool

Returns true if and only if any item is nonzero

func AnyF

func AnyF(array NDArray, f func(v float64) bool) bool

Returns true if f is true for any array element

func AnyF2

func AnyF2(array NDArray, f func(v1, v2 float64) bool, other NDArray) bool

Returns true if f is true for any pair of array elements in the same position

func Equal

func Equal(array, other NDArray) bool

Returns true if and only if all elements in the two arrays are equal

func Fill

func Fill(array NDArray, value float64)

Set all array elements to the given value

func Max

func Max(array NDArray) float64

Get the value of the largest array element

func Min

func Min(array NDArray) float64

Get the value of the smallest array element

func Norm

func Norm(m Matrix, ord float64) float64

Get the matrix norm of the specified ordinality (1, 2, infinity, ...)

func Sum

func Sum(array NDArray) float64

Return the sum of all array elements

func ToMat64

func ToMat64(m Matrix) *mat64.Dense

Convert our matrix type to mat64's matrix type

Types

type ArraySparsity

type ArraySparsity int

ArraySparsity indicates the representation type of the matrix

const (
	DenseArray ArraySparsity = iota
	SparseCooMatrix
	SparseDiagMatrix
)

type DistType

type DistType int

Distance calculations we support

const (
	EuclideanDist DistType = iota
)

type Matrix

type Matrix interface {
	NDArray

	// Set the values of the items on a given column
	ColSet(col int, values []float64)

	// Get a particular column for read-only access. May or may not be a copy.
	Col(col int) []float64

	// Get the number of columns
	Cols() int

	// Get a column vector containing the main diagonal elements of the matrix
	Diag() Matrix

	// Treat the rows as points, and get the pairwise distance between them.
	// Returns a distance matrix D such that D_i,j is the distance between
	// rows i and j.
	Dist(t DistType) Matrix

	// Get the matrix inverse
	Inverse() (Matrix, error)

	// Solve for x, where ax = b and a is `this`.
	LDivide(b Matrix) Matrix

	// Get the result of matrix multiplication between this and some other
	// matrices. Matrix dimensions must be aligned correctly for multiplication.
	// If A is m x p and B is p x n, then C = A.MProd(B) is the m x n matrix
	// with C[i, j] = \sum_{k=1}^p A[i,k] * B[k,j].
	MProd(others ...Matrix) Matrix

	// Get the matrix norm of the specified ordinality (1, 2, infinity, ...)
	Norm(ord float64) float64

	// Set the values of the items on a given row
	RowSet(row int, values []float64)

	// Get a particular column for read-only access. May or may not be a copy.
	Row(row int) []float64

	// Get the number of rows
	Rows() int

	// Return the same matrix, but with axes transposed. The same data is used,
	// for speed and memory efficiency. Use Copy() to create a new array.
	T() Matrix

	// Return a sparse coo copy of the matrix. The method will panic
	// if any off-diagonal elements are nonzero.
	SparseCoo() Matrix

	// Return a sparse diag copy of the matrix. The method will panic
	// if any off-diagonal elements are nonzero.
	SparseDiag() Matrix
}

A two dimensional array with some special functionality

func Diag

func Diag(diag ...float64) Matrix

Create a square matrix with the specified elements on the main diagonal, and zero elsewhere.

func Dist

func Dist(m Matrix, t DistType) Matrix

Treat the rows as points, and get the pairwise distance between them. Returns a distance matrix D such that D_i,j is the distance between rows i and j.

func Eye

func Eye(size int) Matrix

Create a square sparse identity matrix of the specified dimensionality.

func Inverse

func Inverse(a Matrix) (Matrix, error)

Get the matrix inverse

func LDivide

func LDivide(a, b Matrix) Matrix

Solve for x, where ax = b.

func M

func M(rows, cols int, array ...float64) Matrix

Create a matrix from literal data

func M2

func M2(array ...[]float64) Matrix

Create a matrix from literal data and the provided shape

func MProd

func MProd(array Matrix, others ...Matrix) Matrix

Get the result of matrix multiplication between this and some other array(s). All arrays must have two dimensions, and the dimensions must be aligned correctly for multiplication. If A is m x p and B is p x n, then C = A.MProd(B) is the m x n matrix with C[i, j] = \sum_{k=1}^p A[i,k] * B[k,j].

func Solve

func Solve(a, b Matrix) Matrix

Solve is an alias for LDivide

func SparseCoo

func SparseCoo(rows, cols int, array ...float64) Matrix

Create a sparse matrix of the specified dimensionality. This matrix will be stored in coordinate format: each entry is stored as a (x, y, value) triple. The first len(array) elements of the matrix will be initialized to the corresponding nonzero values of array.

func SparseDiag

func SparseDiag(rows, cols int, diag ...float64) Matrix

Create a sparse matrix of the specified dimensionality. This matrix will be stored in diagonal format: the main diagonal is stored as a []float64, and all off-diagonal values are zero. The matrix is initialized from diag, or to all zeros.

func SparseRand

func SparseRand(rows, cols int, density float64) Matrix

Create a sparse coo matrix, randomly populated so that approximately density * rows * cols cells are filled with random values uniformly distributed in [0,1). Note that if density is close to 1, this function may be extremely slow.

func SparseRandN

func SparseRandN(rows, cols int, density float64) Matrix

Create a sparse coo matrix, randomly populated so that approximately density * rows * cols cells are filled with random values in the range [-math.MaxFloat64, +math.MaxFloat64] distributed on the standard Normal distribution. Note that if density is close to 1, this function may be extremely slow.

func ToMatrix

func ToMatrix(m mat64.Matrix) Matrix

Convert mat64's matrix type to our matrix type

type NDArray

type NDArray interface {

	// Return the element-wise sum of this array and one or more others
	Add(others ...NDArray) NDArray

	// Returns true if and only if all items are nonzero
	All() bool

	// Returns true if f is true for all array elements
	AllF(f func(v float64) bool) bool

	// Returns true if f is true for all pairs of array elements in the same position
	AllF2(f func(v1, v2 float64) bool, other NDArray) bool

	// Returns true if and only if any item is nonzero
	Any() bool

	// Returns true if f is true for any array element
	AnyF(f func(v float64) bool) bool

	// Returns true if f is true for any pair of array elements in the same position
	AnyF2(f func(v1, v2 float64) bool, other NDArray) bool

	// Return the result of applying a function to all elements
	Apply(f func(float64) float64) NDArray

	// Get the matrix data as a flattened 1D array; sparse matrices will make
	// a copy first.
	Array() []float64

	// Create a new array by concatenating this with another array along the
	// specified axis. The array shapes must be equal along all other axes.
	// It is legal to add a new axis.
	Concat(axis int, others ...NDArray) NDArray

	// Returns a duplicate of this array
	Copy() NDArray

	// Counts the number of nonzero elements in the array
	CountNonzero() int

	// Returns a dense copy of the array
	Dense() NDArray

	// Return the element-wise quotient of this array and one or more others.
	// This function defines 0 / 0 = 0, so it's useful for sparse arrays.
	Div(others ...NDArray) NDArray

	// Returns true if and only if all elements in the two arrays are equal
	Equal(other NDArray) bool

	// Set all array elements to the given value
	Fill(value float64)

	// Get the coordinates for the item at the specified flat position
	FlatCoord(index int) []int

	// Get an array element in a flattened verison of this array
	FlatItem(index int) float64

	// Set an array element in a flattened version of this array
	FlatItemSet(value float64, index int)

	// Get an array element
	Item(index ...int) float64

	// Return the result of adding a scalar value to each array element
	ItemAdd(value float64) NDArray

	// Return the result of dividing each array element by a scalar value
	ItemDiv(value float64) NDArray

	// Return the reuslt of multiplying each array element by a scalar value
	ItemProd(value float64) NDArray

	// Return the result of subtracting a scalar value from each array element
	ItemSub(value float64) NDArray

	// Set an array element
	ItemSet(value float64, index ...int)

	// Returns the array as a matrix. This is only possible for 1D and 2D arrays;
	// 1D arrays of length n are converted into n x 1 vectors.
	M() Matrix

	// Get the value of the largest array element
	Max() float64

	// Get the value of the smallest array element
	Min() float64

	// Return the element-wise product of this array and one or more others
	Prod(others ...NDArray) NDArray

	// The number of dimensions in the matrix
	NDim() int

	// Return a copy of the array, normalized to sum to 1
	Normalize() NDArray

	// Get a 1D copy of the array, in 'C' order: rightmost axes change fastest
	Ravel() NDArray

	// A slice giving the size of all array dimensions
	Shape() []int

	// The total number of elements in the matrix
	Size() int

	// Get an array containing a rectangular slice of this array.
	// `from` and `to` should both have one index per axis. The indices
	// in `from` and `to` define the first and just-past-last indices you wish
	// to select along each axis. Negative indexing is supported: when slicing,
	// index -1 refers to the item just past the last and -arr.Size() refers to
	// the first element.
	Slice(from []int, to []int) NDArray

	// Ask whether the matrix has a sparse representation (useful for optimization)
	Sparsity() ArraySparsity

	// Return the element-wise difference of this array and one or more others
	Sub(others ...NDArray) NDArray

	// Return the sum of all array elements
	Sum() float64

	// Visit all matrix elements, invoking a method on each. If the method
	// returns false, iteration is aborted and VisitNonzero() returns false.
	// Otherwise, it returns true.
	Visit(f func(pos []int, value float64) bool) bool

	// Visit just nonzero elements, invoking a method on each. If the method
	// returns false, iteration is aborted and VisitNonzero() returns false.
	// Otherwise, it returns true.
	VisitNonzero(f func(pos []int, value float64) bool) bool
}

A NDArray is an n-dimensional array of numbers which can be manipulated in various ways. Concrete implementations can differ; for instance, sparse and dense representations are possible.

func A

func A(shape []int, values ...float64) NDArray

Create an array from literal data

func A1

func A1(values ...float64) NDArray

Create a 1D array

func A2

func A2(rows ...[]float64) NDArray

Create a 2D array

func Add

func Add(array NDArray, others ...NDArray) NDArray

Return the element-wise sum of this array and one or more others

func Apply

func Apply(array NDArray, f func(float64) float64) NDArray

Return the result of applying a function to all elements

func Concat

func Concat(axis int, array NDArray, others ...NDArray) NDArray

Create a new array by concatenating this with one or more others along the specified axis. The array shapes must be equal along all other axes. It is legal to add a new axis.

func Dense

func Dense(size ...int) NDArray

Create an NDArray of float64 values, initialized to zero

func Div

func Div(array NDArray, others ...NDArray) NDArray

Return the element-wise quotient of this array and one or more others. This function defines 0 / 0 = 0, so it's useful for sparse arrays.

func ItemAdd

func ItemAdd(array NDArray, value float64) NDArray

Add a scalar value to each array element

func ItemDiv

func ItemDiv(array NDArray, value float64) NDArray

Divide each array element by a scalar value

func ItemProd

func ItemProd(array NDArray, value float64) NDArray

Multiply each array element by a scalar value

func ItemSub

func ItemSub(array NDArray, value float64) NDArray

Subtract a scalar value from each array element

func Normalize

func Normalize(array NDArray) NDArray

Return a copy of the array, normalized to sum to 1

func Ones

func Ones(size ...int) NDArray

Create an NDArray of float64 values, initialized to one

func Prod

func Prod(array NDArray, others ...NDArray) NDArray

Return the element-wise product of this array and one or more others

func Rand

func Rand(size ...int) NDArray

Create a dense NDArray of float64 values, initialized to uniformly random values in [0, 1).

func RandN

func RandN(size ...int) NDArray

Create a dense NDArray of float64 values, initialized to random values in [-math.MaxFloat64, +math.MaxFloat64] distributed on the standard Normal distribution.

func Ravel

func Ravel(array NDArray) NDArray

Get a 1D copy of the array, in 'C' order: rightmost axes change fastest

func Slice

func Slice(array NDArray, from []int, to []int) NDArray

Get an array containing a rectangular slice of this array. `from` and `to` should both have one index per axis. The indices in `from` and `to` define the first and just-past-last indices you wish to select along each axis. You can also use negative indices to represent the distance from the end of the array, where -1 represents the element just past the end of the array.

func Sub

func Sub(array NDArray, others ...NDArray) NDArray

Return the element-wise difference of this array and one or more others

func WithValue

func WithValue(value float64, size ...int) NDArray

Create an NDArray of float64 values, initialized to value

func Zeros

func Zeros(size ...int) NDArray

Create an NDArray of float64 values, initialized to zero

Jump to

Keyboard shortcuts

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