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

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

Introduction

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

Prototype

int getColumnDimension();

Source Link

Document

Returns the number of columns in the matrix.

Usage

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

/**
 * Multiplies the matrix' rows using the vector element-by-element.
 *
 * @param matrix The input matrix.//from   w  w  w  .j ava 2s .  c  o  m
 * @param vector The vector which will be used to multiply rows of the matrix element-by-element.
 * @return The new matrix of which rows are multiplied with the vector element-by-element.
 */
public static RealMatrix rbrMultiply(RealMatrix matrix, RealVector vector) {
    // Define the return value:
    RealMatrix retval = MatrixUtils.createRealMatrix(matrix.getRowDimension(), matrix.getColumnDimension());

    // Iterate over rows:
    for (int i = 0; i < retval.getRowDimension(); i++) {
        retval.setRowVector(i, matrix.getRowVector(i).ebeMultiply(vector));
    }

    // Done, return:
    return retval;
}

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

/**
 * Create a string representing the content of a RealMatrix,
 * suitable for logging./*from   w  w  w .  j  a v a 2s  . c o  m*/
 *
 * @param label An optional label.
 * @param rm    The RealMatrix.
 *
 * @return The string.
 */
public static String logMessage(String label, RealMatrix rm) {
    StringBuilder sb = new StringBuilder();

    sb.append(EOL);

    if (label != null) {
        sb.append("  ").append(label).append(EOL);
    }

    if (rm == null) {
        sb.append("   (null)");
        sb.append(EOL);
    } else {
        int m = rm.getRowDimension();
        int n = rm.getColumnDimension();

        sb.append("   (").append(m).append(" x ").append(n).append(")").append(EOL);

        for (int i = 0; i < m; ++i) {
            sb.append("    ");

            for (int j = 0; j < n; ++j) {
                sb.append(rm.getEntry(i, j)).append(' ');
            }

            sb.append(EOL);
        }
    }

    return sb.toString();
}

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

/**
 * Create a within or between subject contrast (C) for polynomial trends
 * for an arbitrary list of factors.  The returned collection includes
 * the grand mean contrast, all 1-factor main effect contrasts, and
 * all possible interaction contrasts/*  ww  w . j  a  v  a2 s.c  o m*/
 * 
 * @param factorList list of factors, including name and value information
 * @return polynomial contrast collection.
 * @throws IllegalArgumentException
 */
public static OrthogonalPolynomialContrastCollection buildContrastCollection(List<Factor> factorList,
        boolean between) throws IllegalArgumentException {
    if (factorList == null || factorList.size() <= 0)
        throw new IllegalArgumentException("no factors specified");

    ArrayList<RealMatrix> zeroTrendList = new ArrayList<RealMatrix>(factorList.size());
    ArrayList<RealMatrix> factorTrendList = new ArrayList<RealMatrix>(factorList.size());
    for (Factor factor : factorList) {
        double[] centered = centerAndScale(factor.getValues());
        RealMatrix poly = OrthogonalPolynomials.orthogonalPolynomialCoefficients(centered, centered.length - 1);
        zeroTrendList.add(poly.getColumnMatrix(0));
        factorTrendList.add(poly.getSubMatrix(0, poly.getRowDimension() - 1, 1, poly.getColumnDimension() - 1));
    }

    OrthogonalPolynomialContrastCollection results = new OrthogonalPolynomialContrastCollection();
    /*
     * We need to create contrasts for every possible combination of
     * zero and factor trends.  The possible combinations can be  
     * enumerated by the binary representation of the numbers
     * 0 - 2^(#factors).  In this case, 0 indicates that the zero-trend contrast should
     * be included in the Kronecker product for a given factor, and 1 indicates that the 
     * factor trend contrast should be included in the Kronecker product.
     */
    ArrayList<RealMatrix> kroneckerList = new ArrayList<RealMatrix>(factorList.size());
    ArrayList<Factor> activeFactorList = new ArrayList<Factor>(factorList.size());
    // build the grand mean
    for (RealMatrix zeroTrend : zeroTrendList)
        kroneckerList.add(zeroTrend);
    if (between)
        results.addContrast(
                new OrthogonalPolynomialContrast(MatrixUtils.getKroneckerProduct(kroneckerList).transpose()));
    else
        results.addContrast(new OrthogonalPolynomialContrast(MatrixUtils.getKroneckerProduct(kroneckerList)));
    // loop over the remaining contrasts
    int totalContrasts = (int) Math.pow(2.0, (double) factorList.size());
    for (int i = 1; i < totalContrasts; i++) {
        kroneckerList.clear();
        activeFactorList.clear();
        int mask = 1;
        for (int factorIdx = 0; factorIdx < factorList.size(); factorIdx++, mask *= 2) {
            if ((i & mask) != 0) {
                kroneckerList.add(factorTrendList.get(factorIdx));
                activeFactorList.add(factorList.get(factorIdx));
            } else {
                kroneckerList.add(zeroTrendList.get(factorIdx));
            }
        }
        // add the appropriate contrast type
        // note that if "i" is a power of 2 then we have a  main effect contrast, else interaction
        RealMatrix contrast = null;
        if (between)
            contrast = MatrixUtils.getKroneckerProduct(kroneckerList).transpose();
        else
            contrast = MatrixUtils.getKroneckerProduct(kroneckerList);
        results.addContrast(new OrthogonalPolynomialContrast(
                ((i & (i - 1)) == 0 ? ContrastType.MAIN_EFFECT : ContrastType.INTERACTION), activeFactorList,
                contrast));
    }

    return results;
}

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

