Example usage for org.apache.commons.math3.linear NonPositiveDefiniteMatrixException NonPositiveDefiniteMatrixException

List of usage examples for org.apache.commons.math3.linear NonPositiveDefiniteMatrixException NonPositiveDefiniteMatrixException

Introduction

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

Prototype

public NonPositiveDefiniteMatrixException(double wrong, int index, double threshold) 

Source Link

Document

Construct an exception.

Usage

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

public static RealMatrix makePositiveDefinite(final RealMatrix M, final double eps) {
    assert (eps > 0.0);
    final SingularValueDecomposition svd = new SingularValueDecomposition(M);
    final RealMatrix Sigma = svd.getS().copy();
    final int N = Math.min(Sigma.getColumnDimension(), Sigma.getRowDimension());
    for (int i = 0; i < N; ++i) {
        final double lambda = Sigma.getEntry(i, i);
        System.out.println("lambda_" + i + " = " + lambda);
        if (Math.abs(lambda) < eps) {
            System.out.println("Corrected " + i);
            Sigma.setEntry(i, i, eps);//from   w  w  w  .  jav  a  2 s  . c o m
        } else if (lambda < 0.0) {
            throw new NonPositiveDefiniteMatrixException(lambda, i, eps);
        } else {
            Sigma.setEntry(i, i, lambda);
        }
    }
    return svd.getU().multiply(Sigma).multiply(svd.getVT());
}

From source file:MultivariateNormalDistribution.java

/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.//from  w w  w . j  a  v  a 2s.  c o  m
 * <br/>
 * The number of dimensions is equal to the length of the mean vector
 * and to the number of rows and columns of the covariance matrix.
 * It is frequently written as "p" in formulae.
 *
 * @param rng Random Number Generator.
 * @param means Vector of means.
 * @param covariances Covariance matrix.
 * @throws DimensionMismatchException if the arrays length are
 * inconsistent.
 * @throws SingularMatrixException if the eigenvalue decomposition cannot
 * be performed on the provided covariance matrix.
 * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is
 * negative.
 */
public MultivariateNormalDistribution(RandomGenerator rng, final double[] means, final double[][] covariances)
        throws SingularMatrixException, DimensionMismatchException, NonPositiveDefiniteMatrixException {
    super(rng, means.length);

    final int dim = means.length;

    if (covariances.length != dim) {
        throw new DimensionMismatchException(covariances.length, dim);
    }

    for (int i = 0; i < dim; i++) {
        if (dim != covariances[i].length) {
            throw new DimensionMismatchException(covariances[i].length, dim);
        }
    }

    this.means = MathArrays.copyOf(means);

    covarianceMatrix = new Array2DRowRealMatrix(covariances);

    // Covariance matrix eigen decomposition.
    final EigenDecomposition covMatDec = new EigenDecomposition(covarianceMatrix);

    // Compute and store the inverse.
    covarianceMatrixInverse = covMatDec.getSolver().getInverse();
    // Compute and store the determinant.
    covarianceMatrixDeterminant = covMatDec.getDeterminant();

    // Eigenvalues of the covariance matrix.
    final double[] covMatEigenvalues = covMatDec.getRealEigenvalues();

    for (int i = 0; i < covMatEigenvalues.length; i++) {
        if (covMatEigenvalues[i] < 0) {
            throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0);
        }
    }

    // Matrix where each column is an eigenvector of the covariance matrix.
    final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
    for (int v = 0; v < dim; v++) {
        final double[] evec = covMatDec.getEigenvector(v).toArray();
        covMatEigenvectors.setColumn(v, evec);
    }

    final RealMatrix tmpMatrix = covMatEigenvectors.transpose();

    // Scale each eigenvector by the square root of its eigenvalue.
    for (int row = 0; row < dim; row++) {
        final double factor = FastMath.sqrt(covMatEigenvalues[row]);
        for (int col = 0; col < dim; col++) {
            tmpMatrix.multiplyEntry(row, col, factor);
        }
    }

    samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
}

From source file:org.pmad.gmm.MyMND.java

/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix./* w ww  .ja v  a2  s  .  c o  m*/
 * <br/>
 * The number of dimensions is equal to the length of the mean vector
 * and to the number of rows and columns of the covariance matrix.
 * It is frequently written as "p" in formulae.
 *
 * @param rng Random Number Generator.
 * @param means Vector of means.
 * @param covariances Covariance matrix.
 * @throws DimensionMismatchException if the arrays length are
 * inconsistent.
 * @throws SingularMatrixException if the eigenvalue decomposition cannot
 * be performed on the provided covariance matrix.
 * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is
 * negative.
 */
