Linear Algebra  C++ addon for nodejs to implement linear algebra efficiently
Static Private Member Functions | Private Attributes | Static Private Attributes | List of all members
WrappedArray Class Reference

Inherits ObjectWrap.

Static Private Member Functions

static WrappedArrayCreate (int m, int n, Local< Context > context, Local< Array > array)
 
static WrappedArrayCreate (int m, int n, float *data=NULL)
 
static void ToString (const FunctionCallbackInfo< Value > &args)
 
static void Inspect (const FunctionCallbackInfo< Value > &args)
 
static void Ones (const FunctionCallbackInfo< Value > &args)
 
static void Zeros (const FunctionCallbackInfo< Value > &args)
 
static void Eye (const FunctionCallbackInfo< Value > &args)
 
static void Diag (const FunctionCallbackInfo< Value > &args)
 
static void Read (const FunctionCallbackInfo< Value > &args)
 
static void Rand (const FunctionCallbackInfo< Value > &args)
 
static void Dup (const FunctionCallbackInfo< Value > &args)
 
static void Find (const FunctionCallbackInfo< Value > &args)
 
static void FindGreater (const FunctionCallbackInfo< Value > &args)
 
static void FindLessEqual (const FunctionCallbackInfo< Value > &args)
 
static void Neg (const FunctionCallbackInfo< Value > &args)
 
static void Log (const FunctionCallbackInfo< Value > &args)
 
static void Sqrt (const FunctionCallbackInfo< Value > &args)
 
static void Abs (const FunctionCallbackInfo< Value > &args)
 
static void Transpose (const FunctionCallbackInfo< Value > &args)
 
static void Hadamard (const FunctionCallbackInfo< Value > &args)
 
static void Mul (const FunctionCallbackInfo< Value > &args)
 
static void Mulp (const FunctionCallbackInfo< Value > &args)
 
static void Asum (const FunctionCallbackInfo< v8::Value > &args)
 
static void Sum (const FunctionCallbackInfo< v8::Value > &args)
 
static void Mean (const FunctionCallbackInfo< v8::Value > &args)
 
static void Norm (const FunctionCallbackInfo< v8::Value > &args)
 
static void Add (const FunctionCallbackInfo< v8::Value > &args)
 
static void Sub (const FunctionCallbackInfo< v8::Value > &args)
 
static void Inv (const FunctionCallbackInfo< v8::Value > &args)
 
static void Invp (const FunctionCallbackInfo< v8::Value > &args)
 
static void Pinv (const FunctionCallbackInfo< v8::Value > &args)
 
static void Svd (const FunctionCallbackInfo< v8::Value > &args)
 
static void Pca (const FunctionCallbackInfo< v8::Value > &args)
 
static void GetRows (const FunctionCallbackInfo< v8::Value > &args)
 
static void RemoveRow (const FunctionCallbackInfo< v8::Value > &args)
 
static void GetColumns (const FunctionCallbackInfo< v8::Value > &args)
 
static void RemoveColumn (const FunctionCallbackInfo< v8::Value > &args)
 
static void AppendColumns (const FunctionCallbackInfo< v8::Value > &args)
 
static void RotateColumns (const FunctionCallbackInfo< v8::Value > &args)
 
static void Reshape (const FunctionCallbackInfo< v8::Value > &args)
 
static void Solve (const v8::FunctionCallbackInfo< v8::Value > &args)
 
static void Get (const FunctionCallbackInfo< v8::Value > &args)
 
static void Set (const FunctionCallbackInfo< v8::Value > &args)
 
static void MakeIterator (const FunctionCallbackInfo< v8::Value > &args)
 

Private Attributes

int m_
 
int n_
 
float * data_
 
bool isVector
 
int dataSize_
 
int maxPrint_
 
char * name_
 

Static Private Attributes

static v8::Persistent< v8::Function > constructor
 

Detailed Description

This is the main class to represent a matrix. It is a nodejs compatible object.

Matrices are stored in column order, this is to simplify access to (some) libraries (esp. cuda). The internal data type is always a float, which is good enough for most situations. The comments for the C++ code contain some javascript examples

Member Function Documentation

void WrappedArray::Abs ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Absolute value of matrix

Returns a new matrix which is an copy of the target with each element set to positive

It takes 0 args:

void WrappedArray::Add ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Add two matrices

Performs one of

  • Element wise addition of two matrices. The other array to be added must be the same shape or vector matching shape
  • Row or column wise addition of a vector to the target ( if adding a row vector to a target the number of elements in the vector must match the number of columns in the matrix).
  • Simple element wise addition - adds a single number to every element in the target