/**
 * The method determines if the given matrix is symmetric, i.e.,
 * if (r,c) == (c,r) in every case./*from  w ww  .j a v a 2 s .c o m*/
 * @param RealMatrix matrix
 * @return true if the matrix is symmetric, false if not symmetric.
 */
public static boolean isSymmetric(RealMatrix matrix) {
    int numRows = matrix.getRowDimension();
    int numCols = matrix.getColumnDimension();

    //if not square, can't be symmetrical
    if (numRows != numCols)
        return false;

    for (int r = 0; r < numRows; r++) {
        for (int c = 0; c < numCols; c++) {
            //test for symmetry
            if (matrix.getEntry(r, c) != matrix.getEntry(c, r)) {
                return false;
            }
        }
    }
    return true;
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
* <p>Compute the "hat" matrix./* w w  w.j a  va2 s  .c o  m*/
* </p>
* <p>The hat matrix is defined in terms of the design matrix X
*  by X(X<sup>T</sup>X)<sup>-1</sup>X<sup>T</sup>
* </p>
* <p>The implementation here uses the QR decomposition to compute the
* hat matrix as Q I<sub>p</sub>Q<sup>T</sup> where I<sub>p</sub> is the
* p-dimensional identity matrix augmented by 0's.  This computational
* formula is from "The Hat Matrix in Regression and ANOVA",
* David C. Hoaglin and Roy E. Welsch,
* <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
*@param m - matrix
* @return the hat matrix
*/
public static RealMatrix calculateHat(final BlockRealMatrix m) {
    QRDecomposition qr = new QRDecomposition(m);
    // Create augmented identity matrix
    RealMatrix qM = qr.getQ();
    final int p = qr.getR().getColumnDimension();
    final int n = qM.getColumnDimension();
    Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n);
    double[][] augIData = augI.getDataRef();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j && i < p) {
                augIData[i][j] = 1d;
            } else {
                augIData[i][j] = 0d;
            }
        }
    }
    // Compute and return Hat matrix
    return qM.multiply(augI).multiply(qM.transpose());
}

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

/**
 * Convenience method which will return a boolean which indicates whether
 * or not the dimensions of the two matrices are equal.  i.e., the method
 * will return true if the number of rows in matrixA is equal to the
 * number of rows in matrixB, and the number of columns in matrixA equals
 * the number of columns in matrixB.//w w w .jav  a 2  s  . c om
 * @param matrixA
 * @param matrixB
 * @return boolean indicating whether or not the matrix dimensions are equal.
 */
public static boolean areDimensionsEqual(RealMatrix matrixA, RealMatrix matrixB) {
    int numRowsA = matrixA.getRowDimension();
    int numColsA = matrixA.getColumnDimension();
    int numRowsB = matrixB.getRowDimension();
    int numColsB = matrixB.getColumnDimension();
    return (numRowsA == numRowsB && numColsA == numColsB);
}

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

