Example usage for org.apache.commons.math3.linear RealMatrix getData

List of usage examples for org.apache.commons.math3.linear RealMatrix getData

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealMatrix getData.

Prototype

double[][] getData();

Source Link

Document

Returns matrix entries as a two-dimensional array.

Usage

From source file:edu.oregonstate.eecs.mcplan.ml.SequentialProjectionHashLearner.java

public static void main(final String[] argv) {
    final double[][] a = new double[][] { { 1.0, 0.0 }, { 0.0, 1.0 } };
    final RealMatrix M = new Array2DRowRealMatrix(a);
    System.out.println(a == M.getData());
}

From source file:com.analog.lyric.math.MoreMatrixUtils.java

/**
 * Returns matrix as 2D row-major array.
 * <p>//from  w w  w.ja v a2  s .  c o  m
 * If {@code matrix} is a {@link Array2DRowRealMatrix}, this returns its underlying array,
 * otherwise returns a newly allocated array.
 * <p>
 * @since 0.08
 */
public static double[][] matrixGetDataRef(RealMatrix matrix) {
    if (matrix instanceof Array2DRowRealMatrix) {
        return ((Array2DRowRealMatrix) matrix).getDataRef();
    }

    return matrix.getData();
}

From source file:com.opengamma.strata.math.impl.util.CommonsMathWrapper.java

/**
 * Unwraps a matrix.//from  w  w  w .j  av  a 2 s .c o m
 * 
 * @param x  a Commons matrix
 * @return an OG 2-D matrix of doubles
 */
public static DoubleMatrix unwrap(RealMatrix x) {
    ArgChecker.notNull(x, "x");
    return DoubleMatrix.ofUnsafe(x.getData());
}

From source file:hulo.localization.utils.ArrayUtils.java

