List of usage examples for org.apache.commons.math3.linear Array2DRowRealMatrix multiply
public Array2DRowRealMatrix multiply(final Array2DRowRealMatrix m) throws DimensionMismatchException
From source file:MultivariateNormalDistribution.java
/** * Creates a multivariate normal distribution with the given mean vector and * covariance matrix.//from ww w . j av 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 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.apache.hadoop.hive.ql.abm.simulation.MCSimNode.java
public List<SimulationResult> simulate(IntArrayList[] requests) { init(requests);/*from w ww . ja v a 2 s . com*/ if (dimension == 0) { return null; } if (parent == null) { return defaultSimulate(); } List<SimulationResult> parRet = parent.simulate(targets); if (parRet == null) { return defaultSimulate(); } List<SimulationResult> ret = new ArrayList<SimulationResult>(); for (SimulationResult res : parRet) { ArrayList<IntArrayList> condIds = res.lastCondId; boolean[] fake = new boolean[dimension]; double[] mu = new double[dimension]; double[][] A = new double[dimension][dimension]; double[][] B = new double[res.invSigma.getColumnDimension()][dimension]; double[] zero = new double[dimension]; for (int i = 0; i < within1.length; ++i) { IntArrayList cIds = condIds.get(i); within1[i].fill(cIds, fake, mu, A); InterDistOracle[] w2s = within2[i]; for (int j = i + 1; j < within2.length; ++j) { w2s[j].fillSym(cIds, condIds.get(j), fake, mu, A); } } int dif = between.size() - res.condIds.size(); double[] pmu = res.getMean(); for (int i = 0; i < targets.length; ++i) { int cum = 0; IntArrayList cIds = condIds.get(i); for (int k = 0; k < res.condIds.size(); ++k) { ArrayList<IntArrayList> condIds2 = res.condIds.get(k); InterDistOracle[] os = between.get(k + dif)[i]; for (int j = 0; j < os.length; ++j) { cum += os[j].fillAsym(cIds, condIds2.get(j), fake, mu, pmu, B, cum); } } } for (int k = 0, cum = 0; k < res.condIds.size(); ++k) { ArrayList<IntArrayList> pCIds = res.condIds.get(k); InterDistOracle[][] oss = between.get(k + dif); for (int j = 0; j < oss.length; ++j) { IntArrayList cIds = pCIds.get(j); InterDistOracle[] os = oss[j]; int off = 0; for (int i = 0; i < os.length; ++i) { off = os[i].fillAsym(cIds, condIds.get(i), fake, pmu, mu, B, cum); } cum += off; } } Array2DRowRealMatrix a = new Array2DRowRealMatrix(A); Array2DRowRealMatrix b = new Array2DRowRealMatrix(B); Array2DRowRealMatrix c = (Array2DRowRealMatrix) b.transpose(); Array2DRowRealMatrix tmp = c.multiply(res.invSigma); Array2DRowRealMatrix sigma = a.subtract(tmp.multiply(b)); double[] scale = correct(sigma.getDataRef()); MultivariateNormalDistribution dist = new MultivariateNormalDistribution(zero, sigma.getDataRef()); double[][] smpls = dist.sample(res.samples.size()); int pos = 0; for (double[] smpl : smpls) { if (scale != null) { restore(smpl, scale); } fixFake(fake, mu, smpl); double[] s = res.getSample(pos); subtract(s, pmu); add(smpl, tmp.operate(s)); res.samples.get(pos)[level] = smpl; ++pos; } res.means.add(mu); res.invSigma = new Array2DRowRealMatrix( new LUDecomposition(concat(a, c, b, res.invSigma)).getSolver().getInverse().getData()); dispatch(res, ret); } return ret; }
From source file:org.interpss.opf.dc.impl.EqIneqMatrixBuilder.java
public Array2DRowRealMatrix formCiq() { int numOfBranch = opfNet.getNoActiveBranch(); int numOfBus = opfNet.getNoActiveBus(); int numOfGen = opfNet.getNoOfGen(); double bij = DEFAULT_BIJ; int braIndex = 0; Array2DRowRealMatrix braAdmDiag = new Array2DRowRealMatrix(numOfBranch, numOfBranch); Array2DRowRealMatrix braBusAdjacent = new Array2DRowRealMatrix(numOfBranch, numOfBus - 1); int swingIndex = this.getSwingBusIndex(); for (Branch bra : opfNet.getBranchList()) { //if (bra.isAclfBranch()) { DclfOpfBranch aclfBra = (DclfOpfBranch) bra; // create branch admittance matrix bij = (aclfBra.getZ().getImaginary() > 0.00001) ? 1 / aclfBra.getZ().getImaginary() : DEFAULT_BIJ; // in case x=0; braAdmDiag.setEntry(braIndex, braIndex, bij); // create branch-bus connected or adjacent matrix; if (!((DclfOpfBus) bra.getFromBus()).isSwing()) { int fromBusIndex = bra.getFromBus().getSortNumber(); fromBusIndex = (fromBusIndex < swingIndex) ? fromBusIndex : fromBusIndex - 1; // insure nonswing bus; braBusAdjacent.setEntry(braIndex, fromBusIndex, 1); }/* w w w .ja va2 s .com*/ if (!((DclfOpfBus) bra.getToBus()).isSwing()) { int toBusIndex = bra.getToBus().getSortNumber(); toBusIndex = (toBusIndex < swingIndex) ? toBusIndex : toBusIndex - 1; braBusAdjacent.setEntry(braIndex, toBusIndex, -1); } braIndex++; //} } int genIndex = 0; Array2DRowRealMatrix eyeGenP = new Array2DRowRealMatrix(numOfGen, numOfGen); for (Bus bus : opfNet.getBusList()) { if (opfNet.isOpfGenBus(bus)) { eyeGenP.setEntry(genIndex, genIndex, 1); genIndex++; } } Array2DRowRealMatrix DAr = braAdmDiag.multiply(braBusAdjacent); // Ciq'={Ot,-braAdmDiag*braBusAdjacent; // -Ot,braAdmDiag*braBusAdjacent; // eyeGenP,Op; // -eyeGenP,-Op} Array2DRowRealMatrix CiqTranspose = new Array2DRowRealMatrix(numOfBranch * 2 + numOfGen * 2, numOfGen + numOfBus - 1); CiqTranspose.setSubMatrix(DAr.scalarMultiply(-1).getData(), 0, numOfGen); CiqTranspose.setSubMatrix(DAr.getData(), numOfBranch, numOfGen); CiqTranspose.setSubMatrix(eyeGenP.getData(), 2 * numOfBranch, 0); CiqTranspose.setSubMatrix(eyeGenP.scalarMultiply(-1).getData(), 2 * numOfBranch + numOfGen, 0); // Ciq=CiqTranspose' return (Array2DRowRealMatrix) CiqTranspose.transpose(); }
From source file:org.mpetnuch.gauss.linearalgebra.blas3.JBlasLevel3Test.java
@Test public void testDgemm() { final DenseMatrix a = DenseMatrix.from(generateData(M, P)); final DenseMatrix b = DenseMatrix.from(generateData(P, N)); final Array2DRowRealMatrix aa = new Array2DRowRealMatrix(generateData(M, P)); final Array2DRowRealMatrix bb = new Array2DRowRealMatrix(generateData(P, N)); final DenseMatrix c = a.multiply(b); final Array2DRowRealMatrix cc = aa.multiply(bb); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { Assert.assertEquals(c.get(i, j), cc.getEntry(i, j), 1.0e-6); }/* ww w . j av a 2 s . c om*/ } }
From source file:org.pmad.gmm.MyMND.java
/** * Creates a multivariate normal distribution with the given mean vector and * covariance matrix./*from w w w. jav 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:outlineDescriptor.ODUtils.java
/** * Generates a 2D covariance matrix for a distribution function * * @param vX X component//from w ww . j a v a2 s . co m * @param vY Y component * @param eV1 First eigenvalue * @param eV2 Second eigenvalue * * @return Resulting covariance matrix */ public static Array2DRowRealMatrix getDistributionCovMatrix(double vX, double vY, double eV1, double eV2) { double multiplier = 1 / (vX * vX + vY * vY); Array2DRowRealMatrix vectMat = new Array2DRowRealMatrix(2, 2); Array2DRowRealMatrix valMat = new Array2DRowRealMatrix(2, 2); valMat.setEntry(0, 0, eV1); valMat.setEntry(1, 1, eV2); vectMat.setEntry(0, 0, vX); vectMat.setEntry(0, 1, vY); vectMat.setEntry(1, 0, -vY); vectMat.setEntry(1, 1, vX); Array2DRowRealMatrix vE = vectMat.multiply(valMat); Array2DRowRealMatrix tempCov = vE.multiply((Array2DRowRealMatrix) vectMat.transpose()); return (Array2DRowRealMatrix) tempCov.scalarMultiply(multiplier); }
From source file:xyz.lejon.sampling.FastMultivariateNormalDistribution.java
/** * Creates a multivariate normal distribution with the given mean vector and * covariance matrix.//www . j ava 2s . 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); }