Facemorph
Class BigMat

java.lang.Object
  extended by Facemorph.BigMat
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
Gaussian

public class BigMat
extends java.lang.Object
implements java.io.Serializable

Arbitrary size matrix utility class particularly useful are the singular value decomposition (SVD) and jacobi routines SVD is used to do least-squares matrix inversion and eigen analysis jacobi is used for eigen analysis

See Also:
Serialized Form

Constructor Summary
BigMat()
          A (possibly large) rectangular matrix
BigMat(BigMat P)
           
BigMat(BigMat P, int x, int y)
           
BigMat(double[][] d)
          Constuct a BigMat using an array of doubles (row major)
BigMat(int x, int y)
          Construct a BigMat with the size specified
 
Method Summary
 void add(BigMat mat)
          Adds mat to this
 void add(int x, int y, double val)
          Set the matrix value (matrix[x][y]=val)
 BigMat copy()
          Create a copy of this matrix
 void copy(BigMat mat)
          Copy the matrix given into this
 void display(java.lang.String name)
          Write this matrix out to the console for debugging
 void displayMatlab(java.lang.String name)
           
static double dotProduct(double[] left, double[] right)
          Return the inner (dot) product for two vectors
 boolean equals(BigMat mat)
          Checks if the two matrices are identical
 boolean equals(BigMat mat, double delta)
          Checks if the two matrices are the same to within a given tollerance
 double get(int x, int y)
          Retrieve the value of the matrix
 double[] getColumn(int colIndex)
           
 double[] getColumnCopy(int colIndex)
          Returns copy of a particular column
 int getHeight()
          Get the height
 double[] getRowCopy(int rowIndex)
          Returns copy of a particular row
 int getWidth()
          Get the width
static BigMat identity(int size)
           
 BigMat invertSVD(double threshold)
          find the inverse (possibly in the least squares sense) using SVD
 boolean jacobi(double[] d, BigMat v, int[] nrot)
          Jacobi computes all eigenvalues and eigenvectors of a real symmetric matrix The input matrix elements above the diagonal are destroyed.
 double magnitude()
          Returns the magnitude of this matrix, there are probably more efficient ways of doing this
static void main(java.lang.String[] args)
          Main method just used for testing
 BigMat multiply(BigMat m)
          Multiply this matrix by another matrix
 void multiply(double x)
          Multiply this BigMat by a scalar
 double[] multiply(double[] x)
          Multiply a vector by this matrix
 BigMat multiplyOtherTranspose(BigMat m)
          Multiply the this matrix by the transpose of another matrix
 BigMat multiplySelfTranspose(boolean transpose, boolean skipFirst)
          Multiply this matrix by the transpose of itself
 BigMat multiplyTranspose(BigMat m)
          Multiply this matrix by another matrix
 double[] multiplyTranspose(double[] x)
          Multiply the vector x by the transpos of this matrix
 void normaliseColumns()
          Normalise the columns of this matrix
 void normaliseRows()
          Normalise the rows of this matrix
 void put(int x, int y, double val)
          Set the matrix value (matrix[x][y]=val)
 boolean qrdcmp(BigMat Q, BigMat R)
          Decomposes this square matrix into an orthonormal matrix Q and an upper triangular matrix R such that this = R.multiply(Q)
 boolean qrdcmp(BigMat a, double[] c, double[] d)
          From numerical recipies in C ch2.10 Constructs the QR decomposition of this matrix returning the result in a[1..n][1..n].
 void qrsolv(double[] c, double[] d, double[] b, double[] x)
          Solves the set of n linear equations A.x=b .
 boolean read(java.io.DataInputStream in)
          Read this Template from the DataInputStream provided
 boolean read(java.io.StreamTokenizer st)
          Reads the matrix from the StreamTokenizer
 boolean read(java.lang.String file)
          Reads this BigMat from the file given
 void readBinary(java.io.DataInputStream in)
          Reads a BigMat from a binary file
 void readBinary(java.lang.String filename)
          Reads this BigMat in from a binary file format
 BigMat reconstructQR(double[] c, double[] d)
          Construct the Q and R matrices explicitly, using the output from qrdcmp R.multiply(Q) will give the original input matrix