public static double[][] multiply(double[][] X1, double[][] X2) {
    RealMatrix M1 = MatrixUtils.createRealMatrix(X1);
    RealMatrix M2 = MatrixUtils.createRealMatrix(X2);
    RealMatrix M3 = M1.multiply(M2);
    return M3.getData();
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibCommonsMath.java

/**
 * Function to perform Eigen decomposition on a given matrix.
 * Input must be a symmetric matrix.//from ww w  . j  a v a2 s .  c o  m
 * 
 * @param in
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock[] computeEigen(MatrixObject in) throws DMLRuntimeException {
    if (in.getNumRows() != in.getNumColumns()) {
        throw new DMLRuntimeException(
                "Eigen Decomposition can only be done on a square matrix. Input matrix is rectangular (rows="
                        + in.getNumRows() + ", cols=" + in.getNumColumns() + ")");
    }

    Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in);

    EigenDecomposition eigendecompose = new EigenDecomposition(matrixInput);
    RealMatrix eVectorsMatrix = eigendecompose.getV();
    double[][] eVectors = eVectorsMatrix.getData();
    double[] eValues = eigendecompose.getRealEigenvalues();

    //Sort the eigen values (and vectors) in increasing order (to be compatible w/ LAPACK.DSYEVR())
    int n = eValues.length;
    for (int i = 0; i < n; i++) {
        int k = i;
        double p = eValues[i];
        for (int j = i + 1; j < n; j++) {
            if (eValues[j] < p) {
                k = j;
                p = eValues[j];
            }
        }
        if (k != i) {
            eValues[k] = eValues[i];
            eValues[i] = p;
            for (int j = 0; j < n; j++) {
                p = eVectors[j][i];
                eVectors[j][i] = eVectors[j][k];
                eVectors[j][k] = p;
            }
        }
    }

    MatrixBlock mbValues = DataConverter.convertToMatrixBlock(eValues, true);
    MatrixBlock mbVectors = DataConverter.convertToMatrixBlock(eVectors);

    return new MatrixBlock[] { mbValues, mbVectors };
}

From source file:hulo.localization.utils.ArrayUtils.java

public static double[][] inverseMat(double[][] mat) {
    RealMatrix realMatrix = MatrixUtils.createRealMatrix(mat);
    LUDecomposition lu = new LUDecomposition(realMatrix);
    RealMatrix invMat = lu.getSolver().getInverse();
    return invMat.getData();
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibCommonsMath.java

/**
 * Function to compute matrix inverse via matrix decomposition.
 * /*from w  w w.  ja  v a  2s  .com*/
 * @param in
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock computeMatrixInverse(Array2DRowRealMatrix in) throws DMLRuntimeException {

    if (!in.isSquare())
        throw new DMLRuntimeException("Input to inv() must be square matrix -- given: a " + in.getRowDimension()
                + "x" + in.getColumnDimension() + " matrix.");

    QRDecomposition qrdecompose = new QRDecomposition(in);
    DecompositionSolver solver = qrdecompose.getSolver();
    RealMatrix inverseMatrix = solver.getInverse();

    MatrixBlock inverse = DataConverter.convertToMatrixBlock(inverseMatrix.getData());

    return inverse;
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibCommonsMath.java

/**
 * Function to solve a given system of equations.
 * /*from   ww  w. j  av a2  s . c o m*/
 * @param in1
 * @param in2
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock computeSolve(MatrixObject in1, MatrixObject in2) throws DMLRuntimeException {
    Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in1);
    Array2DRowRealMatrix vectorInput = DataConverter.convertToArray2DRowRealMatrix(in2);

    /*LUDecompositionImpl ludecompose = new LUDecompositionImpl(matrixInput);
    DecompositionSolver lusolver = ludecompose.getSolver();
    RealMatrix solutionMatrix = lusolver.solve(vectorInput);*/

    // Setup a solver based on QR Decomposition
    QRDecomposition qrdecompose = new QRDecomposition(matrixInput);
    DecompositionSolver solver = qrdecompose.getSolver();
    // Invoke solve
    RealMatrix solutionMatrix = solver.solve(vectorInput);

    MatrixBlock solution = DataConverter.convertToMatrixBlock(solutionMatrix.getData());

    return solution;
}

From source file:com.vsthost.rnd.commons.math.ext.linear.EMatrixUtils.java

/**
 * Converts a real matrix to a JSON string.
 *
 * @param matrix The matrix to be represented by a JSON string.
 * @return A JSON representation of the matrix.
 *///from www. j a  v a2  s.  co  m
public static String toJson(RealMatrix matrix) {
    return new Gson().toJson(matrix.getData());
}

From source file:ch.zhaw.iamp.rct.weights.Weights.java

/**
 * Calculates a pseudo-inverse using the values in the given files. They are
 * first read, then converted to a matrix, and finally used for the
 * calculation of the inverse, using Singular value decomposition (SVD).
 *
 * @param pathToA The file which contains the matrix A, represented in
 * comma-separated-value format./*from   w  w  w .j  av a  2  s.  co m*/
 * @param targetTrajectoryFile The file which contains the target
 * trajectory, represented in comma-separated-value format.
 * @param weightsFile The file, to which the calculated weights should be
 * written to.
 * @param offset The numbers of first steps to ignore (to skip fading-memory
 * initialization steps).
 */
public static void calculateWeights(final String pathToA, final String targetTrajectoryFile,
        final String weightsFile, final int offset) {
    try {
        RealMatrix A = csvToMatrix(pathToA);
        // cut first n elements
        A = A.getSubMatrix(offset, A.getRowDimension() - 1, 0, A.getColumnDimension() - 1);
        A = addNoise(A);

        RealMatrix b = csvToMatrix(targetTrajectoryFile);

        // adjust b to cutting
        int n = offset % b.getRowDimension();

        if (n > 0) {
            RealMatrix tmp = b.getSubMatrix(n, b.getRowDimension() - 1, 0, b.getColumnDimension() - 1);
            b = b.getSubMatrix(0, n - 1, 0, b.getColumnDimension() - 1);
            double[][] tmpArray = tmp.getData();
            double[][] tmpArray2 = b.getData();
            b = MatrixUtils.createRealMatrix(concat(tmpArray, tmpArray2));
            tmpArray = b.getData();

            for (int i = 0; tmpArray.length < A.getRowDimension(); ++i) {
                tmpArray2 = new double[1][tmpArray[0].length];

                for (int j = 0; j < tmpArray[i].length; ++j) {
                    tmpArray2[0][j] = tmpArray[i][j];
                }

                tmpArray = concat(tmpArray, tmpArray2);
            }

            b = MatrixUtils.createRealMatrix(tmpArray);
        }

        DecompositionSolver solver = new SingularValueDecomposition(A).getSolver();
        RealMatrix x = solver.solve(b).transpose();
        matrixToCsv(x, weightsFile);

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Could not read a file: " + ex.getMessage(), "File Error",
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "Could not read a file: {0}", ex);
    } catch (DimensionMismatchException ex) {
        JOptionPane.showMessageDialog(null,
                "<html>Could not calculate the " + "pseudo-inverse since a dimension mismatch occurred.<br />"
                        + "Please make sure that all lines of the CSV file posses "
                        + "the same amount of entries.<br />Hint: Remove the last "
                        + "line and try it again.</html>",
                "Matrix Dimension Mismatch", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "A dimension mismatch occurred: {0}", ex);
    }
}