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.cloudera.oryx.common.math.MatrixUtilsTest.java
@Test public void testAccess() { double[][] data = { new double[] { 1 }, }; RealMatrix matrix = new Array2DRowRealMatrix(data, false); assertSame(data, MatrixUtils.accessMatrixDataDirectly(matrix)); }
From source file:com.clust4j.algo.NNHSTests.java
License:asdf
@Test public void testKD1() { final Array2DRowRealMatrix mat = new Array2DRowRealMatrix(a, false); KDTree kd = new KDTree(mat); QuadTup<double[][], int[], NodeData[], double[][][]> arrays = kd.getArrays(); assertTrue(MatUtils.equalsExactly(arrays.getFirst(), a)); assertTrue(VecUtils.equalsExactly(new int[] { 0, 1, 2 }, arrays.getSecond())); Triple<Integer, Integer, Integer> stats = kd.getTreeStats(); assertTrue(stats.getLeft() == 0);//from w w w.j a v a 2s. co m assertTrue(stats.getMiddle() == 0); assertTrue(stats.getRight() == 0); NodeData data = arrays.getThird()[0]; assertTrue(data.idx_start == 0); assertTrue(data.idx_end == 3); assertTrue(data.is_leaf); assertTrue(data.radius == 1); }
From source file:ellipsoidFit.FitPoints.java
/** * Solve the polynomial expression Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + * 2Gx + 2Hy + 2Iz from the provided points. * //from w ww. j a v a2s. co m * @param points * the points that will be fit to the polynomial expression. * @return the solution vector to the polynomial expression. */ private RealVector solveSystem(ArrayList<ThreeSpacePoint> points) { // determine the number of points int numPoints = points.size(); // the design matrix // size: numPoints x 9 RealMatrix d = new Array2DRowRealMatrix(numPoints, 9); // Fit the ellipsoid in the form of // Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz for (int i = 0; i < d.getRowDimension(); i++) { double xx = Math.pow(points.get(i).x, 2); double yy = Math.pow(points.get(i).y, 2); double zz = Math.pow(points.get(i).z, 2); double xy = 2 * (points.get(i).x * points.get(i).y); double xz = 2 * (points.get(i).x * points.get(i).z); double yz = 2 * (points.get(i).y * points.get(i).z); double x = 2 * points.get(i).x; double y = 2 * points.get(i).y; double z = 2 * points.get(i).z; d.setEntry(i, 0, xx); d.setEntry(i, 1, yy); d.setEntry(i, 2, zz); d.setEntry(i, 3, xy); d.setEntry(i, 4, xz); d.setEntry(i, 5, yz); d.setEntry(i, 6, x); d.setEntry(i, 7, y); d.setEntry(i, 8, z); } // solve the normal system of equations // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); // Multiply: d' * d RealMatrix dtd = d.transpose().multiply(d); // Create a vector of ones. RealVector ones = new ArrayRealVector(numPoints); ones.mapAddToSelf(1); // Multiply: d' * ones.mapAddToSelf(1) RealVector dtOnes = d.transpose().operate(ones); // Find ( d' * d )^-1 DecompositionSolver solver = new SingularValueDecomposition(dtd).getSolver(); RealMatrix dtdi = solver.getInverse(); // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); RealVector v = dtdi.operate(dtOnes); return v; }
From source file:interpolacao.Interpolacao.java
public Interpolacao() { UnivariateFunction polinomio = interpolador.interpolate(x, y);//sera excluido int n = (int) Math.abs((StatUtils.max(x) - Math.abs(StatUtils.min(x))) * 10);//numero de elementos double[] xc = new double[n]; double[] yc = new double[n]; double[] yc2 = new double[n]; double xi = StatUtils.min(x);//valor inicial for (int i = 0; i < h.length; i++)//calculo de h {/*from ww w . j a v a 2 s. com*/ h[i] = x[i + 1] - x[i]; } for (int i = 0; i < h.length - 1; i++) { //criacao da matriz A para clculo de G (sistema linear for (int j = 1; j < h.length; j++) { // pular primeira e ultima colunas if (i == j) { matrizA[i][j - 1] = h[i]; } else { if (j == i + 1) { matrizA[i][j - 1] = 2 * (h[i] + h[i + 1]); } else { if (j == i + 2) { matrizA[i][j - 1] = h[i + 1]; } else { matrizA[i][j - 1] = 0; } } } System.out.print(matrizA[i][j - 1] + " ");// imprime matrizA criada } System.out.println(""); } //fim criacao matriz A for (int i = 0; i < vetorB.length; i++) { double auxY1 = y[i + 1] - y[i]; double auxY2 = y[i + 2] - y[i + 1]; double auxH1 = ((x[i + 1] - x[i])); double auxH2 = ((x[i + 2] - x[i + 1])); vetorB[i] = 6 * ((auxY2 / auxH2) - (auxY1 / auxH1)); System.out.print(vetorB[i] + " ");// imprime vetorB criada } RealMatrix coefficients = new Array2DRowRealMatrix(matrizA, false); DecompositionSolver solver = new LUDecomposition(coefficients).getSolver(); RealVector constants = new ArrayRealVector(vetorB, false); RealVector solution = solver.solve(constants); g[0] = 0; for (int k = 1; k < g.length - 2; k++) { g[k] = solution.getEntry(k - 1); } g[g.length - 1] = 0; for (int t = 0; t < x.length - 1; t++) { d[t] = y[t]; c[t] = ((y[t + 1] - y[t]) / h[t]) + (((2 * h[t] * g[t + 1]) + (g[t + 0] * h[t])) / 6); b[t] = g[t + 1] / 2; // talvez seja g[t+1] <----- a[t] = (g[t + 1] - g[t + 0]) / (6 * h[t]); } double step = (StatUtils.max(x) - StatUtils.min(x)) / n; int auxPos = 0; double x_val = x[0]; for (int i = 0; i < xc.length; i++) { while (x_val >= x[auxPos + 1]) { FuncaoS(x[auxPos + 1], auxPos); auxPos++; } xc[i] = x_val; yc[i] = FuncaoS(xc[i], auxPos); yc2[i] = polinomio.value(xc[i]); x_val = (step * i) + x[0]; } plot.addLegend("SOUTH"); plot.addScatterPlot("Pontos", x, y); plot.addLinePlot("Spline", xc, yc); JFrame frame = new JFrame("Spline"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 500); frame.add(plot, BorderLayout.CENTER); frame.setVisible(true); Plot2DPanel plot2 = new Plot2DPanel(); plot2.addLegend("SOUTH"); plot2.addScatterPlot("Pontos", x, y); plot2.addLinePlot("Spline", xc, yc2); JFrame frame2 = new JFrame("SplineComp"); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setSize(600, 500); frame2.add(plot2, BorderLayout.CENTER); frame2.setVisible(true); }
From source file:edu.cmu.sphinx.speakerid.SpeakerCluster.java
public void mergeWith(SpeakerCluster target) throws NullPointerException { if (target == null) throw new NullPointerException(); Iterator<Segment> it = target.segmentSet.iterator(); while (it.hasNext()) { if (!this.addSegment(it.next())) System.out.println("Something doesn't work in mergeWith method, Cluster class"); }//w w w.ja v a 2s . co m int rowDim = featureMatrix.getRowDimension() + target.getFeatureMatrix().getRowDimension(); int colDim = featureMatrix.getColumnDimension(); Array2DRowRealMatrix combinedFeatures = new Array2DRowRealMatrix(rowDim, colDim); combinedFeatures.setSubMatrix(featureMatrix.getData(), 0, 0); combinedFeatures.setSubMatrix(target.getFeatureMatrix().getData(), featureMatrix.getRowDimension(), 0); bicValue = SpeakerIdentification.getBICValue(combinedFeatures); featureMatrix = new Array2DRowRealMatrix(combinedFeatures.getData()); }
From source file:com.clust4j.algo.preprocess.BoxCoxTransformer.java
/** * Inverse transform your matrix. Note: this suffers some * accuracy issues due to the log base//from w ww .j a va 2s. c o m */ @Override public RealMatrix inverseTransform(RealMatrix X) { checkFit(); final int m = X.getRowDimension(); final int n = X.getColumnDimension(); if (n != shift.length) throw new DimensionMismatchException(n, shift.length); double[][] x = X.getData(); for (int j = 0; j < n; j++) { double lam = lambdas[j]; double ool = 1.0 / lam; for (int i = 0; i < m; i++) { // If the lambda is near zero, exp to reverse the log: if (lam < zero) { x[i][j] = FastMath.exp(x[i][j]); } else { x[i][j] *= lam; x[i][j] += 1; x[i][j] = FastMath.pow(x[i][j], ool); } // Add back the shift value: x[i][j] += shift[j]; } } // Implicit copy in the getData() return new Array2DRowRealMatrix(x, false); }
From source file:com.cloudera.oryx.common.math.MatrixUtils.java
/** * @param M tall, skinny matrix//from w w w.j a va 2 s. co m * @return MT * M as a dense matrix */ public static RealMatrix transposeTimesSelf(LongObjectMap<float[]> M) { if (M == null || M.isEmpty()) { return null; } RealMatrix result = null; for (LongObjectMap.MapEntry<float[]> entry : M.entrySet()) { float[] vector = entry.getValue(); int dimension = vector.length; if (result == null) { result = new Array2DRowRealMatrix(dimension, dimension); } for (int row = 0; row < dimension; row++) { float rowValue = vector[row]; for (int col = 0; col < dimension; col++) { result.addToEntry(row, col, rowValue * vector[col]); } } } Preconditions.checkNotNull(result); return result; }
From source file:edu.stanford.cfuller.imageanalysistools.clustering.GaussianLikelihoodObjectiveFunction.java
/** * Evaluates the function with the specified parameters. * * The parameters describe a set of gaussian generators (which are the Clusters). * * @param parameters A RealVector containing the values of all the parameters of each Gaussian, ordered so that all the parameters of a single gaussian are together, then the next gaussian, etc. * @return The negative log likelihood of having observed the ClusterObjects at their locations, given the parameters describing the Gaussian clusters. *//*from w w w . ja va 2s.c o m*/ public double evaluate(RealVector parameters) { int nClusters = parameters.getDimension() / nParametersEach; //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("nClusters: " + nClusters + " abdMatrices_size: " + abdMatrices.size() + " det_dim: " + det.getDimension()); if (det.getDimension() != nClusters) { clusterProbs = new Array2DRowRealMatrix(this.objects.size(), nClusters); det = new ArrayRealVector(nClusters); pk = new ArrayRealVector(nClusters); if (abdMatrices.size() < nClusters) { int originalSize = abdMatrices.size(); for (int i = 0; i < nClusters - originalSize; i++) { abdMatrices.add(new Array2DRowRealMatrix(numDim, numDim)); } } else { abdMatrices.setSize(nClusters); } } pk.mapMultiplyToSelf(0.0); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("nClusters: " + nClusters + " abdMatrices_size: " + abdMatrices.size() + " det_dim: " + det.getDimension()); for (int i = 0; i < nClusters; i++) { /* double ct = Math.cos(parameters.getEntry(nParametersEach*i+3)); double st = Math.sin(parameters.getEntry(nParametersEach*i+3)); double sin2t = Math.sin(2*parameters.getEntry(nParametersEach*i+3)); double a = (ct*ct/(2*parameters.getEntry(nParametersEach*i+2)) + st*st/(2*parameters.getEntry(nParametersEach*i+4))); double b = (sin2t/(4*parameters.getEntry(nParametersEach*i+4)) - sin2t/(4*parameters.getEntry(nParametersEach*i+2))); double d = (st*st/(2*parameters.getEntry(nParametersEach*i+2)) + ct*ct/(2*parameters.getEntry(nParametersEach*i+4))); */ double a = parameters.getEntry(nParametersEach * i + 2); double d = parameters.getEntry(nParametersEach * i + 4); double b = Math.sqrt(a * d) * parameters.getEntry(nParametersEach * i + 3); abdMatrices.get(i).setEntry(0, 0, a); abdMatrices.get(i).setEntry(1, 0, b); abdMatrices.get(i).setEntry(0, 1, b); abdMatrices.get(i).setEntry(1, 1, d); LUDecomposition abdLU = (new LUDecomposition(abdMatrices.get(i))); det.setEntry(i, (abdLU).getDeterminant()); //det.setEntry(i, a*d-b*b); try { abdMatrices.set(i, abdLU.getSolver().getInverse()); } catch (org.apache.commons.math3.linear.SingularMatrixException e) { return Double.MAX_VALUE; } } for (int n = 0; n < this.objects.size(); n++) { ClusterObject c = this.objects.get(n); double max = -1.0 * Double.MAX_VALUE; int maxIndex = 0; for (int k = 0; k < nClusters; k++) { mean.setEntry(0, c.getCentroid().getX() - parameters.getEntry(nParametersEach * k)); mean.setEntry(1, c.getCentroid().getY() - parameters.getEntry(nParametersEach * k + 1)); x = abdMatrices.get(k).operate(mean); double dot = x.dotProduct(mean); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("k, n: " + k + ", " + this.objects.size()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("parameters: " + parameters.toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("abd matrix: " + abdMatrices.get(k).toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("det: " + det.getEntry(k)); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("mean: " + mean.toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("dot: " + dot); double logN = negLog2PI - 0.5 * Math.log(det.getEntry(k)) - 0.5 * dot; // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("logN: " + logN); clusterProbs.setEntry(n, k, logN); if (logN > max) { max = logN; maxIndex = k; } if (Double.isInfinite(logN) || Double.isNaN(logN)) { return Double.MAX_VALUE; } } c.setMostProbableCluster(maxIndex); } for (int k = 0; k < nClusters; k++) { double tempMax = -1.0 * Double.MAX_VALUE; for (int n = 0; n < this.objects.size(); n++) { if (clusterProbs.getEntry(n, k) > tempMax) tempMax = clusterProbs.getEntry(n, k); } pk.setEntry(k, tempMax + Math.log( clusterProbs.getColumnVector(k).mapSubtract(tempMax).mapToSelf(new Exp()).getL1Norm()) - Math.log(this.objects.size())); } double pkMax = -1.0 * Double.MAX_VALUE; for (int k = 0; k < nClusters; k++) { if (pk.getEntry(k) > pkMax) pkMax = pk.getEntry(k); } double logSumPk = pkMax + Math.log(pk.mapSubtract(pkMax).mapToSelf(new Exp()).getL1Norm()); pk.mapSubtractToSelf(logSumPk); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("pk: " + pk.toString()); double L = 0; for (int n = 0; n < this.objects.size(); n++) { RealVector toSum = clusterProbs.getRowVector(n).add(pk); double tempMax = -1.0 * Double.MAX_VALUE; for (int k = 0; k < nClusters; k++) { if (toSum.getEntry(k) > tempMax) tempMax = toSum.getEntry(k); } double pn = tempMax + Math.log(toSum.mapSubtract(tempMax).mapToSelf(new Exp()).getL1Norm()); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("pn: " + pn); L += pn; } return -1.0 * L; }
From source file:com.clust4j.algo.ClustTests.java
static Array2DRowRealMatrix toMat(double[][] d) { return new Array2DRowRealMatrix(d, true); }
From source file:com.clust4j.data.DataSet.java
public DataSet(double[][] data, int[] labels, String[] headers, MatrixFormatter formatter) { this(new Array2DRowRealMatrix(data, true), labels, headers, formatter, false); }