Parameters
[in]oneof
  • a matrix
  • a vector
  • a number
Returns
a new matrix
void WrappedArray::AppendColumns ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Append columns to a matrix

Append column vectors. The target is expanded to have N+K columns. The matrix should have the same length as the matrix.m ( rows ). K is the width of the added column matrix

var MATRIX = lalg.rand(10,6) ;
var V = lalg.rand(3,10) ;
var R = MATRIX.appendColumns(V) ;
Parameters
[in]thecolumn(s) to append to the matrix
Returns
a new matrix containing the additional column.
void WrappedArray::Asum ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

sum all absolute value of each element

Returns
the sum of all absolute values in the matrix
static WrappedArray* WrappedArray::Create ( int  m,
int  n,
Local< Context >  context,
Local< Array >  array 
)
inlinestaticprivate

Create an array with some data provided in a javascript Array

Parameters
[in]mnumber of rows in the matrix
[in]nnumber of cols in the matrix
[in]arraydata to put into the array - column major order
static WrappedArray* WrappedArray::Create ( int  m,
int  n,
float *  data = NULL 
)
inlinestaticprivate

Create an array with some (optional) data. This will be the base call for creation for internal methods.

Parameters
[in]mnumber of rows in the matrix
[in]nnumber of cols in the matrix
[in]datadata to put into the array - column major order
void WrappedArray::Diag ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Returns a new square matrix, where the principal diagonal is formed from a vector. The size of the array is the vector length squared. All other elements are zero.

Parameters
aWrappedArray containing a vector to use as the diagonal
void WrappedArray::Dup ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Duplicate a matrix

Returns a new matrix which is an identical copy of the target

void WrappedArray::Eye ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Returns a new square identity matrix.

An identity matrix is a leading diagonal of 1.0 and all other elements are 0. Any matrix multiplied by (a suitable shaped) identity will return itself.

Parameters
thenumber of rows (m) and columns (n)
Returns
a new matrix, each element is set to 1.0
void WrappedArray::Find ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Find matching values in a matrix

Returns a new matrix where a matching element is set to the given parameter if the value matches the supplied number. An optional parameter defines the match accuracy ( since we are working with real numbers ). If the 2nd parameter is not given the orginal target element is dropped in.

Parameters
[in]thenumber to find ( default 1 )
[in]thevalue to pop into the matching elements
[in]theaccuracy to find a match default 0.000001
void WrappedArray::FindGreater ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Keep greater values in a matrix

Returns a new matrix where a matching element is set to supplied value if an element is less than or equal to the supplied number, otherwise it's the target value. In other words keep the values that are > than the input and zero the rest. If the 2nd parameter is not given (null) the orginal target element is dropped in.

Parameters
[in]thenumber to find ( default 1 )
[in]thevalue to pop into the matching elements
void WrappedArray::FindLessEqual ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Keep less (or same) values in a matrix

Returns a new matrix where a matching element is set to the supplied value if an element is greater than the supplied number, otherwise it's the target value. In other words keep the values that are <= than the input and zero the rest. If the 2nd parameter is not given (null) the orginal target element is dropped in.

Parameters
[in]thenumber to find ( default 1 )
[in]thevalue to pop into the matching elements
void WrappedArray::Get ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Get a value from the matrix

Returns a value from the matrix at the X,Y. If a single index is given it is used an an absolute address into the underlying store. Negative indices count from the end.

Parameters
[in,default=0]M the row index ( or the absolute index is N is missing )
[in,optional]N the column index
Returns
the value in the matrix at required
void WrappedArray::GetColumns ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Copy columns from the target

Build a new matrix containing some of the columns of the target. The target is unchanged. The input can be a single number or an array of column indices to copy from the target. The reulting array will be MxK, where k is the number of columns requested and M is the number of rows in the target.

var R = MATRIX.getColumns( [0,2] ) ;
Parameters
[in,default=0]the column indices to copy from the array , may be a number or an array of numbers
Returns
a new matrix containing the copies of the requested columns.
void WrappedArray::GetRows ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Copy rows from the target

Build a new matrix containing some of the rows or the target. The target is unchanged. The input can be a single number or an array of rows to copy from the target. The reulting array will be KxN, where k is the number of rows requested and N is the number of columns in the target.