static BigMat removeNaNRecords(BigMat in)
          Removes any rows from the matrix that have NaNs of INF etc.
 void rsolv(double[] d, double[] b, double[] x)
          solves the set of n linear equations R.x = b, where is R an upper triangular matrix stored in (a) this BigMat and b.
 void setColumn(int col, double[] vec)
           
 void setRow(int row, double[] vec)
           
 void setSize(int x, int y)
          Set the size of this matrix
 double SIGN(double a, double b)
          returns sign(b)*abs(a)
 void sort(double[] d)
          sorting routine for jacobi method
 void squareInPlace()
          Squares the value of each individual value in the matrix ( .^ in matlab)
 BigMat subMat(int[] rowIndex, int[] colIndex)
          Return a sub matrix containing only those columns points to by the indices.
 BigMat subMat(int x, int y)
          Returns a matrix with row x and column y removed
 BigMat subMat(int xstart, int xend, int ystart, int yend)
          Retrieve a sub-part of this matrix
 BigMat subMatCols(int[] colIndex)
          Return a sub matrix containing only those columns pointed to by the indices.
 BigMat subMatRows(int[] rowIndex)
          Return a sub matrix containing only those rows pointed to by the indices.
 void subtractFromInPlace(double val)
          Subtract each value in the matrix from val ( val - X in matlab)
 void subtractInPlace(BigMat mat)
          Subtracts mat to this
 void subtractInPlace(double val)
          Subtract a value from each value in the Matrix ( X .- val in matlab)
 double sumSquares()
           
 BigMat svbksb(double[] w, BigMat V, BigMat A, double threshold)
          SVD back substitution routine
 void svbksb(double[] w, BigMat V, double[] b, double[] x, double threshold)
          Back substitution routine for SVD.
 BigMat svbksbt(double[] w, BigMat V, BigMat A, double threshold)
          SVD back substitution routine (transposed)
 void svbksbt(double[] w, BigMat V, double[] b, double[] x, double threshold)
          Back substitution routine for SVD.
 boolean svdcmp(BigMat v, double[] w)
          Performs Singular Value Decomposition A = UwVt U replace A on output (this goes from being A to being U) v and w are filled in returns true if successful, false otherwise.
 boolean svdcmpt(BigMat v, double[] w)
          Performs Singular Value Decomposition A = UwVt U replace A on output (this goes from being A to being U) v and w are filled in returns true if successful, false otherwise.
 BigMat transposeCopy()
          Create a transposed copy of this matrix
 boolean upperTriangularBacksub(double[] X, double[] T)
          Solves AT=X for T where A = this and T and X are column vectors A must be upper triangular
 BigMat upperTriangularInverseMultiply(BigMat M)
          Calculates A^(-1)M where A = this is upper triangular, by using repeated backsubstitutions.
 double[] vectorise()
          Scan this matrix into a 1D vector
 boolean write(java.io.PrintStream ps)
          Write this matrix out a file
 boolean write(java.lang.String filename)
          Write this matrix out a file
 boolean write(java.lang.StringBuffer ps)
          Write this matrix out a String
 void writeBinary(java.io.DataOutputStream out)
          Reads a BigMat from a binary file
 void writeBinary(java.lang.String filename)
          Writes this BigMat out in a binary format
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

BigMat

public BigMat()
A (possibly large) rectangular matrix


BigMat

public BigMat(int x,
              int y)
Construct a BigMat with the size specified

Parameters:
x - The width of the matrix
y - The height of the matrix

BigMat

public BigMat(double[][] d)
Constuct a BigMat using an array of doubles (row major)

Parameters:
d - array of data

BigMat

public BigMat(BigMat P)

BigMat

public BigMat(BigMat P,
              int x,
              int y)
Method Detail

setSize

public void setSize(int x,
                    int y)
             throws BigMatException
Set the size of this matrix

Parameters:
x - The width of the matrix
y - The height of the matrix
Throws:
BigMatException - Thrown if width or height are negative

