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

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

Introduction

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

Prototype

boolean isSquare();

Source Link

Document

Is this a square matrix?

Usage

From source file:com.joptimizer.util.Utils.java

/**
 * @see http://en.wikipedia.org/wiki/Machine_epsilon#Approximation_using_Java
 *//*  w ww.  j  a v a2  s .c o  m*/
//   public static final float calculateFloatMachineEpsilon() {
//      float eps = 1.0f;
//      do {
//         eps /= 2.0f;
//      } while ((float) (1.0 + (eps / 2.0)) != 1.0);
//      Log.d(MainActivity.JOPTIMIZER_LOGTAG,"Calculated float machine epsilon: " + eps);
//      return eps;
//   }

public static RealMatrix squareMatrixInverse(RealMatrix M) throws SingularMatrixException {
    if (!M.isSquare()) {
        throw new IllegalArgumentException("Not square matrix!");
    }

    // try commons-math cholesky
    try {
        CholeskyDecomposition cd = new CholeskyDecomposition(M);
        return cd.getSolver().getInverse();
    } catch (SingularMatrixException e) {
        throw e;
    } catch (Exception e) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, e.getMessage());
    }

    // try joptimizer cholesky
    try {
        CholeskyFactorization cd = new CholeskyFactorization(M.getData());
        double[][] MInv = cd.getInverse();
        return MatrixUtils.createRealMatrix(MInv);
    } catch (Exception e) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, e.getMessage());
    }

    // try LU
    try {
        LUDecomposition ld = new LUDecomposition(M);
        return ld.getSolver().getInverse();
    } catch (SingularMatrixException e) {
        throw e;
    } catch (Exception e) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, e.getMessage());
    }

    // try QR
    try {
        QRDecomposition qr = new org.apache.commons.math3.linear.QRDecomposition(M);
        return qr.getSolver().getInverse();
    } catch (SingularMatrixException e) {
        throw e;
    } catch (Exception e) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, e.getMessage());
    }

    return null;
}

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

/**
 * The method determines if the given matrix is positive definite.
 * The matrix must be square.//from  w  w w.j  av  a 2  s . c  o m
 * @param matrix
 * @return true if the matrix is positive definite.
 */
public static boolean isPositiveDefinite(RealMatrix matrix) {
    if (matrix == null || !matrix.isSquare()) {
        throw new IllegalArgumentException("Matrix must be non-null, " + "square. ");
    }
    double[] eigenValues = new EigenDecomposition(matrix).getRealEigenvalues();

    // if all eigenValues are positive, we return true
    boolean isPositiveDefinite = true;
    for (int i = 0; i < eigenValues.length; i++) {
        if (eigenValues[i] <= -EPSILON) {
            isPositiveDefinite = false;
            break;
        }
    }
    return isPositiveDefinite;
}

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

/**
 * The method determines if the given matrix is positive semidefinite.
 * The matrix must be square.// w ww .j a  v a  2 s.co m
 * @param matrix
 * @return true if the matrix is positive semidefinite.
 */
public static boolean isPositiveSemidefinite(RealMatrix matrix) {
    if (matrix == null || !matrix.isSquare()) {
        throw new IllegalArgumentException("Matrix must be non-null, " + "square. ");
    }
    double[] eigenValues = new EigenDecomposition(matrix).getRealEigenvalues();

    // if all eigenValues are nonnegative, we return true
    boolean isPositiveSemidefinite = true;
    for (int i = 0; i < eigenValues.length; i++) {
        if (eigenValues[i] < -EPSILON) {
            isPositiveSemidefinite = false;
            break;
        }
    }
    return isPositiveSemidefinite;
}

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)
 * //  w w w.j a va  2  s .  c o  m
 * @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:info.debatty.java.datasets.sift.Matrix.java

/**
 * @param A a square matrix.//from   w  w  w .  j  av  a  2s  .  c o m
 * @return the inverse of A or null if A is non-square or singular.
 */
public static double[][] inverse(final double[][] A) {
    RealMatrix M = MatrixUtils.createRealMatrix(A);
    if (!M.isSquare()) {
        return null;
    } else {
        double[][] Ai = null;
        try {
            RealMatrix Mi = MatrixUtils.inverse(M); //new LUDecomposition(M).getSolver().getInverse();
            Ai = Mi.getData();
        } catch (SingularMatrixException e) {
        }
        return Ai;
    }
}

From source file:imagingbook.lib.math.Matrix.java

/**
 * @param A a square matrix./*from  w  w  w.  ja  v a 2 s  . com*/
 * @return the inverse of A or null if A is non-square or singular.
 */