/**
 * Returns the means of rows./*from   w w w . j a v  a 2 s .c o  m*/
 *
 * @param matrix The matrix of which the means of rows to be computed
 * @return A double array of row means
 */
public static double[] rowMeans(RealMatrix matrix) {
    // Get the col sums:
    double[] retval = EMatrixUtils.rowSums(matrix);

    // Iterate over return value and divide by the length:
    for (int i = 0; i < retval.length; i++) {
        retval[i] = retval[i] / matrix.getColumnDimension();
    }

    // Done, return row means:
    return retval;
}

From source file:com.yahoo.egads.utilities.SpectralMethods.java

public static RealMatrix mFilter(RealMatrix data, int windowSize, FilteringMethod method,
        double methodParameter) {

    int n = data.getRowDimension();
    int m = data.getColumnDimension();
    int k = n - windowSize + 1;
    int i = 0, ind = 0;
    double[] temp;
    double sum = 0;

    RealMatrix hankelMat = SpectralMethods.createHankelMatrix(data, windowSize);
    SingularValueDecomposition svd = new SingularValueDecomposition(hankelMat);

    double[] singularValues = svd.getSingularValues();

    switch (method) {
    case VARIANCE:
        temp = new double[singularValues.length - 1];

        for (i = 1; i < singularValues.length; ++i) {
            sum += (singularValues[i] * singularValues[i]);
        }/*  www  . j ava  2 s. c  om*/

        for (i = 0; i < temp.length; ++i) {
            temp[i] = (singularValues[i + 1] * singularValues[i + 1]) / sum;
        }

        sum = 0;
        for (i = temp.length - 1; i >= 0; --i) {
            sum += temp[i];
            if (sum >= 1 - methodParameter) {
                ind = i;
                break;
            }
        }

        break;

    case EXPLICIT:
        ind = (int) Math.max(Math.min(methodParameter - 1, singularValues.length - 1), 0);
        break;

    case K_GAP:
        final double[] eigenGaps = new double[singularValues.length - 1];
        Integer[] index = new Integer[singularValues.length - 1];
        for (i = 0; i < eigenGaps.length; ++i) {
            eigenGaps[i] = singularValues[i] - singularValues[i + 1];
            index[i] = i;
        }

        Arrays.sort(index, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Double.compare(eigenGaps[o1], eigenGaps[o2]);
            }
        });

        int maxIndex = 0;
        for (i = index.length - (int) methodParameter; i < index.length; ++i) {
            if (index[i] > maxIndex) {
                maxIndex = index[i];
            }
        }

        ind = Math.min(maxIndex, singularValues.length / 3);
        break;

    case SMOOTHNESS:
        double[] variances = new double[singularValues.length];

        for (i = 1; i < singularValues.length; ++i) {
            variances[i] = (singularValues[i] * singularValues[i]);
        }
        variances[0] = variances[1];

        double smoothness = SpectralMethods
                .computeSmoothness(Arrays.copyOfRange(variances, 1, variances.length));

        if (methodParameter - smoothness < 0.01) {
            methodParameter += 0.01;
        }

        double invalidS = smoothness;
        int validIndex = 1, invalidIndex = singularValues.length;

        while (true) {
            if (invalidS >= methodParameter) {
                ind = invalidIndex - 1;
                break;
            } else if (invalidIndex - validIndex <= 1) {
                ind = validIndex - 1;
                break;
            }

            int ii = (validIndex + invalidIndex) / 2;

            double[] tempVariances = Arrays.copyOf(Arrays.copyOfRange(variances, 0, ii + 1),
                    singularValues.length);
            double s = SpectralMethods.computeSmoothness(tempVariances);

            if (s >= methodParameter) {
                validIndex = ii;
            } else {
                invalidIndex = ii;
                invalidS = s;
            }
        }

        break;

    case EIGEN_RATIO:
        int startIndex = 0, endIndex = singularValues.length - 1;

        if (singularValues[endIndex] / singularValues[0] >= methodParameter) {
            ind = endIndex;
        } else {
            while (true) {
                int midIndex = (startIndex + endIndex) / 2;
                if (singularValues[midIndex] / singularValues[0] >= methodParameter) {
                    if (singularValues[midIndex + 1] / singularValues[0] < methodParameter) {
                        ind = midIndex;
                        break;
                    } else {
                        startIndex = midIndex;
                    }
                } else {
                    endIndex = midIndex;
                }
            }
        }

        break;

    case GAP_RATIO:
        double[] gaps = new double[singularValues.length - 1];
        for (i = 0; i < gaps.length; ++i) {
            gaps[i] = singularValues[i] - singularValues[i + 1];
        }

        ind = 0;
        for (i = gaps.length - 1; i >= 0; --i) {
            if (gaps[i] / singularValues[0] >= methodParameter) {
                ind = i;
                break;
            }
        }

        break;

    default:
        ind = singularValues.length - 1;
        break;
    }

    ind = Math.max(0, Math.min(ind, singularValues.length - 1));
    RealMatrix truncatedHankelMatrix = MatrixUtils.createRealMatrix(k, m * windowSize);
    RealMatrix mU = svd.getU();
    RealMatrix mVT = svd.getVT();

    for (i = 0; i <= ind; ++i) {
        truncatedHankelMatrix = truncatedHankelMatrix
                .add(mU.getColumnMatrix(i).multiply(mVT.getRowMatrix(i)).scalarMultiply(singularValues[i]));
    }

    return SpectralMethods.averageHankelMatrix(truncatedHankelMatrix, windowSize);
}

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