var R = MATRIX.getRows( [ 1,2,2] ) ;
Parameters
[in,default=0]the rows to copy from the matrix, may be a number or an array of numbers
Returns
a new matrix containing the copies of the requested rows.
void WrappedArray::Hadamard ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Hadamard (Schur) multiply of two matrices

This is (VERY) different to normal matrix multipliy. Also the vector x matrix version just multiplies each column (or row) entry by the corresponding vector element.

It is the .* operator in Matlab or Octave

Performs one of

  • Element wise multiplication of two matrices. The other array to be added must be the same shape or vector matching shape
  • Row or column wise multiplication of a vector to the target ( if adding a row vector to a target the number of elements in the vector must match the number of columns in the matrix).
  • Simple element wise multiplication - multiplication a single number by every element in the target
Parameters
[in]oneof
  • a matrix
  • a vector
  • a number
Returns
a new matrix
void WrappedArray::Inspect ( const FunctionCallbackInfo< Value > &  args)
staticprivate

internally calls ToString.

See also
ToString
void WrappedArray::Inv ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Matrix inverse

Calculate the inverse of a matrix. A matrix inverse multiplied by itself is an identity matrix. The input matrix must be square. A newly created inverse is returned, the original remains intact.

Returns
the new matrix inverse of the target
void WrappedArray::Invp ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Matrix inverse

Calculate the inverse of a matrix. A matrix inverse multiplied by itself is an identity matrix. The input matrix must be square. The return is a promise ( no args ) or, if a callback function is provided undefined. A newly created inverse is resolved into the promise or the callback; the original remains intact.

Parameters
[in,optional]a callback function prototype = function(err,inv) { }
Returns
a promise (if the callback function is not given)
void WrappedArray::Log ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Log a matrix

Returns a new matrix which is an copy of the target with each element being the natural log of the target. Since we're not doing complex values (yet:o), negative and zero values will result in NaN

It takes 0 args:

void WrappedArray::MakeIterator ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

get javascript iterator

This creates an iterator object so we can iterate over the elements of a matrix.

var lalg = require( "lalg" ) ;
var R = lalg.rand( 10,5 ) ;
var arr = Array.from( R ) ;
Returns
an object with a method next() that matches specs for an iterator
void WrappedArray::Mean ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

mean of rows or columns of a matrix

This calculates the mean of rows or columns of a matrix into a row or column vector. If the target is a vector this will return the mean of all the elements into a single number.

Parameters
[in,default=0]the dimension to inspect - 0 = mean of columns, 1 = mean of rows.
Returns
the vector of the mean of columns or rows. In the case that the target is a vector, this is a number
void WrappedArray::Mul ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Mul - multiply a matrix

Perform matrix multiplication. The target must be MxK and the other must be KxN a new matrix of MxN is produced. This is fine for small matrices, if large matrices are to be multiplied, consider Mulp. If a scalar is passed in all elements in the array are multiplied by it.

See also
Mulp for a version which returns a promise
Parameters
theother matrix or a number
Returns
a new matrix
void WrappedArray::Mulp ( const FunctionCallbackInfo< Value > &  args)
staticprivate

multiply a matrix in non-blocking mode

Perform matrix multiplication. The target must be MxK and the other must be KxN a new matrix of MxN is produced. This will run in non-blocked mode.

There are two ways to use this, pass in an optional callback or accept a returned promise. Passing in a callback will prevent the Promise from being returned.

See also
Mul for a version which is blocking
Parameters
[in]theother matrix
[in]acallback of prototype function(err,MATRIX){ }
Returns
a promise which will resolve to a new Matrix
void WrappedArray::Neg ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Negate a matrix

Returns a new matrix which is an copy of the target with each element sign reversed

It takes 0 args:

void WrappedArray::Norm ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Euclidian norm of rows or columns of a matrix

This calculates the norms of a row or column of a matrix into a row or column vector. If the target is a vector this will return the norm as a number.

Parameters
[in,default=0]the dimension to sum - 0 = sum columns, 1 = sum rows
Returns
the vector of the norms of columns or rows or a number if the target is a vector.
void WrappedArray::Ones ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Returns a new matrix with all values set to 1.0

Parameters
thenumber of rows (m) defaults to 0
thenumber of columns (n) defaults to m
Returns
a new matrix, each element is set to 1.0
void WrappedArray::Pca ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Principal component analysis

Calculate the PCA factor of a matrix. The returned factor can be multiplies by any observation (row) or observations (the whole matrix) to get a reduced dimension set of features. The amount of information (variance) to keep is passed in as an argument.

