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

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

Introduction

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

Prototype

int getRowDimension();

Source Link

Document

Returns the number of rows in the matrix.

Usage

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * Calculate the horizontal direct product of two matrices
 *
 * @param matrix1 first matrix//from   w  w  w .ja va 2 s  .  c om
 * @param matrix2 second matrix
 * @return horizontal direct product of matrix 1 and matrix 2
 */
public static RealMatrix getHorizontalDirectProduct(RealMatrix matrix1, RealMatrix matrix2)
        throws IllegalArgumentException {
    if (matrix1 == null || matrix2 == null)
        throw new IllegalArgumentException("null input matrix");
    if (matrix1.getRowDimension() != matrix2.getRowDimension())
        throw new IllegalArgumentException("input matrices must have equal row dimension");

    int mRows = matrix1.getRowDimension();
    int m1Cols = matrix1.getColumnDimension();
    int m2Cols = matrix2.getColumnDimension();

    double[][] productData = new double[mRows][m1Cols * m2Cols];
    RealMatrix productMatrix = new Array2DRowRealMatrix(productData);
    for (int col = 0; col < m1Cols; col++) {
        for (int row = 0; row < mRows; row++) {
            RealMatrix m2Row = matrix2.getRowMatrix(row);
            productMatrix.setSubMatrix((m2Row.scalarMultiply(matrix1.getEntry(row, col))).getData(), row,
                    col * m2Cols);
        }
    }
    return productMatrix;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * This method will return vech(matrix).
 * matrix must be symmetric in order to perform vech operation.
 * @param RealMatrix matrix/*from www.  j a  v a 2 s .c  o m*/
 * @return vech(matrix)
 */
public static RealMatrix getVechMatrix(RealMatrix matrix) throws IllegalArgumentException {
    if (matrix == null || !isSymmetric(matrix)) {
        throw new IllegalArgumentException("Matrix must be non-null and " + "symmetrical.");
    }
    int newRow = 0;
    int numRows = matrix.getRowDimension();
    RealMatrix vech = new Array2DRowRealMatrix(numRows * (numRows + 1) / 2, 1);
    for (int c = 0; c < matrix.getColumnDimension(); c++) {
        for (int r = c; r < matrix.getRowDimension(); r++, newRow++) {
            vech.setEntry(newRow, 0, matrix.getEntry(r, c));
        }
    }
    return vech;
}

From source file:lirmm.inria.fr.math.TestUtils.java

/** verifies that two matrices are close (1-norm) */
public static void assertEquals(String msg, RealMatrix expected, RealMatrix observed, double tolerance) {

    Assert.assertNotNull(msg + "\nObserved should not be null", observed);

    if (expected.getColumnDimension() != observed.getColumnDimension()
            || expected.getRowDimension() != observed.getRowDimension()) {
        StringBuilder messageBuffer = new StringBuilder(msg);
        messageBuffer.append("\nObserved has incorrect dimensions.");
        messageBuffer/*from w w  w.j a  v  a2 s .  c o m*/
                .append("\nobserved is " + observed.getRowDimension() + " x " + observed.getColumnDimension());
        messageBuffer
                .append("\nexpected " + expected.getRowDimension() + " x " + expected.getColumnDimension());
        Assert.fail(messageBuffer.toString());
    }

    RealMatrix delta = expected.subtract(observed);
    if (delta.getNorm() >= tolerance) {
        StringBuilder messageBuffer = new StringBuilder(msg);
        messageBuffer.append("\nExpected: " + expected);
        messageBuffer.append("\nObserved: " + observed);
        messageBuffer.append("\nexpected - observed: " + delta);
        Assert.fail(messageBuffer.toString());
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static RealMatrix combinedMatrices(@Nonnull final RealMatrix[] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 0: " + grid.length);

    final int rows = grid.length;
    final int rowDims = grid[0].getRowDimension();
    final int colDims = grid[0].getColumnDimension();

    final RealMatrix combined = new BlockRealMatrix(rows * rowDims, colDims);
    for (int row = 0; row < grid.length; row++) {
        RealMatrix cell = grid[row];
        Preconditions.checkArgument(cell.getRowDimension() == rowDims, "Mismatch in row dimensions at row ",
                row);/*from   w w  w.jav  a  2  s  .c o  m*/
        Preconditions.checkArgument(cell.getColumnDimension() == colDims, "Mismatch in col dimensions at row ",
                row);
        combined.setSubMatrix(cell.getData(), row * rowDims, 0);
    }
    return combined;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * Regenerates the design matrix and fills any random columns with a new
 * realization of random values based on a normal distribution.
 *
 * @return full design matrix/* w ww .  ja va2  s.  c  om*/
 */
public static RealMatrix getFullDesignMatrix(RealMatrix designEssence, RealMatrix sigmaGaussianRandom,
        int sampleSize, int seed) {
    RealMatrix fixed = MatrixUtils.getKroneckerProduct(designEssence,
            MatrixUtils.getRealMatrixWithFilledValue(sampleSize, 1, 1));
    // GLMM(F, g), so we need to append a random column
    return MatrixUtils.getHorizontalAppend(fixed, MatrixUtils.getRandomColumnMatrix(fixed.getRowDimension(), 0,
            sigmaGaussianRandom.getEntry(0, 0), seed));
}

From source file:edu.ucdenver.bios.powersvc.resource.ContrastHelper.java

/**
 * Create a trend test fpr the specified factor of interest
 * @param factorOfInterestMap factor of interest plus trend type information
 * @param factorList list of all between participant factors
 * @return trend contrast//w  w  w  .j a  va  2  s .c  o m
 */
public static RealMatrix trendBetween(HypothesisBetweenParticipantMapping factorOfInterestMap,
        List<BetweenParticipantFactor> factorList) {

    // build contrast component for the effect of interest 
    BetweenParticipantFactor factorOfInterest = factorOfInterestMap.getBetweenParticipantFactor();
    HypothesisTrendTypeEnum trendType = factorOfInterestMap.getType();
    int levels = factorOfInterest.getCategoryList().size();
    if (levels > 1) {
        // create even spacing
        double[] spacing = new double[levels];
        for (int i = 0; i < levels; i++) {
            spacing[i] = i;
        }
        RealMatrix trendContrast = getTrendContrast(spacing, trendType, true);

        // Kronecker product the trend contrast with average contrasts for remaining
        // factors
        RealMatrix contrast = MatrixUtils.getRealMatrixWithFilledValue(1, 1, 1);
        int df = trendContrast.getRowDimension();
        for (BetweenParticipantFactor factor : factorList) {
            if (factor.getPredictorName().equals(factorOfInterest.getPredictorName())) {
                contrast = MatrixUtils.getKroneckerProduct(contrast, trendContrast);
            } else {
                List<Category> categoryList = factor.getCategoryList();
                if (categoryList.size() > 0) {
                    int dimension = categoryList.size();
                    contrast = MatrixUtils.getKroneckerProduct(contrast,
                            MatrixUtils.getRealMatrixWithFilledValue(1, dimension, 1 / (double) dimension));
                }
            }
        }
        return contrast;
    } else {
        return ContrastHelper.grandMeanBetween(factorList);
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static double[] flatten(@Nonnull final RealMatrix[] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 1");

    final int rows = grid.length;
    RealMatrix grid0 = grid[0];
    Preconditions.checkNotNull(grid0);/*from ww  w  . ja  v  a2 s  .c o  m*/
    int cellRows = grid0.getRowDimension();
    int cellCols = grid0.getColumnDimension();

    final DoubleArrayList list = new DoubleArrayList(rows * cellRows * cellCols);
    final RealMatrixPreservingVisitor visitor = new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            list.add(value);
        }
    };

    for (int row = 0; row < rows; row++) {
        RealMatrix cell = grid[row];
        cell.walkInRowOrder(visitor);
    }

    return list.toArray();
}

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static double[] flatten(@Nonnull final RealMatrix[][] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 1");
    Preconditions.checkArgument(grid[0].length >= 1, "The number of cols must be greater than 1");

    final int rows = grid.length;
    final int cols = grid[0].length;
    RealMatrix grid00 = grid[0][0];
    Preconditions.checkNotNull(grid00);/*w  w w  . j  a va2s  .co  m*/
    int cellRows = grid00.getRowDimension();
    int cellCols = grid00.getColumnDimension();

    final DoubleArrayList list = new DoubleArrayList(rows * cols * cellRows * cellCols);
    final RealMatrixPreservingVisitor visitor = new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            list.add(value);
        }
    };

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            RealMatrix cell = grid[row][col];
            cell.walkInRowOrder(visitor);
        }
    }

    return list.toArray();
}