/**
 * Calculate the Kronecker product of a list of matrices.  Applies the
 * Kronecker product following the list order (i.e. from left to right).
 *
 * @param matrixList list of matrices//www . ja va  2 s.  co  m
 * @return Kronecker product of matrices
 */
public static RealMatrix getKroneckerProduct(List<RealMatrix> matrixList) {
    if (matrixList == null || matrixList.size() <= 0)
        throw new IllegalArgumentException("no input matrices");
    if (matrixList.size() == 1)
        return matrixList.get(0); // nothing to do, only one matrix

    // calculate the dimensions of the Kronecker product matrix
    int totalRows = 1;
    int totalCols = 1;
    for (RealMatrix matrix : matrixList) {
        totalRows *= matrix.getRowDimension();
        totalCols *= matrix.getColumnDimension();
    }

    // create a matrix to hold the data
    double[][] productData = new double[totalRows][totalCols];
    // initialize to 1 (allows us to multiple the contents of each matrix
    // onto the result sequentially
    for (int prodRow = 0; prodRow < totalRows; prodRow++) {
        for (int prodCol = 0; prodCol < totalCols; prodCol++) {
            productData[prodRow][prodCol] = 1;
        }
    }

    // multiply the contents of each matrix onto the result
    int maxRow = totalRows;
    int maxCol = totalCols;
    for (RealMatrix matrix : matrixList) {
        maxRow /= matrix.getRowDimension();
        maxCol /= matrix.getColumnDimension();
        int matrixRow = 0;
        int matrixCol = 0;
        // multiply onto the result
        for (int prodRow = 0, sectionRow = 0; prodRow < totalRows; prodRow++, sectionRow++) {
            matrixCol = 0;
            double value = matrix.getEntry(matrixRow, matrixCol);
            for (int prodCol = 0, sectionCol = 0; prodCol < totalCols; prodCol++, sectionCol++) {
                productData[prodRow][prodCol] *= value;
                if (sectionCol >= maxCol - 1) {
                    matrixCol++;
                    if (matrixCol >= matrix.getColumnDimension())
                        matrixCol = 0;
                    sectionCol = -1;
                    value = matrix.getEntry(matrixRow, matrixCol);
                }
            }
            if (sectionRow >= maxRow - 1) {
                matrixRow++;
                if (matrixRow >= matrix.getRowDimension())
                    matrixRow = 0;
                sectionRow = -1;
            }
        }
    }

    // return a new matrix containing the Kronecker product
    return new Array2DRowRealMatrix(productData);
}

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/*  w w  w . j ava  2 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());
    }
}