public static double[][] inverse(final double[][] A) {
    RealMatrix M = MatrixUtils.createRealMatrix(A);
    if (!M.isSquare())
        return null;
    else {
        double[][] Ai = null;
        try {
            RealMatrix Mi = new LUDecomposition(M).getSolver().getInverse();
            Ai = Mi.getData();
        } catch (SingularMatrixException e) {
        }
        return Ai;
    }
}

From source file:edu.cudenver.bios.matrix.test.TestMatrixOrthonormalization.java

/**
 * Verify that the Q'Q = I for the Q matrix produced by the
 * orthonormalization// w w w.  ja  v  a 2 s  .  c o  m
 */
public void testQQisIdentity() {
    RealMatrix Q = norm.getQ();

    // verify that Q'Q = identity
    RealMatrix shouldBeIdentityMatrix = Q.transpose().multiply(Q);
    // make sure the matrix is sqaure
    if (!shouldBeIdentityMatrix.isSquare()) {
        fail();
    }
    // make sure the diagonal elements are one (within tolerance), and off diagonals
    // are zero (within tolerance)
    for (int r = 0; r < shouldBeIdentityMatrix.getRowDimension(); r++) {
        for (int c = 0; c < shouldBeIdentityMatrix.getColumnDimension(); c++) {
            double shouldBeValue = (r == c) ? 1 : 0;
            if (Precision.compareTo(shouldBeIdentityMatrix.getEntry(r, c), shouldBeValue, TOLERANCE) != 0)
                fail();
        }
    }
    assertTrue(true);
}

From source file:edu.cudenver.bios.power.glmm.GLMMTestHotellingLawley.java

/**
 * Compute a Hotelling-Lawley Trace statistic
 *
 * @param H hypothesis sum of squares matrix
 * @param E error sum of squares matrix/*from  ww w  . j  a  v  a 2s  .  c  o  m*/
 * @returns F statistic
 */
private double getHotellingLawleyTrace(RealMatrix H, RealMatrix E) throws IllegalArgumentException {
    if (!H.isSquare() || !E.isSquare() || H.getColumnDimension() != E.getRowDimension())
        throw new IllegalArgumentException(
                "Failed to compute Hotelling-Lawley Trace: hypothesis and error matrices must be square and same dimensions");

    RealMatrix inverseE = new LUDecomposition(E).getSolver().getInverse();
    RealMatrix HinverseE = H.multiply(inverseE);

    return HinverseE.getTrace();
}

From source file:es.csic.iiia.planes.util.InverseWishartDistribution.java

/**
 * Builds a new Inverse Wishart distribution with the given scale and degrees of freedom.
 *
 * @param scaleMatrix scale matrix./*w  ww  .  j a va 2  s. co  m*/
 * @param df degrees of freedom.
 */
public InverseWishartDistribution(RealMatrix scaleMatrix, double df) {
    if (!scaleMatrix.isSquare()) {
        throw new RuntimeException("scaleMatrix must be square.");
    }

    this.scaleMatrix = scaleMatrix;
    this.df = df;
    this.random = new Well19937c();
    initialize();
}

From source file:edu.cudenver.bios.power.glmm.GLMMTestPillaiBartlett.java

/**
 * Compute a Pillai Bartlett Trace statistic
 * /*from www  .j  a va  2 s .c  o m*/
 * @param H hypothesis sum of squares matrix
 * @param E error sum of squares matrix
 * @returns F statistic
 */
private double getPillaiBartlettTrace(RealMatrix H, RealMatrix E) {
    if (!H.isSquare() || !E.isSquare() || H.getColumnDimension() != E.getRowDimension())
        throw new IllegalArgumentException(
                "Failed to compute Pillai-Bartlett Trace: hypothesis and error matrices must be square and same dimensions");

    double a = C.getRowDimension();
    double b = U.getColumnDimension();
    double s = (a < b) ? a : b;
    double p = beta.getColumnDimension();

    RealMatrix adjustedH = H;
    if ((s == 1 && p > 1) || fMethod == FApproximation.PILLAI_ONE_MOMENT_OMEGA_MULT
            || fMethod == FApproximation.MULLER_TWO_MOMENT_OMEGA_MULT) {
        adjustedH = H.scalarMultiply(((double) (totalN - rank) / (double) totalN));
    }

    RealMatrix T = adjustedH.add(E);
    RealMatrix inverseT = new LUDecomposition(T).getSolver().getInverse();

    RealMatrix HinverseT = adjustedH.multiply(inverseT);

    return HinverseT.getTrace();
}