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:com.vsthost.rnd.commons.math.ext.linear.EMatrixUtils.java

/**
 * Shuffles rows of a matrix using the provided random number generator.
 *
 * @param matrix The matrix of which the rows will be shuffled.
 * @param randomGenerator The random number generator to be used.
 * @return The new shuffled matrix.//from w  ww.ja v a 2  s  .c  o  m
 */
public static RealMatrix shuffleRows(RealMatrix matrix, RandomGenerator randomGenerator) {
    // Create an index vector to be shuffled:
    int[] index = MathArrays.sequence(matrix.getRowDimension(), 0, 1);
    MathArrays.shuffle(index, randomGenerator);

    // Create a new matrix:
    RealMatrix retval = MatrixUtils.createRealMatrix(matrix.getRowDimension(), matrix.getColumnDimension());

    // Populate:
    for (int row = 0; row < index.length; row++) {
        retval.setRowVector(row, matrix.getRowVector(index[row]));
    }

    // Done, return:
    return retval;
}

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/*  w  ww  .j  a v a2s.co  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 ww w  .  j  a  v a  2  s  .com
 * @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:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * Returns the total sample size for the current per group sample size
 *///from   w w w  .ja va 2 s.  c  o  m
public static int getTotalSampleSize(RealMatrix designEssence, int perGroupSize) {
    return designEssence.getRowDimension() * perGroupSize;
}

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.//from ww  w .  j  av a  2s .co  m
 * @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:hivemall.utils.math.StatsUtils.java

/**
 * pdf(x, x_hat) = exp(-0.5 * (x-x_hat) * inv() * (x-x_hat)T) / ( 2^0.5d * det()^0.5)
 * /*from w  ww .ja  va 2s .c  om*/
 * @return value of probabilistic density function
 * @link https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function
 */
public static double pdf(@Nonnull final RealVector x, @Nonnull final RealVector x_hat,
        @Nonnull final RealMatrix sigma) {
    final int dim = x.getDimension();
    Preconditions.checkArgument(x_hat.getDimension() == dim,
            "|x| != |x_hat|, |x|=" + dim + ", |x_hat|=" + x_hat.getDimension());
    Preconditions.checkArgument(sigma.getRowDimension() == dim,
            "|x| != |sigma|, |x|=" + dim + ", |sigma|=" + sigma.getRowDimension());
    Preconditions.checkArgument(sigma.isSquare(), "Sigma is not square matrix");

    LUDecomposition LU = new LUDecomposition(sigma);
    final double detSigma = LU.getDeterminant();
    double denominator = Math.pow(2.d * Math.PI, 0.5d * dim) * Math.pow(detSigma, 0.5d);
    if (denominator == 0.d) { // avoid divide by zero
        return 0.d;
    }

    final RealMatrix invSigma;
    DecompositionSolver solver = LU.getSolver();
    if (solver.isNonSingular() == false) {
        SingularValueDecomposition svd = new SingularValueDecomposition(sigma);
        invSigma = svd.getSolver().getInverse(); // least square solution
    } else {
        invSigma = solver.getInverse();
    }
    //EigenDecomposition eigen = new EigenDecomposition(sigma);
    //double detSigma = eigen.getDeterminant();
    //RealMatrix invSigma = eigen.getSolver().getInverse();

    RealVector diff = x.subtract(x_hat);
    RealVector premultiplied = invSigma.preMultiply(diff);
    double sum = premultiplied.dotProduct(diff);
    double numerator = Math.exp(-0.5d * sum);

    return numerator / denominator;
}

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

/**
 * Returns the sums of rows./*from w  ww.  j  a  v  a  2  s.  c  o m*/
 *
 * @param matrix The matrix of which the sums of rows to be computed
 * @return A double array of row sums.
 */
public static double[] rowSums(RealMatrix matrix) {
    // Declare and initialize the return value:
    double[] retval = new double[matrix.getColumnDimension()];

    // Iterate over columns and compute totals:
    for (int row = 0; row < matrix.getRowDimension(); row++) {
        for (int col = 0; col < matrix.getColumnDimension(); col++) {
            retval[row] += matrix.getEntry(row, col);
        }
    }

    // Done, return col sums:
    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]);
        }/*from   w  w  w .  ja  v  a2  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//from  w ww.j a  v  a2  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:edu.cudenver.bios.matrix.OrthogonalPolynomials.java

/**
 * Computes orthogonal polynomial contrasts for the specified data values.  Currently only
 * supports fitting (not prediction contrasts).  
 * /*from  w w w  .j a  v  a2 s. com*/
 *    @param x the points at which the polynomials will be evaluated
 * @param maxDegree contrasts will be computed for degrees 1 to maxDegree
 * @return matrix containing 0th,1st, 2nd,...maxDegree-th degree contrasts in each column
 * @throws IllegalArgumentException
 */
public static RealMatrix orthogonalPolynomialCoefficients(double[] x, int maxDegree)
        throws IllegalArgumentException {
    if (x == null)
        throw new IllegalArgumentException("no data specified");
    if (maxDegree < 1)
        throw new IllegalArgumentException("max polynomial degree must be greater than 1");
    // count number of unique values
    HashSet<Double> s = new HashSet<Double>();
    for (double i : x)
        s.add(i);
    int uniqueCount = s.size();
    if (maxDegree >= uniqueCount)
        throw new IllegalArgumentException(
                "max polynomial degree must be less than the number of unique points");

    // center the data
    double xBar = StatUtils.mean(x);
    double[] xCentered = new double[x.length];
    for (int i = 0; i < x.length; i++)
        xCentered[i] = x[i] - xBar;
    // compute an "outer product" of the centered x vector and a vector 
    // containing the sequence 0 to maxDegree-1, but raise the x values
    // to the power in the sequence array
    double[][] xOuter = new double[x.length][maxDegree + 1];
    int row = 0;
    for (double xValue : xCentered) {
        for (int col = 0; col <= maxDegree; col++) {
            xOuter[row][col] = Math.pow(xValue, col);
        }
        row++;
    }
    // do some mysterious QR decomposition stuff.  See Emerson (1968)
    RealMatrix outerVector = new Array2DRowRealMatrix(xOuter);
    QRDecomposition qrDecomp = new QRDecomposition(outerVector);

    RealMatrix z = MatrixUtils.getDiagonalMatrix(qrDecomp.getR());
    RealMatrix raw = qrDecomp.getQ().multiply(z);

    // column sum of squared elements in raw
    double[] normalizingConstants = new double[raw.getColumnDimension()];
    for (int col = 0; col < raw.getColumnDimension(); col++) {
        normalizingConstants[col] = 0;
        for (row = 0; row < raw.getRowDimension(); row++) {
            double value = raw.getEntry(row, col);
            normalizingConstants[col] += value * value;
        }
    }

    // now normalize the raw values
    for (int col = 0; col < raw.getColumnDimension(); col++) {
        double normalConstantSqrt = Math.sqrt(normalizingConstants[col]);
        for (row = 0; row < raw.getRowDimension(); row++) {
            raw.setEntry(row, col, raw.getEntry(row, col) / normalConstantSqrt);
        }
    }

    return raw;
}