getWidth

public int getWidth()
Get the width

Returns:
The width of this matrix

getHeight

public int getHeight()
Get the height

Returns:
The height of this matrix

vectorise

public double[] vectorise()
Scan this matrix into a 1D vector

Returns:
Returns a 1D version of this matrix

normaliseColumns

public void normaliseColumns()
Normalise the columns of this matrix


normaliseRows

public void normaliseRows()
Normalise the rows of this matrix


display

public void display(java.lang.String name)
Write this matrix out to the console for debugging

Parameters:
name - The name to display above the matrix on the output.

displayMatlab

public void displayMatlab(java.lang.String name)

write

public boolean write(java.lang.String filename)
Write this matrix out a file

Parameters:
filename - The name of the file to write to
Returns:
Returns true unless an Exception occurs

write

public boolean write(java.lang.StringBuffer ps)
Write this matrix out a String

Parameters:
ps - The StringBuffer to write to
Returns:
returns true

write

public boolean write(java.io.PrintStream ps)
Write this matrix out a file

Parameters:
ps - The PrintStream to write to
Returns:
returns true

read

public boolean read(java.lang.String file)
Reads this BigMat from the file given

Parameters:
file - The name of the file to read
Returns:
true if the file was read successfully, false otherwise

read

public boolean read(java.io.DataInputStream in)
Read this Template from the DataInputStream provided

Parameters:
in - The DataInputStream to read from
Returns:
true if the Template was successfully read.

read

public boolean read(java.io.StreamTokenizer st)
Reads the matrix from the StreamTokenizer

Parameters:
st - The StreamTokenizer to read from
Returns:
returns true unless and exception occurs

readBinary

public void readBinary(java.io.DataInputStream in)
Reads a BigMat from a binary file

Parameters:
in - The DataInputStream to read from

writeBinary

public void writeBinary(java.io.DataOutputStream out)
Reads a BigMat from a binary file

Parameters:
out - The DataOutputStream to write to

writeBinary

public void writeBinary(java.lang.String filename)
Writes this BigMat out in a binary format

Parameters:
filename - The name of the file to write to

readBinary

public void readBinary(java.lang.String filename)
Reads this BigMat in from a binary file format

Parameters:
filename - The file to read from

put

public void put(int x,
                int y,
                double val)
Set the matrix value (matrix[x][y]=val)

Parameters:
x - The row to update
y - The column to update
val - The updated value

add

public void add(int x,
                int y,
                double val)
Set the matrix value (matrix[x][y]=val)

Parameters:
x - The row to update
y - The column to update
val - The updated value

get

public double get(int x,
                  int y)
Retrieve the value of the matrix

Parameters:
x - The row to get
y - The column to get
Returns:
The value of matrix[x][y]

multiply

public double[] multiply(double[] x)
                  throws BigMatException
Multiply a vector by this matrix

Parameters:
x - The 1D vector to multiply
Returns:
The resulting vector i.e. this*x
Throws:
BigMatException - Thrown if the size of the vector and matrix don't match

multiply

public BigMat multiply(BigMat m)
                throws BigMatException
Multiply this matrix by another matrix

Parameters:
m - he matrix to multiply
Returns:
The resulting matrix i.e. this*m
Throws:
BigMatException - thrown if wrong sized matrices used

multiplyTranspose

public BigMat multiplyTranspose(BigMat m)
                         throws BigMatException
Multiply this matrix by another matrix

Parameters:
m - he matrix to multiply
Returns:
The resulting matrix i.e. this*m
Throws:
BigMatException - thrown if wrong sized matrices used

multiplyOtherTranspose

public BigMat multiplyOtherTranspose(BigMat m)
                              throws BigMatException
Multiply the this matrix by the transpose of another matrix

Parameters:
m - he matrix to multiply
Returns:
The resulting matrix i.e. this*m
Throws:
BigMatException - thrown if wrong sized matrices used

multiply

public void multiply(double x)
Multiply this BigMat by a scalar

Parameters:
x - the scalar to multiply this by

multiplyTranspose

public double[] multiplyTranspose(double[] x)
Multiply the vector x by the transpos of this matrix

Parameters:
x - the vector to multiply
Returns:
returns the transformed vector x

copy

public BigMat copy()
Create a copy of this matrix

Returns:
A copy of this matrix

copy

public void copy(BigMat mat)
Copy the matrix given into this

Parameters:
mat - The matrix to copy from

transposeCopy

public BigMat transposeCopy()
Create a transposed copy of this matrix

Returns:
The transpose of this matrix

multiplySelfTranspose

public BigMat multiplySelfTranspose(boolean transpose,
                                    boolean skipFirst)
Multiply this matrix by the transpose of itself

Parameters:
transpose - flag to indicate that MtM should be calculated rather than MMt (or is it the other way around?)
skipFirst - flag to indicate if the first row should be skipped
Returns:
Returns the resulting matrix

subMat

public BigMat subMat(int xstart,
                     int xend,
                     int ystart,
                     int yend)
Retrieve a sub-part of this matrix

Parameters:
xstart - The starting x coordinate
xend - The ending x coordinate
ystart - The starting y coordinate
yend - The ending y coordinate
Returns:
The sub matrix from xstart to xend and from ystart to yend

subMat

public BigMat subMat(int x,
                     int y)
Returns a matrix with row x and column y removed

Parameters:
x - row to remove
y - column to remove
Returns:
returns the matrix with row x and column y removed

magnitude

public double magnitude()
Returns the magnitude of this matrix, there are probably more efficient ways of doing this

Returns:
Returns the magnitude of the matrix

svdcmpt

public boolean svdcmpt(BigMat v,
                       double[] w)
Performs Singular Value Decomposition A = UwVt U replace A on output (this goes from being A to being U) v and w are filled in returns true if successful, false otherwise.

Parameters:
v - Storage space for the output matrix V
w - 1D array that stores the diagonal of the W matrix (hoding any singular values)
Returns:
true if the decomposition was successful (converged within 100 iterations)

svbksbt

public BigMat svbksbt(double[] w,
                      BigMat V,
                      BigMat A,
                      double threshold)
               throws BigMatException
SVD back substitution routine (transposed)

Parameters:
w - vector of (possibly) singluar values
V - Orthogonal matrix V
A - The matrix to multiply by the invesrse of the original decomposed matrix
threshold - Threshold below which values are treated as singluar
Returns:
Returns the result of the back substitution
Throws:
BigMatException - Thrown if wrong sized matrices or vectors are used

svbksbt

public void svbksbt(double[] w,
                    BigMat V,
                    double[] b,
                    double[] x,
                    double threshold)
Back substitution routine for SVD. (transposed) Solves Ax=b where A has been converted to U*w*V using SVD This method should be called on the matrix U.

Parameters:
w - The diagonal matrix of possibly singular values, calculated by SVD
V - The orthogonal matrix V calculated by SVD
b - The known vector of values (the equations RHS).
x - The unknown vector of values tosolve for
threshold - The largest value that will be treated as singular.

svdcmp

public boolean svdcmp(BigMat v,
                      double[] w)
Performs Singular Value Decomposition A = UwVt U replace A on output (this goes from being A to being U) v and w are filled in returns true if successful, false otherwise.

Parameters:
v - Storage space for the output matrix V
w - 1D array that stores the diagonal of the W matrix (hoding any singular values)
Returns:
true if the decomposition was successful (converged within 100 iterations)

svbksb

public BigMat svbksb(double[] w,
                     BigMat V,
                     BigMat A,
                     double threshold)
SVD back substitution routine

Parameters:
w - vector of (possibly) singluar values
V - Orthogonal matrix V
A - The matrix to multiply by the invesrse of the original decomposed matrix
threshold - Threshold below which values are treated as singluar
Returns:
Returns the result of the back substitution

invertSVD

public BigMat invertSVD(double threshold)
find the inverse (possibly in the least squares sense) using SVD

Parameters:
threshold - The threshold below which values are treated as singular
Returns:
Returns the inverted matrix (or least squares approximation)

svbksb

public void svbksb(double[] w,
                   BigMat V,
                   double[] b,
                   double[] x,
                   double threshold)
Back substitution routine for SVD. Solves Ax=b where A has been converted to U*w*V using SVD This method should be called on the matrix U.

Parameters:
w - The diagonal matrix of possibly singular values, calculated by SVD
V - The orthogonal matrix V calculated by SVD
b - The known vector of values (the equations RHS).
x - The unknown vector of values tosolve for
threshold - The largest value that will be treated as singular.

jacobi

public boolean jacobi(double[] d,
                      BigMat v,
                      int[] nrot)
Jacobi computes all eigenvalues and eigenvectors of a real symmetric matrix The input matrix elements above the diagonal are destroyed. The eigen values are returned in d The eigen vectors are returned in the orthogonal matrix v. The method returns the number of rotations used.

Parameters:
d - Output space for the Eigenvalues of this matrix
v - Output space for the Eigenvectors of this matrix
nrot - A int array (of size 1) used to return the number of rotations performed
Returns:
returns true if successfully converged, false otherwise.

sort

public void sort(double[] d)
sorting routine for jacobi method

Parameters:
d - The vector to sort

SIGN

public double SIGN(double a,
                   double b)
returns sign(b)*abs(a)

Parameters:
a - Gives the value
b - Gives the sign
Returns:
sign(b)*abs(a)

qrdcmp

public boolean qrdcmp(BigMat a,
                      double[] c,
                      double[] d)
From numerical recipies in C ch2.10 Constructs the QR decomposition of this matrix returning the result in a[1..n][1..n]. The upper triangular matrix R is returned in the upper triangle of a, except for the diagonal elements of R which are returned in d[1..n]. The orthogonal matrix Q is represented as a product of n- 1 Householder matrices Q_1..Q_{n-1}, where Q_j = 1 - u_j cross u_j/c_j. The i-th component of u_j is zero for i=1,...j-1 while the nonzero components are returned in a[i][j] for i=j,...,n. sing returns as true (1) if singularoty is encountered during the decomposition, but the decomposition is still completed in this case; otherwise it returns false (0)

Parameters:
a - The above diagonal elements of R and the non-zero values of the vectors u are returned here
c - The array of weights 0.5*(u.u)
d - The diagonal of the matrix R
Returns:
true if a singular value is found, false otherwise

qrdcmp

public boolean qrdcmp(BigMat Q,
                      BigMat R)
Decomposes this square matrix into an orthonormal matrix Q and an upper triangular matrix R such that this = R.multiply(Q)

Parameters:
Q - The orthonormal matrix Q is returned here
R - The upper diagonal matrix is returned here
Returns:
returns true if the decomposition completes successfully, false otherwise. Reasons for failure include a non-square original matrix, Q and/or R not having the same dimensions as this and a singular matrix passed to the routine.

upperTriangularBacksub

public boolean upperTriangularBacksub(double[] X,
                                      double[] T)
Solves AT=X for T where A = this and T and X are column vectors A must be upper triangular

Parameters:
X - The input vector X
T - the output vector T
Returns:
returns true

upperTriangularInverseMultiply

public BigMat upperTriangularInverseMultiply(BigMat M)
Calculates A^(-1)M where A = this is upper triangular, by using repeated backsubstitutions.

Parameters:
M - The matrix to multiply by the inverse of this
Returns:
Returns the result of multiplying by the inverse of this

reconstructQR

public BigMat reconstructQR(double[] c,
                            double[] d)
Construct the Q and R matrices explicitly, using the output from qrdcmp R.multiply(Q) will give the original input matrix

Parameters:
c - The weights 0.5*u.u as returned from qrdcmp
d - The diagonal of the matrix R as returned from qrdcmp
Returns:
The matrix R, Q replaces this on output.

qrsolv

public void qrsolv(double[] c,
                   double[] d,
                   double[] b,
                   double[] x)