public MyMND(RandomGenerator rng, final double[] means, final double[][] covariances)
        throws SingularMatrixException, DimensionMismatchException, NonPositiveDefiniteMatrixException {
    super(rng, means.length);

    final int dim = means.length;

    if (covariances.length != dim) {
        throw new DimensionMismatchException(covariances.length, dim);
    }

    for (int i = 0; i < dim; i++) {
        if (dim != covariances[i].length) {
            throw new DimensionMismatchException(covariances[i].length, dim);
        }
    }

    this.means = MathArrays.copyOf(means);
    double msum = 0;
    for (int i = 0; i < covariances.length; i++) {
        for (int j = 0; j < covariances.length; j++) {
            msum += covariances[i][j];
        }
    }
    msum /= covariances.length * covariances.length;
    //        System.out.print("in");
    MyEDC covMatDec = null;
    double a = -1;
    while (true) {
        try {

            covarianceMatrix = new Array2DRowRealMatrix(covariances);

            covMatDec = new MyEDC(covarianceMatrix);

            // Compute and store the inverse.
            covarianceMatrixInverse = covMatDec.getSolver().getInverse();
            a *= -1;
            break;
        } catch (NoDataException e) {
            e.printStackTrace();
        } catch (NullArgumentException e) {
            e.printStackTrace();
        } catch (MathArithmeticException e) {
            e.printStackTrace();
        } catch (SingularMatrixException e) {
            //            System.out.print("S");
            for (int i = 0; i < covariances.length; i++) {
                double add = covariances[i][i] == 0 ? msum : covariances[i][i];
                covariances[i][i] += new Random().nextDouble() * add * 0.01;
            }
        }
        //         catch (MaxCountExceededException e) {
        ////            e.printStackTrace();
        ////            System.out.print("M"+msum);
        //            for (int i = 0; i < covariances.length; i++) {
        //               for (int j = i; j < covariances.length; j++) {
        //                  double add = covariances[i][j] == 0?msum:covariances[i][j];
        //                  add = new Random().nextDouble()*add*0.1*a;
        //                  covariances[i][j] += add;
        //                  covariances[j][i] += add;
        //               }
        //            }
        ////            break;
        //         }
    }
    // Compute and store the determinant.
    covarianceMatrixDeterminant = covMatDec.getDeterminant();

    // Eigenvalues of the covariance matrix.
    final double[] covMatEigenvalues = covMatDec.getRealEigenvalues();

    for (int i = 0; i < covMatEigenvalues.length; i++) {
        if (covMatEigenvalues[i] < 0) {
            throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0);
        }
    }

    // Matrix where each column is an eigenvector of the covariance matrix.
    final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
    for (int v = 0; v < dim; v++) {
        final double[] evec = covMatDec.getEigenvector(v).toArray();
        covMatEigenvectors.setColumn(v, evec);
    }

    final RealMatrix tmpMatrix = covMatEigenvectors.transpose();

    // Scale each eigenvector by the square root of its eigenvalue.
    for (int row = 0; row < dim; row++) {
        final double factor = FastMath.sqrt(covMatEigenvalues[row]);
        for (int col = 0; col < dim; col++) {
            tmpMatrix.multiplyEntry(row, col, factor);
        }
    }

    samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
}

From source file:xyz.lejon.sampling.FastMultivariateNormalDistribution.java

/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix./*from  w  ww  .  j a va2s.  com*/
 * <br/>
 * The number of dimensions is equal to the length of the mean vector
 * and to the number of rows and columns of the covariance matrix.
 * It is frequently written as "p" in formulae.
 *
 * @param rng Random Number Generator.
 * @param means Vector of means.
 * @param covariances Covariance matrix.
 * @throws DimensionMismatchException if the arrays length are
 * inconsistent.
 * @throws SingularMatrixException if the eigenvalue decomposition cannot
 * be performed on the provided covariance matrix.
 * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is
 * negative.
 */
public FastMultivariateNormalDistribution(RandomGenerator rng, final double[] means,
        final double[][] covariances)
        throws SingularMatrixException, DimensionMismatchException, NonPositiveDefiniteMatrixException {
    super(rng, means.length);

    final int dim = means.length;

    if (covariances.length != dim) {
        throw new DimensionMismatchException(covariances.length, dim);
    }

    for (int i = 0; i < dim; i++) {
        if (dim != covariances[i].length) {
            throw new DimensionMismatchException(covariances[i].length, dim);
        }
    }

    this.means = MathArrays.copyOf(means);

    covarianceMatrix = new Array2DRowRealMatrix(covariances);

    // Covariance matrix eigen decomposition.
    final EigenDecomposition covMatDec = new EigenDecomposition(covarianceMatrix);

    // Compute and store the inverse.
    covarianceMatrixInverse = covMatDec.getSolver().getInverse();
    // Compute and store the determinant.
    covarianceMatrixDeterminant = covMatDec.getDeterminant();

    // Eigenvalues of the covariance matrix.
    final double[] covMatEigenvalues = covMatDec.getRealEigenvalues();

    for (int i = 0; i < covMatEigenvalues.length; i++) {
        if (covMatEigenvalues[i] < 0) {
            throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0);
        }
    }

    // Matrix where each column is an eigenvector of the covariance matrix.
    final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
    final Array2DRowRealMatrix tmpMatrix = new Array2DRowRealMatrix(dim, dim);
    for (int v = 0; v < dim; v++) {
        final double factor = FastMath.sqrt(covMatEigenvalues[v]);
        final double[] evec = covMatDec.getEigenvector(v).toArray();
        covMatEigenvectors.setColumn(v, evec);
        tmpMatrix.setRow(v, evec);
        for (int col = 0; col < dim; col++) {
            tmpMatrix.multiplyEntry(v, col, factor);
        }
    }

    samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
}