IMPORTANT: the target features should be mean normalized for this to be accurate. Mean normalized data has a zero mean for each feature ( each col mean = 0 ).

The returned factor is a NxK array. Where K<M. We can reduce the dimensions of the target from M to K by multiplying the observation(s) by the factor.

In this example we extract the mean - in case we want to normalize unseen features.

var lalg = require('lalg');
var A = lalg.rand(10) ; // a 10x10 random array
var mean = A.mean() ) ; // keep the mean for later use
// normalize the array befopre PCA
var factor = A.sub( mean ).pca( 0.95 ) ; // keep 95% of the information
// normalize any data we will reduce as well (need not be the same as the inputs )
var ARD = A.sub(mean).mul( factor ) ; // A's features mapped to a reduced set of dimensions
Parameters
theamount of variance to return (0 to 1.0). Default is 0.97
Returns
a matrix to multiple an obeservation (matrix) by to reduce its dimensionality
See also
Diag
void WrappedArray::Pinv ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Get the pseudo inverse of a matrix

Calculate the pseudo inverse of a matrix. A matrix multiplied by its pseudo inverse is an identity matrix. A newly created inverse is returned, the original remains intact.

This seems to have a problem with vectors - don't invert a vector
until we know what it may mean.
Returns
the new matrix pseudo inverse of the target
void WrappedArray::Rand ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Returns a new matrix with all values set to a random integer between -10 and 10 (inclusive)

The randomness isn't very good, it's used for testing.

Parameters
void WrappedArray::Read ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Read a matrix from a stream

This takes a stream which emits data events for each row. One such stream is the fast-csv.

