List of usage examples for org.apache.commons.math3.linear Array2DRowRealMatrix Array2DRowRealMatrix
public Array2DRowRealMatrix(final double[][] d, final boolean copyArray) throws DimensionMismatchException, NoDataException, NullArgumentException
From source file:com.clust4j.algo.KMedoidsTests.java
/** * Assert that when all of the matrix entries are exactly the same, * the algorithm will still converge, yet produce one label: 0 *///from w w w .ja va 2 s.c o m @Override @Test public void testAllSame() { final double[][] x = MatUtils.rep(-1, 3, 3); final Array2DRowRealMatrix X = new Array2DRowRealMatrix(x, false); int[] labels = new KMedoids(X, new KMedoidsParameters(3).setVerbose(true)).fit().getLabels(); assertTrue(new VecUtils.IntSeries(labels, Inequality.EQUAL_TO, 0).all()); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.DifferentialEvolutionMinimizer.java
/** * Performs a minimization of a function starting with only parameter bounds; a full population is generated based on these bounds. * * @param f The function to be minimized. * @param parameterLowerBounds The lower bounds of each parameter. Generated parameter values less than these values will be discarded. * @param parameterUpperBounds The upper bounds of each parameter. Generated parameter values greater than these values will be discarded. * @param populationSize The size of the population of parameters sets to use for optimization. * @param scaleFactor Factor controlling the scale of crossed over entries during crossover events. * @param maxIterations The maximum number of iterations to allow before returning a result. * @param crossoverFrequency The frequency of crossover from 0 to 1. At any given parameter, this is the probability of initiating a crossover as well as the probability of ending one after it has started. * @param tol Relative function value tolerance controlling termination; if the maximal and minimal population values differ by less than this factor times the maximal value, optimization will terminate. * @return The parameter values at the minimal function value found. */// ww w. j av a2 s.co m public RealVector minimize(ObjectiveFunction f, RealVector parameterLowerBounds, RealVector parameterUpperBounds, int populationSize, double scaleFactor, int maxIterations, double crossoverFrequency, double tol) { int numberOfParameters = parameterLowerBounds.getDimension(); //generate the initial population RealMatrix population = new Array2DRowRealMatrix(populationSize, numberOfParameters); for (int i = 0; i < populationSize; i++) { for (int j = 0; j < numberOfParameters; j++) { population.setEntry(i, j, RandomGenerator.rand() * (parameterUpperBounds.getEntry(j) - parameterLowerBounds.getEntry(j)) + parameterLowerBounds.getEntry(j)); } } return minimizeWithPopulation(population, f, parameterLowerBounds, parameterUpperBounds, populationSize, scaleFactor, maxIterations, crossoverFrequency, tol); }
From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java
/** * Pca tensor./*from w w w . ja va2 s.com*/ * * @param cov the cov * @param power the power * @return the tensor */ @Nonnull public static Tensor pca(final Tensor cov, final double power) { final int inputbands = (int) Math.sqrt(cov.getDimensions()[2]); final int outputbands = inputbands; Array2DRowRealMatrix realMatrix = new Array2DRowRealMatrix(inputbands, inputbands); cov.coordStream(false).forEach(c -> { double v = cov.get(c); int x = c.getIndex() % inputbands; int y = (c.getIndex() - x) / inputbands; realMatrix.setEntry(x, y, v); }); Tensor[] features = PCAUtil.pcaFeatures(realMatrix, outputbands, new int[] { 1, 1, inputbands }, power); Tensor kernel = new Tensor(1, 1, inputbands * outputbands); PCAUtil.populatePCAKernel_1(kernel, features); return kernel; }
From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java
/** * Import template scan variables./*from w ww.j a v a 2 s. com*/ * * @param matrixModel the matrix model * @param nodeCounts the node counts * @param nodeBases the node bases * @param nodeRequests the node requests * @param nodeCount the node count * @param sheets the sheets * @throws NotStrictlyPositiveException the not strictly positive exception */ public static void importTemplateScanVariables(MatrixModel matrixModel, HashMap<Integer, Integer> nodeCounts, HashMap<Integer, Integer> nodeBases, int nodeRequests, int nodeCount, Iterator<XSSFSheet> sheets) throws NotStrictlyPositiveException { // Scan the variables. XSSFSheet sheet; while (sheets.hasNext()) { // Move to the next sheet. sheet = sheets.next(); // Allocate a new variable. MatrixVariable matrixVariable = new MatrixVariable(); // Assign the new variables's name and, possibly, units. String newName = sheet.getSheetName(); if (newName.contains("(")) { // Parse the name and units. matrixVariable.name = newName.substring(0, newName.indexOf("(") - 1); String unitsString = newName.substring(newName.indexOf("(") + 1, newName.indexOf(")")); // Attempt to convert the units text to a units value. try { // Convert the units text to a units value. matrixVariable.units = Amount.valueOf("1.0 " + unitsString); // Catch errors. } catch (Exception e) { // Use a default value. matrixVariable.units = Amount.ONE; } } else { // Assign the name. matrixVariable.name = newName; } // Scan the sheet for the next variable. for (int rowIndex = 0; rowIndex < nodeRequests; rowIndex++) { // Get the next equation. String equation = Util.getSpreadsheetString(sheet, rowIndex + 1, 0); // Store the equation. for (int count = 0; count < nodeCounts.get(rowIndex); count++) matrixVariable.equations.add(equation); // Check to make sure that the matrix is allocated. if (matrixVariable.coefficients == null) { // Allocate the coefficient matrix. matrixVariable.coefficients = new Array2DRowRealMatrix(nodeCount, nodeCount); } // Scan the columns for the next coefficient. for (int columnIndex = 0; columnIndex < nodeRequests; columnIndex++) { // Get the next coefficient. double fullValue = Util.getSpreadsheetNumber(sheet, rowIndex + 1, columnIndex + 2); // Store the next coefficients. MatrixModel.setTemplateEntry(nodeCounts, nodeBases, matrixVariable, rowIndex, columnIndex, fullValue); } } // Store the new variable. matrixModel.add(matrixVariable); } }
From source file:GeMSE.GS.Analysis.Stats.OneSamplePCAPanel.java
private void computePrincipalComponents() { RealMatrix realMatrix = MatrixUtils.createRealMatrix(_data); Covariance covariance = new Covariance(realMatrix); _covariance = covariance.getCovarianceMatrix(); EigenDecomposition ed = new EigenDecomposition(_covariance); double[] realEigenvalues = ed.getRealEigenvalues(); int pcaCols = numPCAIndices(realEigenvalues, _level); int eigenCount = realEigenvalues.length; _principalComponents = new Array2DRowRealMatrix(eigenCount, pcaCols); _variance = new ArrayRealVector(pcaCols); for (int i = 0; i < pcaCols; i++) { RealVector eigenVec = ed.getEigenvector(i); for (int j = 0; j < eigenCount; j++) _principalComponents.setEntry(j, i, eigenVec.getEntry(j)); _variance.setEntry(i, realEigenvalues[i]); }/*from ww w . j a v a 2 s. co m*/ }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.DBEA.java
/** * Updates the ideal point and intercepts given the new solution. * //from w w w. j a v a 2s . c o m * @param solution the new solution */ void updateIdealPointAndIntercepts(Solution solution) { if (!solution.violatesConstraints()) { // update the ideal point for (int j = 0; j < problem.getNumberOfObjectives(); j++) { idealPoint[j] = Math.min(idealPoint[j], solution.getObjective(j)); intercepts[j] = Math.max(intercepts[j], solution.getObjective(j)); } // compute the axis intercepts Population feasibleSolutions = getFeasibleSolutions(population); feasibleSolutions.add(solution); Population nondominatedSolutions = getNondominatedFront(feasibleSolutions); if (!nondominatedSolutions.isEmpty()) { // find the points with the largest value in each objective Population extremePoints = new Population(); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { extremePoints.add(largestObjectiveValue(i, nondominatedSolutions)); } if (numberOfUniqueSolutions(extremePoints) != problem.getNumberOfObjectives()) { for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = extremePoints.get(i).getObjective(i); } } else { try { RealMatrix b = new Array2DRowRealMatrix(problem.getNumberOfObjectives(), 1); RealMatrix A = new Array2DRowRealMatrix(problem.getNumberOfObjectives(), problem.getNumberOfObjectives()); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { b.setEntry(i, 0, 1.0); for (int j = 0; j < problem.getNumberOfObjectives(); j++) { A.setEntry(i, j, extremePoints.get(i).getObjective(j)); } } double numerator = new LUDecomposition(A).getDeterminant(); b.scalarMultiply(numerator); RealMatrix normal = MatrixUtils.inverse(A).multiply(b); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = numerator / normal.getEntry(i, 0); if (intercepts[i] <= 0 || Double.isNaN(intercepts[i]) || Double.isInfinite(intercepts[i])) { intercepts[i] = extremePoints.get(i).getObjective(i); } } } catch (RuntimeException e) { for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = extremePoints.get(i).getObjective(i); } } } } } }
From source file:com.clust4j.algo.HierarchicalTests.java
@Test public void testPredict() { HierarchicalAgglomerative h = new HierarchicalAgglomerativeParameters(3).fitNewModel(data_); /*/*from ww w. j a va 2s . c om*/ * Test on actual rows */ int[] predicted = h.predict(new Array2DRowRealMatrix( new double[][] { h.data.getRow(0), h.data.getRow(148), h.data.getRow(149) }, false)); assertTrue(VecUtils.equalsExactly(predicted, new int[] { 0, 2, 1 })); /* * Test on random rows... */ predicted = h .predict(new Array2DRowRealMatrix(new double[][] { new double[] { 150, 150, 150, 150 } }, false)); assertTrue(VecUtils.equalsExactly(predicted, new int[] { 2 })); /* * Test on k = 1 */ h = new HierarchicalAgglomerativeParameters(1).fitNewModel(data_); predicted = h.predict(new Array2DRowRealMatrix(new double[][] { h.data.getRow(0), h.data.getRow(148), h.data.getRow(149), new double[] { 150, 150, 150, 150 } }, false)); assertTrue(VecUtils.equalsExactly(predicted, new int[] { 0, 0, 0, 0 })); /* * Test for dim mismatch */ Array2DRowRealMatrix newData = new Array2DRowRealMatrix( new double[][] { new double[] { 150, 150, 150, 150, 150 } }, false); boolean a = false; try { h.predict(newData); } catch (DimensionMismatchException dim) { a = true; } finally { assertTrue(a); } }
From source file:com.clust4j.data.DataSet.java
/** * Shuffle the rows (and corresponding labels, if they exist) * and return the new dataset//from w w w .j a v a 2 s . c om * in place */ public DataSet shuffle() { final int m = numRows(); boolean has_labels = null != labels; // if the labels are null, there are no labels to shuffle... /* * Generate range of indices... */ ArrayList<Integer> indices = new ArrayList<Integer>(); for (int i = 0; i < m; i++) indices.add(i); /* * Shuffle indices in place... */ Collections.shuffle(indices); final int[] newLabels = has_labels ? new int[m] : null; final double[][] newData = new double[m][]; /* * Reorder things... */ int j = 0; for (Integer idx : indices) { if (has_labels) { newLabels[j] = this.labels[idx]; } newData[j] = VecUtils.copy(this.data.getRow(idx)); j++; } return new DataSet(new Array2DRowRealMatrix(newData, true), newLabels, getHeaders(), formatter, false); }
From source file:msi.gama.util.matrix.GamaIntMatrix.java
RealMatrix getRealMatrix() { final RealMatrix realMatrix = new Array2DRowRealMatrix(this.numRows, this.numCols); for (int i = 0; i < this.numRows; i++) { for (int j = 0; j < this.numCols; j++) { realMatrix.setEntry(i, j, Cast.asFloat(null, this.get(null, j, i))); }/*from w ww . ja va2 s .c om*/ } return realMatrix; }
From source file:ffx.crystal.Crystal.java
/** * Update all Crystal variables that are a function of unit cell parameters. *///from w w w. ja v a2s. c om private void updateCrystal() { switch (crystalSystem) { case CUBIC: case ORTHORHOMBIC: case TETRAGONAL: cos_alpha = 0.0; sin_beta = 1.0; cos_beta = 0.0; sin_gamma = 1.0; cos_gamma = 0.0; beta_term = 0.0; gamma_term = 1.0; volume = a * b * c; dVdA = b * c; dVdB = a * c; dVdC = a * b; dVdAlpha = 0.0; dVdBeta = 0.0; dVdGamma = 0.0; break; case MONOCLINIC: cos_alpha = 0.0; sin_beta = sin(toRadians(beta)); cos_beta = cos(toRadians(beta)); sin_gamma = 1.0; cos_gamma = 0.0; beta_term = 0.0; gamma_term = sin_beta; volume = sin_beta * a * b * c; dVdA = sin_beta * b * c; dVdB = sin_beta * a * c; dVdC = sin_beta * a * b; dVdAlpha = 0.0; dVdBeta = cos_beta * a * b * c; dVdGamma = 0.0; break; case HEXAGONAL: case TRICLINIC: case TRIGONAL: default: double sin_alpha = sin(toRadians(alpha)); cos_alpha = cos(toRadians(alpha)); sin_beta = sin(toRadians(beta)); cos_beta = cos(toRadians(beta)); sin_gamma = sin(toRadians(gamma)); cos_gamma = cos(toRadians(gamma)); beta_term = (cos_alpha - cos_beta * cos_gamma) / sin_gamma; gamma_term = sqrt(sin_beta * sin_beta - beta_term * beta_term); volume = sin_gamma * gamma_term * a * b * c; dVdA = sin_gamma * gamma_term * b * c; dVdB = sin_gamma * gamma_term * a * c; dVdC = sin_gamma * gamma_term * a * b; double dbeta = 2.0 * sin_beta * cos_beta - (2.0 * (cos_alpha - cos_beta * cos_gamma) * sin_beta * cos_gamma) / (sin_gamma * sin_gamma); double dgamma1 = -2.0 * (cos_alpha - cos_beta * cos_gamma) * cos_beta / sin_gamma; double dgamma2 = cos_alpha - cos_beta * cos_gamma; dgamma2 *= dgamma2 * 2.0 * cos_gamma / (sin_gamma * sin_gamma * sin_gamma); dVdAlpha = (cos_alpha - cos_beta * cos_gamma) * sin_alpha / (sin_gamma * gamma_term) * a * b * c; dVdBeta = 0.5 * sin_gamma * dbeta / gamma_term * a * b * c; dVdGamma = (cos_gamma * gamma_term + 0.5 * sin_gamma * (dgamma1 + dgamma2) / gamma_term) * a * b * c; break; } // a is the first row of A^(-1). Ai[0][0] = a; Ai[0][1] = 0.0; Ai[0][2] = 0.0; // b is the second row of A^(-1). Ai[1][0] = b * cos_gamma; Ai[1][1] = b * sin_gamma; Ai[1][2] = 0.0; // c is the third row of A^(-1). Ai[2][0] = c * cos_beta; Ai[2][1] = c * beta_term; Ai[2][2] = c * gamma_term; Ai00 = Ai[0][0]; Ai01 = Ai[0][1]; Ai02 = Ai[0][2]; Ai10 = Ai[1][0]; Ai11 = Ai[1][1]; Ai12 = Ai[1][2]; Ai20 = Ai[2][0]; Ai21 = Ai[2][1]; Ai22 = Ai[2][2]; // Invert A^-1 to get A RealMatrix m = new Array2DRowRealMatrix(Ai, true); m = new LUDecomposition(m).getSolver().getInverse(); A = m.getData(); // The columns of A are the reciprocal basis vectors A00 = A[0][0]; A10 = A[1][0]; A20 = A[2][0]; A01 = A[0][1]; A11 = A[1][1]; A21 = A[2][1]; A02 = A[0][2]; A12 = A[1][2]; A22 = A[2][2]; // Reciprocal basis vector lengths aStar = 1.0 / sqrt(A00 * A00 + A10 * A10 + A20 * A20); bStar = 1.0 / sqrt(A01 * A01 + A11 * A11 + A21 * A21); cStar = 1.0 / sqrt(A02 * A02 + A12 * A12 + A22 * A22); if (logger.isLoggable(Level.FINEST)) { logger.finest(String.format(" Reciprocal Lattice Lengths: (%8.3f, %8.3f, %8.3f)", aStar, bStar, cStar)); } // Interfacial diameters from the dot product of the real and reciprocal vectors interfacialRadiusA = (Ai00 * A00 + Ai01 * A10 + Ai02 * A20) * aStar; interfacialRadiusB = (Ai10 * A01 + Ai11 * A11 + Ai12 * A21) * bStar; interfacialRadiusC = (Ai20 * A02 + Ai21 * A12 + Ai22 * A22) * cStar; // Divide by 2 to get radii. interfacialRadiusA /= 2.0; interfacialRadiusB /= 2.0; interfacialRadiusC /= 2.0; if (logger.isLoggable(Level.FINEST)) { logger.finest(String.format(" Interfacial radii: (%8.3f, %8.3f, %8.3f)", interfacialRadiusA, interfacialRadiusB, interfacialRadiusC)); } G[0][0] = a * a; G[0][1] = a * b * cos_gamma; G[0][2] = a * c * cos_beta; G[1][0] = G[0][1]; G[1][1] = b * b; G[1][2] = b * c * cos_alpha; G[2][0] = G[0][2]; G[2][1] = G[1][2]; G[2][2] = c * c; // invert G to yield Gstar m = new Array2DRowRealMatrix(G, true); m = new LUDecomposition(m).getSolver().getInverse(); Gstar = m.getData(); List<SymOp> symOps = spaceGroup.symOps; int nSymm = symOps.size(); if (symOpsCartesian == null) { symOpsCartesian = new ArrayList<>(nSymm); } else { symOpsCartesian.clear(); } RealMatrix toFrac = new Array2DRowRealMatrix(A); RealMatrix toCart = new Array2DRowRealMatrix(Ai); for (int i = 0; i < nSymm; i++) { SymOp symOp = symOps.get(i); m = new Array2DRowRealMatrix(symOp.rot); // rot_c = A^(-1).rot_f.A RealMatrix rotMat = m.preMultiply(toCart.transpose()).multiply(toFrac.transpose()); // tr_c = tr_f.A^(-1) double tr[] = toCart.preMultiply(symOp.tr); symOpsCartesian.add(new SymOp(rotMat.getData(), tr)); } }