From source file:edu.ucdenver.bios.powersvc.resource.ContrastHelper.java

/**
 * Create a trend test fpr the specified within participant of interest
 * @param factorOfInterestMap factor of interest plus trend type information
 * @param factorList list of all within participant factors
 * @return trend contrast// w ww  .  ja  v  a 2 s  .  c om
 */
public static RealMatrix trendWithin(HypothesisRepeatedMeasuresMapping factorOfInterestMap,
        List<RepeatedMeasuresNode> factorList, List<ResponseNode> responseList) {

    // build contrast component for the effect of interest 
    RepeatedMeasuresNode factorOfInterest = factorOfInterestMap.getRepeatedMeasuresNode();
    HypothesisTrendTypeEnum trendType = factorOfInterestMap.getType();
    int levels = factorOfInterest.getNumberOfMeasurements();
    if (levels > 1) {
        List<Spacing> spacingList = factorOfInterest.getSpacingList();
        double[] spacingArray;
        if (spacingList != null) {
            spacingArray = new double[spacingList.size()];
            for (int i = 0; i < spacingList.size(); i++) {
                spacingArray[i] = spacingList.get(i).getValue();
            }
        } else {
            int size = factorOfInterest.getNumberOfMeasurements();
            spacingArray = new double[size];
            for (int i = 0; i < size; i++) {
                spacingArray[i] = i + 1;
            }
        }
        RealMatrix trendContrast = getTrendContrast(spacingArray, trendType, false);

        // horizontal direct product the trend contrast with average contrasts for remaining
        // factors
        RealMatrix contrast = MatrixUtils.getRealMatrixWithFilledValue(1, 1, 1);
        int df = trendContrast.getRowDimension();
        for (RepeatedMeasuresNode factor : factorList) {
            if (factor.getDimension().equals(factorOfInterest.getDimension())) {
                contrast = MatrixUtils.getKroneckerProduct(contrast, trendContrast);
            } else {
                int size = factor.getNumberOfMeasurements();
                if (size > 0) {
                    contrast = MatrixUtils.getKroneckerProduct(contrast,
                            MatrixUtils.getRealMatrixWithFilledValue(1, size, 1 / (double) size));
                }
            }
        }
        // multiply on an identity matrix with dimension equal to the number of multivariate responses
        if (responseList != null && responseList.size() > 1) {
            contrast = MatrixUtils.getKroneckerProduct(contrast,
                    org.apache.commons.math3.linear.MatrixUtils.createRealIdentityMatrix(responseList.size()));
        }
        return contrast;
    } else {
        return ContrastHelper.grandMeanWithin(factorList, responseList);
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * QR decomposition for a tridiagonal matrix T.
 *
 * @see https://gist.github.com/lightcatcher/8118181
 * @see http://www.ericmart.in/blog/optimizing_julia_tridiag_qr
 * @param T target tridiagonal matrix//from  w ww .  j av  a2  s. c o  m
 * @param R output matrix for R which is the same shape as T
 * @param Qt output matrix for Q.T which is the same shape an T
 */
public static void tridiagonalQR(@Nonnull final RealMatrix T, @Nonnull final RealMatrix R,
        @Nonnull final RealMatrix Qt) {
    int n = T.getRowDimension();
    Preconditions.checkArgument(n == R.getRowDimension() && n == R.getColumnDimension(),
            "T and R must be the same shape");
    Preconditions.checkArgument(n == Qt.getRowDimension() && n == Qt.getColumnDimension(),
            "T and Qt must be the same shape");

    // initial R = T
    R.setSubMatrix(T.getData(), 0, 0);

    // initial Qt = identity
    Qt.setSubMatrix(eye(n), 0, 0);

    for (int i = 0; i < n - 1; i++) {
        // Householder projection for a vector x
        // https://en.wikipedia.org/wiki/Householder_transformation
        RealVector x = T.getSubMatrix(i, i + 1, i, i).getColumnVector(0);
        x = unitL2norm(x);

        RealMatrix subR = R.getSubMatrix(i, i + 1, 0, n - 1);
        R.setSubMatrix(subR.subtract(x.outerProduct(subR.preMultiply(x)).scalarMultiply(2)).getData(), i, 0);

        RealMatrix subQt = Qt.getSubMatrix(i, i + 1, 0, n - 1);
        Qt.setSubMatrix(subQt.subtract(x.outerProduct(subQt.preMultiply(x)).scalarMultiply(2)).getData(), i, 0);
    }
}