var lalg = require('lalg');
var fs = require('fs');
var csv = require("fast-csv");
const rr = fs.createReadStream('wine.csv');
var csvStream = csv() ;
rr.pipe(csvStream);
lalg.read( csvStream )
.then( function(X) {
console.log( X ) ;
.catch( function(err) {
console.log( "Fail", err ) ;
});
Parameters
astream that presents data events with a single Array of numbers
Returns
a Promise that will resolve to a matrix
void WrappedArray::RemoveColumn ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Remove a column from a matrix

Return a column vector which is the requested column of the target. The target is shrunk to have N-1 columns.

var R = MATRIX.removeColumn(4) ;
Parameters
[in,default=0]the column index (zero based) to remove from the array
Returns
a column vector containing the extracted column.
void WrappedArray::RemoveRow ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Remove a row from a matrix

Return a vector which is the requested row of the target. The target is shrunk to have M-1 rows. This is not very efficient.

var R = MATRIX.removeRow(4) ;
Parameters
[in]therow index (zero based) to remove from the array default=0
Returns
a row vector containing the extracted row.
void WrappedArray::Reshape ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Reshape the matrix

Change the shape of the matrix. If the shape is smaller ( new M x new N < M x N ) the memory is left alone. Otherwise a new buffer is allocated, and the additional elements are initialized to zero. This operation is done in place - the target is changed. The default is to produce a (M*N)x1 vector is no paramters are given.

Parameters
[in,default=m*n]the number of rows to have in the new shape
[in,default=1]the number of columns to have in the new shape
void WrappedArray::RotateColumns ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Rotate columns in a matrix

Rotate column vectors. A positive number means rotate to the left, a negative number rotates to the right. The rotation count is internally and silently limited using modulus the number of columns.

If there is a requirement to rotate rows, transpose the matrix then call this, the transpose back.

B = A.rotateColumns( 1 ) ;
C = A.rotateColumns( -2 ) ;
    | 1.00 2.00 3.00 4.00 5.00 |
A = | 1.00 2.00 3.00 4.00 5.00 |
    | 1.00 2.00 3.00 4.00 5.00 |


    | 2.00 3.00 4.00 5.00 1.00 |
B = | 2.00 3.00 4.00 5.00 1.00 |
    | 2.00 3.00 4.00 5.00 1.00 |


    | 4.00 5.00 1.00 2.00 3.00 |
C = | 4.00 5.00 1.00 2.00 3.00 |
    | 4.00 5.00 1.00 2.00 3.00 |
Parameters
[in,default=1]the rotation count.
Returns
a new matrix containing the rotated columns.
void WrappedArray::Set ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Set a value in the matrix

Overwrites a the value in the matrix at the X,Y. If the target is a vector only the first argument is used. If a single index is given it is used an an absolute address into the underlying store. Negative indices count from the end.

Parameters
[in]valueto set into the matrix
[in,default=0]M the row index ( or the absolute index is N is missing )
[in,optional]N the column index
Returns
the previous value in the matrix at location (m,n)
void WrappedArray::Solve ( const v8::FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Solves a function for its minimum

Solves the function starting at the given Array based starting position. After this is finished the array is set to the global minimum.

This requires a gradient function object to be passed as a parameter. The gradient function is an object with two methods:

  • value( lalg.Array x ) returns Number
  • gradient( lalg.Array x ) returns lalg.Array gradients

The solver name parameter should be one of

  • BFGS
  • CGD
  • NEWTON
  • NELDERMEAD
  • LBFGS
  • CMAES
var lalg = require( "lalg" ) ;
var R = lalg.rand( 2,1 ) ;
function gradFunction() {
// f(x,y)
this.value = function( x ) {
return x.get(0)*x.get(0) + x.get(1)*x.get(1) - x.get(0) - x.get(1) ;
} ;
// df(x,y)/dx , df(x,y)/dy
this.gradient = function( x ) {
var rc = new lalg.Array(x.length, 1 ) ;
rc.set( 2*x.get(0) - 1 ,0 ) ;
rc.set( 2*x.get(1) - 1 ,1 ) ;
return rc ;
}
} ;
var f = new gradFunction() ;
A = new lalg.Array( 2, 1, [ 0.1, 0.1] ) ;
A.solve( f, "LBFGS" ) ;
console.log( "Actual Min:", f.value(A), "@", Array.from(A) ) ;
Parameters
[in]thefunction to solve
void WrappedArray::Sqrt ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Square root a matrix

Returns a new matrix which is an copy of the target with each element being the square root of the target. Negative target values will result in NaN entries.

It takes 0 args:

void WrappedArray::Sub ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Subtract two matrices

Performs one of

  • Element wise subtraction of two matrices. The other array to be subtracted from target must be the same shape or vector matching shape
  • Row or column wise subtraction of a vector from the target ( if subtracting a row vector from a target the number of elements in the vector must match the number of columns in the matrix).
  • Simple element wise subtraction - subtracts a single number from every element in the target
Parameters
[in]oneof
  • a matrix
  • a vector
  • a number
Returns
a new matrix
void WrappedArray::Sum ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Sum the rows or columns of a matrix into a vector

This sums the rows or columns of a matrix into a row or column vector. If the target is a vector this will just sum all the elements into a single number.

Parameters
[in,default=0]the dimension to sum - 0 = sum columns, 1 = sum rows.
Returns
the vector of the summed columns or rows or a number if the target is a vector.
void WrappedArray::Svd ( const FunctionCallbackInfo< v8::Value > &  args)
staticprivate

Singular Value Decomposition of a matrix

Calculate the SVD of a matrix. This will return an object with 3 attributes: U, S and VT. This factorizes the matrix to 3 components.

var lalg = require('lalg');
var A = lalg.rand(10) ; // a 10x10 random array
var svd = A.svd() ;
var B = U x lalg.diag(S) x VT ;
// B and A should be the same ! (math precision permitting)
Returns
a JS object with 3 components
  • U the left singular vectors
  • S a vector of the eigenvalues ( use Diag to conver to a matrix )
  • VT the transposed right singular vectors
See also
Diag
void WrappedArray::ToString ( const FunctionCallbackInfo< Value > &  args)
staticprivate

returns a string representation of the matrix

This will print up to maxPrint rows and columns

void WrappedArray::Transpose ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Transpose a matrix

Returns a new matrix which is an transpose of the target.

It takes 0 args:

void WrappedArray::Zeros ( const FunctionCallbackInfo< Value > &  args)
staticprivate

Returns a new matrix with all values set to .0

Parameters
thenumber of rows (m) defaults to 0
thenumber of columns (n) defaults to m
Returns
a new matrix, each element is set to 0.0

Member Data Documentation

Persistent< Function > WrappedArray::constructor
staticprivate

a nodejs constructor for this object

float* WrappedArray::data_
private

the data buffer holding the values

int WrappedArray::dataSize_
private

private - used to remember the last data allocation size

bool WrappedArray::isVector
private

helper flag to see whether the target is a vector Mx1 or 1xN

int WrappedArray::m_
private

the number of rows in the matrix

int WrappedArray::maxPrint_
private

the number of rows & columns to print out in toString()

int WrappedArray::n_
private

the number of columns in the matrix

char* WrappedArray::name_
private

The name of this matrix - useful for keeping track of things


The documentation for this class was generated from the following file: