Module JBLAS
In: lib/jblas/arith.rb
lib/jblas/complex.rb
lib/jblas/errors.rb
lib/jblas/functions.rb
lib/jblas/java.rb
lib/jblas/matrix_mixin.rb
lib/jblas/mixin_access.rb
lib/jblas/mixin_arith.rb
lib/jblas/mixin_class.rb
lib/jblas/mixin_complex_matrix.rb
lib/jblas/mixin_convert.rb
lib/jblas/mixin_enum.rb
lib/jblas/mixin_general.rb
lib/jblas/proxies.rb
lib/jblas.rb

The jblas module provides matrix classes and functions to comfortably work with the matrices.

Overview

JBLAS defines the following six classes:

These classes have the usual arithmetic operations defined as well as coercion to make them work as seamlessly as possible with the norm built-in Ruby numerical types.

Technically, jblas-ruby is organized in a number of mixins which are included in the Java objects to add syntactic sugar and make the objects play well with Ruby. Links to these mixins are included in each section.

Creation

See also JBLAS::MatrixClassMixin, mat

You create a matrix or vector explicitly by using the DoubleMatrix[], or FloatMatrix[] constructor. For example:

  DoubleMatrix[[1,2,3],[4,5,6]]
  => 1.0  2.0  3.0
     4.0  5.0  6.0

  DoubleMatrix[1,2,3]
  => 1.0
     2.0
     3.0

Since typing DoubleMatrix all the time is a bit cumbersome, jblas also provides the mat function which is a short-hand for DoubleMatrix:

  mat[1,2,3]
  => 1.0
     2.0
     3.0

Apart from these constructors, there are few more functions which generate matrices or vectors:

  • zeros(n), and zeros(n,m): vector or matrix of zeros.
  • ones(…) - a vector or matrix of ones.
  • rand(…) - a vector or matrix whose elements are drawn uniformly in [0,1]
  • randn(…) - elemens are drawn from normal Gaussian distribution
  • diag(x) - return diagonal of a matrix or matrix with given diagonal
  • eye(n) - identity matrix
  • x.hcat(y) - returns the horizontal concatenation of x and y
  • x.vcat(y) - returns the vertical concatenation of x and y

hcat and vcat also exist as methods which take an arbitrary number of arguments and returns the horizontal or vertical concatenation of its arguments.

Accessing elements

See also JBLAS::MatrixAccessMixin.

To access individual elements, use the [] or []= methods, or get, and put respectively.

Rows and columns can be accessed with get_row, put_row and get_column, put_column.

You can also often use ranges or enumerables with [] and []=, for example

  x[0..2, [1,2,3]]

Arithmetics

See also JBLAS::MatrixAccessMixin.

Arithmetic is defined using the usual operators, that is

  • (matrix-)multiplication: a * b
  • addition: a + b
  • subtraction: a - b

Multiplication is the usual (linear algebra) multiplication.

There exist also non-operator versions (which are the original Java functions) These also give you more control over the generation of temporary objects. The suffix "!" or "i" indicates that the computation is performed in-place on the left operand.

  • (matrix-)multiplication: a.mmul(b), a.mmul!(b)
  • elementwise multiplication: a.mul(b), a.mul!(b)
  • addition: a.add(b), a.add!(b)
  • subtraction: a.sub(b), a.sub!(b)
  • elementwise division: a.div(b), a.div!(b)

Some special functions exist for adding the same column vector to all columns of a matrix, or row vector to all rows:

  • m.add_column_vector(x) adds a column vector
  • m.add_row_vector(x) adds a row vector

Matrix and Vectors as Enumerables

See also JBLAS::MatrixEnumMixin.

Both the matrices and vectors implement the Enumerable mixin. Matrices behave as if they are a linear array of their elements (going down rows first). If you want to iterate over rows or columns, use the rows_to_a or columns_to_a methods, as well as each_row and each_column.

Functions

JBLAS defines a large number of mathematical functions. You can either call these as a method on a matrix, vector, or even number, or in the usual notation as a function.

  • acos: arcus cosine
  • asin: arcus sine
  • atan: arcus tangens
  • cos: cosine
  • cosh: hyperbolic cosine
  • exp: exponential
  • log10: logarithm to base 10
  • log: natural logarithm
  • sin: sine
  • sinh: hyperbolic sine
  • sqrt: square root
  • tan: tangens
  • tanh: hyperbolic tangens

By adding the suffix "i" or "!" to the method functions, you again perform the computation in-place. For example

  exp(x)

returns a copy of x, but

  exp(x)
  exp!(x)

do not.

Geometry

Some functions to deal with geometric properties:

  • norm(x, type=2) computes the norm for type=1, 2, or :inf
  • x.dot(y) computes the scalar product

Linear Equations

In order to solve the linear equation a * x = b, with b either being a matrix or a vector, call solve:

  x = a.solve(b)

or

  solve(a, b)

Eigenproblems

Compute the eigenvalue of a square matrix a with

  e = eig(a)

Compute the eigenvectors as well with

  u, d = eigv(a)

eigv returns two matrices, the matrix u whose columns are the eigenvectors, and the matrix d, whose diagonal contains the eigenvalues.

Singular value decomposition

Compute the singular value decomposition of an (arbitrarily shaped) matrix a with

   u, s, v = svd(a)

The columns of u and v will contain the singular vectors, and s is a vector containing the singular values.

You can also compute a sparse SVD with svd(a, true) (meaning that u and v are not square but have the minimal rectangular size necessary).

Finally, svdv(a) computes only the singular values of a.

Methods

check_matrix_square   cholesky   cumsum   det   diag   eig   eigv   eye   hcat   idx   linspace   logspace   lup   mat   max   mean   min   norm   ones   pow   pow!   powi   rand   randn   range   repmat   sinc   solve   sort   sum   svd   svdv   tictoc   trace   vcat   zeros  

Included Modules

Java

Classes and Modules

Module JBLAS::ComplexMatrixMixin
Module JBLAS::ComplexMixin
Module JBLAS::Errors
Module JBLAS::MatrixAccessMixin
Module JBLAS::MatrixArithMixin
Module JBLAS::MatrixClassMixin
Module JBLAS::MatrixConvertMixin
Module JBLAS::MatrixEnumMixin
Module JBLAS::MatrixGeneralMixin
Module JBLAS::MatrixMixin
Class JBLAS::ComplexDouble
Class JBLAS::ComplexDoubleMatrix
Class JBLAS::ComplexFloat
Class JBLAS::ComplexFloatMatrix
Class JBLAS::DoubleMatrix
Class JBLAS::FloatMatrix
Class JBLAS::MatrixDotProxy
Class JBLAS::MatrixElementWiseProxy
Class JBLAS::ReversedArithmetic

Constants

MatrixFactory = { :double => DoubleMatrix, :float => FloatMatrix   Module Functions
FUNCTIONS = { 'abs' => 'Compute the absolute value.', 'acos' => 'Compute the arcus cosine.', 'asin' => 'Compute the arcus sine.', 'atan' => 'Compute the arcus tangens.', 'cbrt' => 'Compute the cube root.', 'ceil' => 'Round up to the next integer', 'cos' => 'Compute the cosine.', 'cosh' => 'Compute the hyperbolic cosine.', 'exp' => 'Compute the exponential function.', 'floor' => 'Round down to the next integer', 'log' => 'Compute the natural logarithm', 'log10' => 'Compute the base-10 logarithm', 'signum' => 'Compute the sign', 'sin' => 'Compute the sine', 'sinh' => 'Compute the hyperbolic sine', 'sqrt' => 'Compute the square root', 'tan' => 'Compute the tangens', 'tanh' => 'Compute the hyperbolic tangens'
PI = Math::PI
I = ComplexDouble::I

Public Instance methods

Check whether matrix is square. Raises Errors::MatrixNotSquare if it isn‘t.

[Source]

# File lib/jblas/functions.rb, line 47
  def check_matrix_square(m)
    unless m.square?
      raise Errors::MatrixNotSquare
    end
  end

Compute the Cholesky decomposition of a square, positive definite matrix.

Returns a matrix an upper triangular matrix u such that u * u.t is the original matrix.

[Source]

# File lib/jblas/functions.rb, line 346
  def cholesky(x)
    check_matrix_square(x)
    begin
      Decompose.cholesky(x)
    rescue org.jblas.exceptions.LapackPositivityException
      raise Errors::MatrixNotPositiveDefinite
    end
  end

Compute the cumulative sum of a vector.

[Source]

# File lib/jblas/functions.rb, line 328
  def cumsum(x)
    x.cumulative_sum
  end

Compute the determinant of a square matrix.

Internally computes the LU factorization and then takes the product of the diagonal elements.

[Source]

# File lib/jblas/functions.rb, line 359
  def det(x)
    check_matrix_square(x)
    l, u, p = lup(x)
    return u.diag.prod
  end

Return the diagonal of a matrix or return a matrix whose diagonal is specified by the vector

[Source]

# File lib/jblas/functions.rb, line 101
  def diag(x)
    if x.vector?
      mat.diag(x)
    else
      x.diag
    end
  end

Computing the eigenvalues of matrix.

[Source]

# File lib/jblas/functions.rb, line 203
  def eig(x)
    check_matrix_square(x)
    if x.symmetric?
      return Eigen.symmetric_eigenvalues(x)
    else
      return Eigen.eigenvalues(x)
    end
  end

Computing the eigenvectors of matrix.

  u, v = eigv(x)

u are the eigenvalues and v is a diagonal matrix containing the eigenvalues

[Source]

# File lib/jblas/functions.rb, line 218
  def eigv(x)
    check_matrix_square(x)
    if x.symmetric?
      return Eigen.symmetric_eigenvectors(x).to_a
    else
      return Eigen.eigenvectors(x).to_a
    end
  end

Return the identity matrix of given size.

[Source]

# File lib/jblas/functions.rb, line 110
  def eye(n)
    mat.eye(n)
  end

Returns the horizontal concatenation of all arguments.

See also MatrixGeneralMixin#hcat.

[Source]

# File lib/jblas/functions.rb, line 247
  def hcat(*args)
    args.map {|s| s.to_matrix}.inject{|s,x| s = s.hcat x}
  end

Convenience function for converting arbitrary objects into indices.

[Source]

# File lib/jblas/mixin_access.rb, line 152
  def idx(i)
    i.to_indices
  end

Generate an array of n linearly spaced points starting at a, ending at b.

[Source]

# File lib/jblas/functions.rb, line 271
  def linspace(a, b, n)
    (0...n).map do |i|
      t = Float(i) / (n-1)
      (1-t)*a + t*b
    end
  end

Generate an array of n logarithmically spaced points starting at 10^a and ending at 10^b.

[Source]

# File lib/jblas/functions.rb, line 280
  def logspace(a, b, n)
    (0...n).map do |i|
      t = Float(i) / (n-1)
      10**( (1-t)*a + t*b )
    end
  end

Compute the LU factorization with pivoting.

Returns matrices l, u, p

[Source]

# File lib/jblas/functions.rb, line 335
  def lup(x)
    check_matrix_square(x)
    result = Decompose.lu(x)
    return result.l, result.u, result.p
  end

Construct a matrix. Use it like this:

  mat[1,2,3] -> constructs a column vector
  mat[[1,2,3],[4,5,6]] -> construct a rectangular matrix

[Source]

# File lib/jblas/functions.rb, line 69
  def mat(type=:double)
    MatrixFactory[type]
  end

Return the largest element of a vector.

[Source]

# File lib/jblas/functions.rb, line 318
  def max(x)
    x.max
  end

The mean of a vector.

[Source]

# File lib/jblas/functions.rb, line 303
  def mean(x)
    x.to_mat.mean
  end

Return the smallest element of a vector.

[Source]

# File lib/jblas/functions.rb, line 313
  def min(x)
    x.min
  end

Compute the norm of a vector

[Source]

# File lib/jblas/functions.rb, line 233
  def norm(x, type=2)
    case type
    when 1
      x.norm1
    when 2
      x.norm2
    when :inf
      x.normmax
    end
  end

Construct a matrix of all ones.

  ones(2, 3) == mat[[1, 1, 1],[1, 1, 1]]

If the second argument is omitted, a column vector is constructed.

[Source]

# File lib/jblas/functions.rb, line 91
  def ones(n,m=nil)
    if m
      mat.ones(n,m)
    else
      mat.ones(n)
    end
  end

Computer power. pow(x, y) = x ^ y.

[Source]

# File lib/jblas/functions.rb, line 181
  def pow(x, y)
    x = x.to_mat if Array === x
    y = y.to_amt if Array === y
    return MatrixFunctions.pow(x, y)
  end
pow!(x, y)

Alias for powi

Compute power, in-place.

[Source]

# File lib/jblas/functions.rb, line 188
  def powi(x, y)
    MatrixFunctions.powi(x, y)
  end

Construct a matrix or vector with elements randomly drawn uniformly from [0, 1].

If the second argument is omitted, a column vector is constructed.

[Source]

# File lib/jblas/functions.rb, line 118
  def rand(n=1,m=nil)
    if m
      mat.rand(n,m)
    else
      mat.rand(n)
    end
  end

Construct a matrix or vector with elements randomly drawn from a Gaussian distribution with mean 0 and variance 1. With one argument, construct a vector, with two a matrix.

If the second argument is omitted, a column vector is constructed.

[Source]

# File lib/jblas/functions.rb, line 131
  def randn(n=1,m=nil)
    if m
      mat.randn(n,m)
    else
      mat.randn(n)
    end
  end

Generate a range from a to b with step size s.

[Source]

# File lib/jblas/functions.rb, line 288
  def range(a, s, b)
    x = []
    while a < b
      x << a
      a += s
    end
    return x
  end

Replicate a matrix a certain number of horizontal and vertical times.

For example:

    repmat(mat[[1,2,3],[4,5,6]], 1, 2)
    => [1.0, 2.0, 3.0, 1.0, 2.0, 3.0; 4.0, 5.0, 6.0, 4.0, 5.0, 6.0]

[Source]

# File lib/jblas/functions.rb, line 265
  def repmat(m, r, c)
    m.to_matrix.repmat(r, c)
  end

The sinc function (Defined as sin(x)/x if x != 0 and 1 else).

[Source]

# File lib/jblas/functions.rb, line 323
  def sinc(x)
    sin(x) / x
  end

Solve the linear equation a*x = b. See also MatrixMixin#solve.

[Source]

# File lib/jblas/functions.rb, line 228
  def solve(a, b)
    a.solve b
  end

Sort the elements of a vector.

[Source]

# File lib/jblas/functions.rb, line 308
  def sort(x)
    x.sort
  end

The sum of a vector. See also

[Source]

# File lib/jblas/functions.rb, line 298
  def sum(x)
    x.sum
  end

Compute the singular value decompositon of a rectangular matrix.

Returns matrices u, s, v such that u*diag(s)*v.t is the original matrix. Put differently, the columns of u are the left singular vectors, the columns of v are the right singular vectors, and s are the singular values.

[Source]

# File lib/jblas/functions.rb, line 372
  def svd(x, sparse=false)
    if sparse
      usv = Singular.sparseSVD(x)
    else
      usv = Singular.fullSVD(x)
    end
    return usv.to_a
  end

Compute the singular values of a rectangular matrix.

[Source]

# File lib/jblas/functions.rb, line 382
  def svdv(x)
    Singular.SVDValues(x)
  end

Times a block and returns the elapsed time in seconds.

For example:

  tictoc { n = 100; x = randn(n, n); u, d = eigv(x) }

Times how long it takes to generate a random 100*100 matrix and compute its eigendecomposition.

[Source]

# File lib/jblas/functions.rb, line 400
  def tictoc
    saved_time = Time.now
    yield
    return Time.now - saved_time
  end

Computing the trace of a matrix.

[Source]

# File lib/jblas/functions.rb, line 197
  def trace(x)
    JBLAS::check_matrix_square(x)
    x.diag.sum
  end

Returns the vertical concatenation of all arguments

See also MatrixGeneralMixin#vcat.

[Source]

# File lib/jblas/functions.rb, line 254
  def vcat(*args)
    args.map {|s| s.to_matrix}.inject{|s,x| s = s.vcat x}
  end

Construct a matrix of all zeros.

  zeros(2, 3) == mat[[0, 0, 0],[0, 0, 0]]

If the second argument is omitted, a column vector is constructed.

[Source]

# File lib/jblas/functions.rb, line 78
  def zeros(n,m=nil)
    if m
      mat.zeros(n,m)
    else
      mat.zeros(n)
    end
  end

[Validate]