Java Code Examples for org.apache.commons.math3.linear.Array2DRowRealMatrix#transpose()

The following examples show how to use org.apache.commons.math3.linear.Array2DRowRealMatrix#transpose() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KnnRegressionEvaluator.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public double[] scale(double[] predictors) {
  double[][] data = observations.getData();
  //We need to scale the columns of the data matrix with along with the predictors
  Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(data);
  Array2DRowRealMatrix transposed = (Array2DRowRealMatrix) matrix.transpose();
  double[][] featureRows = transposed.getDataRef();

  double[] scaledPredictors = new double[predictors.length];

  for(int i=0; i<featureRows.length; i++) {
    double[] featureRow = featureRows[i];
    double[] combinedFeatureRow = new double[featureRow.length+1];
    System.arraycopy(featureRow, 0, combinedFeatureRow, 0, featureRow.length);
    combinedFeatureRow[featureRow.length] = predictors[i];  // Add the last feature from the predictor
    double[] scaledFeatures = MinMaxScaleEvaluator.scale(combinedFeatureRow, 0, 1);
    scaledPredictors[i] = scaledFeatures[featureRow.length];
    System.arraycopy(scaledFeatures, 0, featureRow, 0, featureRow.length);
  }

  Array2DRowRealMatrix scaledFeatureMatrix = new Array2DRowRealMatrix(featureRows);


  Array2DRowRealMatrix scaledObservationsMatrix= (Array2DRowRealMatrix)scaledFeatureMatrix.transpose();
  this.scaledObservations = new Matrix(scaledObservationsMatrix.getDataRef());
  return scaledPredictors;
}
 
Example 2
Source File: TransposeEvaluator.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Object doWork(Object value) throws IOException{
  if(null == value){
    return null;
  } else if(value instanceof Matrix) {
    Matrix matrix = (Matrix) value;
    double[][] data = matrix.getData();
    Array2DRowRealMatrix amatrix = new Array2DRowRealMatrix(data, false);
    Array2DRowRealMatrix tmatrix = (Array2DRowRealMatrix)amatrix.transpose();
    Matrix newMatrix = new Matrix(tmatrix.getDataRef());
    //Switch the row and column labels
    newMatrix.setColumnLabels(matrix.getRowLabels());
    newMatrix.setRowLabels(matrix.getColumnLabels());
    return newMatrix;
  } else {
    throw new IOException("matrix parameter expected for transpose function");
  }
}
 
Example 3
Source File: KnnRegressionEvaluator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public Matrix scale(Matrix predictors) {
  double[][] observationData = observations.getData();
  //We need to scale the columns of the data matrix with along with the predictors
  Array2DRowRealMatrix observationMatrix = new Array2DRowRealMatrix(observationData);
  Array2DRowRealMatrix observationTransposed = (Array2DRowRealMatrix) observationMatrix.transpose();
  double[][] observationFeatureRows = observationTransposed.getDataRef();

  double[][] predictorsData = predictors.getData();
  //We need to scale the columns of the data matrix with along with the predictors
  Array2DRowRealMatrix predictorMatrix = new Array2DRowRealMatrix(predictorsData);
  Array2DRowRealMatrix predictorTransposed = (Array2DRowRealMatrix) predictorMatrix.transpose();
  double[][] predictorFeatureRows = predictorTransposed.getDataRef();

  for(int i=0; i<observationFeatureRows.length; i++) {
    double[] observationFeatureRow = observationFeatureRows[i];
    double[] predictorFeatureRow = predictorFeatureRows[i];
    double[] combinedFeatureRow = new double[observationFeatureRow.length+predictorFeatureRow.length];
    System.arraycopy(observationFeatureRow, 0, combinedFeatureRow, 0, observationFeatureRow.length);
    System.arraycopy(predictorFeatureRow, 0, combinedFeatureRow, observationFeatureRow.length, predictorFeatureRow.length);

    double[] scaledFeatures = MinMaxScaleEvaluator.scale(combinedFeatureRow, 0, 1);
    System.arraycopy(scaledFeatures, 0, observationFeatureRow, 0, observationFeatureRow.length);
    System.arraycopy(scaledFeatures, observationFeatureRow.length, predictorFeatureRow, 0, predictorFeatureRow.length);
  }

  Array2DRowRealMatrix scaledFeatureMatrix = new Array2DRowRealMatrix(observationFeatureRows);
  Array2DRowRealMatrix scaledObservationsMatrix= (Array2DRowRealMatrix)scaledFeatureMatrix.transpose();
  this.scaledObservations = new Matrix(scaledObservationsMatrix.getDataRef());

  Array2DRowRealMatrix scaledPredictorMatrix = new Array2DRowRealMatrix(predictorFeatureRows);
  Array2DRowRealMatrix scaledTransposedPredictorMatrix= (Array2DRowRealMatrix)scaledPredictorMatrix.transpose();
  return new Matrix(scaledTransposedPredictorMatrix.getDataRef());
}
 
Example 4
Source File: Math_11_MultivariateNormalDistribution_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 5
Source File: Math_11_MultivariateNormalDistribution_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 6
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 7
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 8
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 9
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 10
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}
 
Example 11
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a multivariate normal distribution with the given mean vector and
 * covariance matrix.
 * <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);
}