Solves the set of n linear equations A.x=b . c[1..n], d[1..n] together with this BigMat object as a are the results of qrdcmp above and are not modified. b[1..n] is input as the right-hand side vector. x[1..n] is the output

Parameters:
c - The weights 0.5*u.u as output from qrdcmp
d - The diagonal of the matrix R as output from qrdcmp
b - the rhs of the equation to solve
x - The result of solving the linear system is returned in x

rsolv

public void rsolv(double[] d,
                  double[] b,
                  double[] x)
solves the set of n linear equations R.x = b, where is R an upper triangular matrix stored in (a) this BigMat and b. this[1..][1..n] and d[1..n] are input as the output of the routine qrdcmp and not modified. b[1..n] is input as the right-hand vector and x[1..n] is the solution.

Parameters:
d - The diagonal of the upper diagonal matrix R
b - The rhs of the linear system to solve
x - The result of solving the linear systemis returned here.

main

public static void main(java.lang.String[] args)
Main method just used for testing

Parameters:
args - Some arguments...

add

public void add(BigMat mat)
         throws BigMatException
Adds mat to this

Parameters:
mat - The matrix to add to this
Throws:
BigMatException - thrown if matrices are different sizes

subtractInPlace

public void subtractInPlace(BigMat mat)
                     throws BigMatException
Subtracts mat to this

Parameters:
mat - The matrix subtract add to this
Throws:
BigMatException - thrown if matrices are different sizes

equals

public boolean equals(BigMat mat)
Checks if the two matrices are identical

Parameters:
mat - The matrix to compare with this
Returns:
returns true if they are the same size and each element has equal value, false otherwise

equals

public boolean equals(BigMat mat,
                      double delta)
Checks if the two matrices are the same to within a given tollerance

Parameters:
mat - The matrix to compare to
delta - The tolerance within which they matrices are considered to match
Returns:
true if the matrices are the same size and all elements are within +/- delta of each other

subMatRows

public BigMat subMatRows(int[] rowIndex)
Return a sub matrix containing only those rows pointed to by the indices.

Parameters:
rowIndex -
Returns:
submatrix

subMatCols

public BigMat subMatCols(int[] colIndex)
Return a sub matrix containing only those columns pointed to by the indices.

Parameters:
colIndex -
Returns:
submatrix

subMat

public BigMat subMat(int[] rowIndex,
                     int[] colIndex)
Return a sub matrix containing only those columns points to by the indices.

Parameters:
rowIndex - indices to the row numbers
colIndex - indices to the column number
Returns:
the sbu matrix

getColumn

public double[] getColumn(int colIndex)

getColumnCopy

public double[] getColumnCopy(int colIndex)
Returns copy of a particular column

Parameters:
colIndex - the index for the column to return
Returns:
a copy of a particular column

getRowCopy

public double[] getRowCopy(int rowIndex)
Returns copy of a particular row

Parameters:
rowIndex - the index for the row to return
Returns:
a copy of a particular row

setRow

public void setRow(int row,
                   double[] vec)

setColumn

public void setColumn(int col,
                      double[] vec)

removeNaNRecords

public static BigMat removeNaNRecords(BigMat in)
Removes any rows from the matrix that have NaNs of INF etc. Removes entire record.

Parameters:
in - matrix to purge
Returns:
resulting purged matrix

dotProduct

public static double dotProduct(double[] left,
                                double[] right)
Return the inner (dot) product for two vectors

Parameters:
left - first vector
right - second vector
Returns:
inner product
Throws:
BigMatException - if the two vectors are no the same length

sumSquares

public double sumSquares()
Returns:
the squared sum of all elements in the Matrix

squareInPlace

public void squareInPlace()
Squares the value of each individual value in the matrix ( .^ in matlab)


subtractInPlace

public void subtractInPlace(double val)
Subtract a value from each value in the Matrix ( X .- val in matlab)

Parameters:
val - value to subtract

subtractFromInPlace

public void subtractFromInPlace(double val)
Subtract each value in the matrix from val ( val - X in matlab)

Parameters:
val -

identity

public static BigMat identity(int size)