List of usage examples for org.apache.commons.math3.linear RealMatrix getRowDimension
int getRowDimension();
From source file:org.rhwlab.variationalbayesian.SuperVoxelGaussianMixture.java
public void reportMatrix(PrintStream str, String name, RealMatrix mat) { str.printf("%s\n", name); for (int r = 0; r < mat.getRowDimension(); ++r) { for (int c = 0; c < mat.getColumnDimension(); ++c) { str.printf(" %f", mat.getEntry(r, c)); }/*from w ww . j a v a 2 s . co m*/ str.println(); } }
From source file:org.ssascaling.model.timeseries.learner.apache.QRDecomposition.java
/** * Calculates the QR-decomposition of the given matrix. * * @param matrix The matrix to decompose. * @param threshold Singularity threshold. *//* w w w . j ava 2 s. co m*/ public QRDecomposition(RealMatrix matrix, double threshold) { this.threshold = threshold; final int m = matrix.getRowDimension(); final int n = matrix.getColumnDimension(); qrt = matrix.transpose().getData(); rDiag = new double[FastMath.min(m, n)]; cachedQ = null; cachedQT = null; cachedR = null; cachedH = null; /* * The QR decomposition of a matrix A is calculated using Householder * reflectors by repeating the following operations to each minor * A(minor,minor) of A: */ for (int minor = 0; minor < FastMath.min(m, n); minor++) { final double[] qrtMinor = qrt[minor]; /* * Let x be the first column of the minor, and a^2 = |x|^2. * x will be in the positions qr[minor][minor] through qr[m][minor]. * The first column of the transformed minor will be (a,0,0,..)' * The sign of a is chosen to be opposite to the sign of the first * component of x. Let's find a: */ double xNormSqr = 0; for (int row = minor; row < m; row++) { final double c = qrtMinor[row]; xNormSqr += c * c; } final double a = (qrtMinor[minor] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); rDiag[minor] = a; if (a != 0.0) { /* * Calculate the normalized reflection vector v and transform * the first column. We know the norm of v beforehand: v = x-ae * so |v|^2 = <x-ae,x-ae> = <x,x>-2a<x,e>+a^2<e,e> = * a^2+a^2-2a<x,e> = 2a*(a - <x,e>). * Here <x, e> is now qr[minor][minor]. * v = x-ae is stored in the column at qr: */ qrtMinor[minor] -= a; // now |v|^2 = -2a*(qr[minor][minor]) /* * Transform the rest of the columns of the minor: * They will be transformed by the matrix H = I-2vv'/|v|^2. * If x is a column vector of the minor, then * Hx = (I-2vv'/|v|^2)x = x-2vv'x/|v|^2 = x - 2<x,v>/|v|^2 v. * Therefore the transformation is easily calculated by * subtracting the column vector (2<x,v>/|v|^2)v from x. * * Let 2<x,v>/|v|^2 = alpha. From above we have * |v|^2 = -2a*(qr[minor][minor]), so * alpha = -<x,v>/(a*qr[minor][minor]) */ for (int col = minor + 1; col < n; col++) { final double[] qrtCol = qrt[col]; double alpha = 0; for (int row = minor; row < m; row++) { alpha -= qrtCol[row] * qrtMinor[row]; } alpha /= a * qrtMinor[minor]; // Subtract the column vector alpha*v from x. for (int row = minor; row < m; row++) { qrtCol[row] -= alpha * qrtMinor[row]; } } } } }
From source file:org.ujmp.commonsmath.AbstractCommonsMathDenseDoubleMatrix2D.java
public AbstractCommonsMathDenseDoubleMatrix2D(RealMatrix matrix) { super(matrix.getRowDimension(), matrix.getColumnDimension()); this.matrix = matrix; }
From source file:pl.matrix.core.MatrixCalculator.java
public Matrix transformToTriangularUpperMatrix(Matrix a) throws Exception { RealMatrix aRealMatrix = a.toRealMatrix(); if (aRealMatrix.getRowDimension() != aRealMatrix.getColumnDimension()) { throw new Exception(); }/* w ww. j a va 2 s. c o m*/ int n = aRealMatrix.getRowDimension(); // iteracja (zerowanie i-tej kolumny) for (int i = 0; i < n - 1; i++) { // po wierszach for (int j = i + 1; j < n; j++) { double factor = aRealMatrix.getEntry(j, i) / aRealMatrix.getEntry(i, i); // po kolumnach for (int k = i; k < n; k++) { double newValue = aRealMatrix.getEntry(j, k) - factor * aRealMatrix.getEntry(i, k); aRealMatrix.setEntry(j, k, newValue); } } } Matrix result = new Matrix(aRealMatrix); return result; }
From source file:playground.sergioo.facilitiesGenerator2012.WorkFacilitiesGeneration.java
private static Set<PointPerson> getPCATransformation(Collection<PointPerson> points) { RealMatrix pointsM = new Array2DRowRealMatrix(points.iterator().next().getDimension(), points.size()); int k = 0;//from ww w . ja v a 2 s .co m for (PointND<Double> point : points) { for (int f = 0; f < point.getDimension(); f++) pointsM.setEntry(f, k, point.getElement(f)); k++; } RealMatrix means = new Array2DRowRealMatrix(pointsM.getRowDimension(), 1); for (int r = 0; r < means.getRowDimension(); r++) { double mean = 0; for (int c = 0; c < pointsM.getColumnDimension(); c++) mean += pointsM.getEntry(r, c) / pointsM.getColumnDimension(); means.setEntry(r, 0, mean); } RealMatrix deviations = new Array2DRowRealMatrix(pointsM.getRowDimension(), pointsM.getColumnDimension()); for (int r = 0; r < deviations.getRowDimension(); r++) for (int c = 0; c < deviations.getColumnDimension(); c++) deviations.setEntry(r, c, pointsM.getEntry(r, c) - means.getEntry(r, 0)); RealMatrix covariance = deviations.multiply(deviations.transpose()) .scalarMultiply(1 / (double) pointsM.getColumnDimension()); EigenDecomposition eigenDecomposition = new EigenDecomposition(covariance, 0); RealMatrix eigenVectorsT = eigenDecomposition.getVT(); RealVector eigenValues = new ArrayRealVector(eigenDecomposition.getD().getRowDimension()); for (int r = 0; r < eigenDecomposition.getD().getRowDimension(); r++) eigenValues.setEntry(r, eigenDecomposition.getD().getEntry(r, r)); for (int i = 0; i < eigenValues.getDimension(); i++) { for (int j = i + 1; j < eigenValues.getDimension(); j++) if (eigenValues.getEntry(i) < eigenValues.getEntry(j)) { double tempValue = eigenValues.getEntry(i); eigenValues.setEntry(i, eigenValues.getEntry(j)); eigenValues.setEntry(j, tempValue); RealVector tempVector = eigenVectorsT.getRowVector(i); eigenVectorsT.setRowVector(i, eigenVectorsT.getRowVector(j)); eigenVectorsT.setRowVector(j, tempVector); } eigenVectorsT.setRowVector(i, eigenVectorsT.getRowVector(i).mapMultiply(Math.sqrt(1 / eigenValues.getEntry(i)))); } RealVector standardDeviations = new ArrayRealVector(pointsM.getRowDimension()); for (int r = 0; r < covariance.getRowDimension(); r++) standardDeviations.setEntry(r, Math.sqrt(covariance.getEntry(r, r))); double zValue = standardDeviations.dotProduct(new ArrayRealVector(pointsM.getRowDimension(), 1)); RealMatrix zScore = deviations.scalarMultiply(1 / zValue); pointsM = eigenVectorsT.multiply(zScore); Set<PointPerson> pointsC = new HashSet<PointPerson>(); k = 0; for (PointPerson point : points) { PointPerson pointC = new PointPerson(point.getId(), point.getOccupation(), new Double[] { pointsM.getEntry(0, k), pointsM.getEntry(1, k) }, point.getPlaceType()); pointC.setWeight(point.getWeight()); pointsC.add(pointC); k++; } return pointsC; }
From source file:plugins.SURFPixelMatching.java
private void run() { try {/*from ww w . ja v a 2 s.com*/ // variables int a, b, c, i, j, k, n, r; int row, col; int progress, oldProgress; double x, y, z, newX, newY; double x2, y2; double north, south, east, west; double newNorth, newSouth, newEast, newWest; double rightNodata; double leftNodata; Object[] rowData; whitebox.geospatialfiles.shapefile.Point outputPoint; ShapeFile rightTiePoints; ShapeFile leftTiePoints; ShapeFile rightFiducials; ShapeFile leftFiducials; XYPoint xyPoint; ArrayList<XYPoint> leftTiePointsList = new ArrayList<>(); ArrayList<XYPoint> rightTiePointsList = new ArrayList<>(); float balanceValue = 0.81f; float threshold = 0.004f; int octaves = 4; double maxAllowableRMSE = 1.0; double matchingThreshold = 0.6; // left image //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus_C6430-74072-L9_253_Blue_clipped.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-82_Blue.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253 epipolar.dep"; String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-82_Blue low res.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp1.dep"; // right image //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus_C6430-74072-L9_254_Blue_clipped.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-83_Blue.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 254.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 254 epipolar.dep"; String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-83_Blue low res.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253.dep"; String leftOutputHeader = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp4.shp"; String rightOutputHeader = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp4_2.shp"; DBFField[] fields = new DBFField[5]; fields[0] = new DBFField(); fields[0].setName("FID"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setDecimalCount(4); fields[0].setFieldLength(10); fields[1] = new DBFField(); fields[1].setName("ORIENT"); fields[1].setDataType(DBFField.DBFDataType.NUMERIC); fields[1].setDecimalCount(4); fields[1].setFieldLength(10); fields[2] = new DBFField(); fields[2].setName("SCALE"); fields[2].setDataType(DBFField.DBFDataType.NUMERIC); fields[2].setDecimalCount(4); fields[2].setFieldLength(10); fields[3] = new DBFField(); fields[3].setName("LAPLAC"); fields[3].setDataType(DBFField.DBFDataType.NUMERIC); fields[3].setDecimalCount(4); fields[3].setFieldLength(10); fields[4] = new DBFField(); fields[4].setName("RESID"); fields[4].setDataType(DBFField.DBFDataType.NUMERIC); fields[4].setDecimalCount(4); fields[4].setFieldLength(10); // read the input data WhiteboxRaster leftImage = new WhiteboxRaster(leftImageName, "r"); // leftImage.setForceAllDataInMemory(true); int nRowsLeft = leftImage.getNumberRows(); int nColsLeft = leftImage.getNumberColumns(); leftNodata = leftImage.getNoDataValue(); WhiteboxRaster rightImage = new WhiteboxRaster(rightImageName, "r"); //rightImage.setForceAllDataInMemory(true); // int nRowsRight = rightImage.getNumberRows(); // int nColsRight = rightImage.getNumberColumns(); rightNodata = rightImage.getNoDataValue(); // ArrayList<InterestPoint> interest_points; // double threshold = 600; // double balanceValue = 0.9; // int octaves = 4; // ISURFfactory mySURF = SURF.createInstance(leftImage, balanceValue, threshold, octaves); // IDetector detector = mySURF.createDetector(); // interest_points = detector.generateInterestPoints(); // System.out.println("Interest points generated"); // IDescriptor descriptor = mySURF.createDescriptor(interest_points); // descriptor.generateAllDescriptors(); System.out.println("Performing SURF analysis on left image..."); Surf leftSurf = new Surf(leftImage, balanceValue, threshold, octaves); // if (leftSurf.getNumberOfPoints() > 500000) { // System.out.println("Number of points exceeds limit, reset threshold: " + leftSurf.getNumberOfPoints()); // return; // } if (leftSurf.getNumberOfPoints() == 0) { System.out .println("Number of points equals zero, reset threshold: " + leftSurf.getNumberOfPoints()); return; } System.out.println("Performing SURF analysis on right image..."); Surf rightSurf = new Surf(rightImage, balanceValue, threshold, octaves); if (rightSurf.getNumberOfPoints() == 0) { System.out .println("Number of points equals zero, reset threshold: " + leftSurf.getNumberOfPoints()); return; } System.out.println("Matching points of interest..."); Map<SURFInterestPoint, SURFInterestPoint> matchingPoints = leftSurf.getMatchingPoints(rightSurf, matchingThreshold, false); int numTiePoints = matchingPoints.size(); if (numTiePoints < 3) { System.err.println( "The number of potential tie points is less than 3. Adjust your threshold parameters and retry."); return; } System.out.println(numTiePoints + " potential tie points located"); System.out.println("Trimming outlier tie points..."); boolean flag; do { flag = false; leftTiePointsList.clear(); rightTiePointsList.clear(); i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { x = point.getX(); y = point.getY(); SURFInterestPoint target = matchingPoints.get(point); x2 = target.getX(); y2 = target.getY(); leftTiePointsList.add(new XYPoint(x, y)); rightTiePointsList.add(new XYPoint(x2, y2)); i++; } PolynomialLeastSquares2DFitting overallFit = new PolynomialLeastSquares2DFitting(leftTiePointsList, rightTiePointsList, 1); double maxDist = 0; SURFInterestPoint mostInfluentialPoint = null; i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { leftTiePointsList.clear(); rightTiePointsList.clear(); for (SURFInterestPoint point2 : matchingPoints.keySet()) { if (point2 != point) { x = point2.getX(); y = point2.getY(); SURFInterestPoint target = matchingPoints.get(point2); x2 = target.getX(); y2 = target.getY(); leftTiePointsList.add(new XYPoint(x, y)); rightTiePointsList.add(new XYPoint(x2, y2)); } } PolynomialLeastSquares2DFitting newFit = new PolynomialLeastSquares2DFitting(leftTiePointsList, rightTiePointsList, 1); x = point.getX(); y = point.getY(); XYPoint pt1 = overallFit.getForwardCoordinates(x, y); XYPoint pt2 = newFit.getForwardCoordinates(x, y); double dist = pt1.getSquareDistance(pt2); if (dist > maxDist) { maxDist = dist; mostInfluentialPoint = point; } } if (maxDist > 10 && mostInfluentialPoint != null) { matchingPoints.remove(mostInfluentialPoint); flag = true; } System.out.println(maxDist); } while (flag); int numPoints = matchingPoints.size(); // create homogeneous points matrices double[][] leftPoints = new double[3][numPoints]; double[][] rightPoints = new double[3][numPoints]; i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { leftPoints[0][i] = point.getX(); leftPoints[1][i] = point.getY(); leftPoints[2][i] = 1; SURFInterestPoint target = matchingPoints.get(point); rightPoints[0][i] = target.getX(); rightPoints[1][i] = target.getY(); rightPoints[2][i] = 1; i++; } double[][] normalizedLeftPoints = Normalize2DHomogeneousPoints.normalize(leftPoints); RealMatrix Tl = MatrixUtils.createRealMatrix(Normalize2DHomogeneousPoints.T); double[][] normalizedRightPoints = Normalize2DHomogeneousPoints.normalize(rightPoints); RealMatrix Tr = MatrixUtils.createRealMatrix(Normalize2DHomogeneousPoints.T); RealMatrix pnts1 = MatrixUtils.createRealMatrix(normalizedLeftPoints); RealMatrix pnts2 = MatrixUtils.createRealMatrix(normalizedRightPoints); RealMatrix A = MatrixUtils.createRealMatrix(buildA(normalizedLeftPoints, normalizedRightPoints)); //RealMatrix ata = A.transpose().multiply(A); SingularValueDecomposition svd = new SingularValueDecomposition(A); RealMatrix V = svd.getV(); RealVector V_smallestSingularValue = V.getColumnVector(8); RealMatrix F = MatrixUtils.createRealMatrix(3, 3); for (i = 0; i < 9; i++) { F.setEntry(i / 3, i % 3, V_smallestSingularValue.getEntry(i)); } for (i = 0; i < V.getRowDimension(); i++) { System.out.println(V.getRowVector(i).toString()); } SingularValueDecomposition svd2 = new SingularValueDecomposition(F); RealMatrix U = svd2.getU(); RealMatrix S = svd2.getS(); V = svd2.getV(); RealMatrix m = MatrixUtils.createRealMatrix( new double[][] { { S.getEntry(1, 1), 0, 0 }, { 0, S.getEntry(2, 2), 0 }, { 0, 0, 0 } }); F = U.multiply(m).multiply(V).transpose(); // Denormalise F = Tr.transpose().multiply(F).multiply(Tl); for (i = 0; i < F.getRowDimension(); i++) { System.out.println(F.getRowVector(i).toString()); } svd2 = new SingularValueDecomposition(F); //[U,D,V] = svd(F,0); RealMatrix e1 = svd2.getV().getColumnMatrix(2); //hnormalise(svd2.getV(:,3)); RealMatrix e2 = svd2.getU().getColumnMatrix(2); //e2 = hnormalise(U(:,3)); e1.setEntry(0, 0, (e1.getEntry(0, 0) / e1.getEntry(2, 0))); e1.setEntry(1, 0, (e1.getEntry(1, 0) / e1.getEntry(2, 0))); e1.setEntry(2, 0, 1); e2.setEntry(0, 0, (e2.getEntry(0, 0) / e2.getEntry(2, 0))); e2.setEntry(1, 0, (e2.getEntry(1, 0) / e2.getEntry(2, 0))); e2.setEntry(2, 0, 1); System.out.println(""); // boolean[] removeTiePoint = new boolean[numTiePoints]; // double[] residuals = null; // double[] residualsOrientation = null; // boolean flag; // do { // // perform the initial tie point transformation // leftTiePointsList.clear(); // rightTiePointsList.clear(); // int numPointsIncluded = 0; // i = 0; // for (SURFInterestPoint point : matchingPoints.keySet()) { // if (i < numTiePoints && !removeTiePoint[i]) { // x = point.getX(); // y = point.getY(); // // SURFInterestPoint target = matchingPoints.get(point); // x2 = target.getX(); // y2 = target.getY(); // // leftTiePointsList.add(new XYPoint(x, y)); // rightTiePointsList.add(new XYPoint(x2, y2)); // // numPointsIncluded++; // } // i++; // } // // PolynomialLeastSquares2DFitting plsFit = new PolynomialLeastSquares2DFitting( // leftTiePointsList, rightTiePointsList, 1); // // double rmse = plsFit.getOverallRMSE(); // System.out.println("RMSE: " + rmse + " with " + numPointsIncluded + " points included."); // // flag = false; // residuals = plsFit.getResidualsXY(); // residualsOrientation = plsFit.getResidualsOrientation(); // if (rmse > maxAllowableRMSE) { // i = 0; // for (k = 0; k < numTiePoints; k++) { // if (!removeTiePoint[k]) { // if (residuals[i] > 3 * rmse) { // removeTiePoint[k] = true; // flag = true; // } // i++; // } // } // } // } while (flag); // // i = 0; // for (k = 0; k < numTiePoints; k++) { // if (!removeTiePoint[k]) { // i++; // } // } System.out.println(numPoints + " tie points remain."); System.out.println("Outputing tie point files..."); ShapeFile leftOutput = new ShapeFile(leftOutputHeader, ShapeType.POINT, fields); ShapeFile rightOutput = new ShapeFile(rightOutputHeader, ShapeType.POINT, fields); i = 0; k = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { // if (i < numTiePoints && !removeTiePoint[i]) { x = leftImage.getXCoordinateFromColumn((int) point.getX()); y = leftImage.getYCoordinateFromRow((int) point.getY()); SURFInterestPoint target = matchingPoints.get(point); x2 = rightImage.getXCoordinateFromColumn((int) target.getX()); y2 = rightImage.getYCoordinateFromRow((int) target.getY()); outputPoint = new whitebox.geospatialfiles.shapefile.Point(x, y); rowData = new Object[5]; rowData[0] = new Double(k + 1); rowData[1] = new Double(point.getOrientation()); rowData[2] = new Double(point.getScale()); rowData[3] = new Double(point.getLaplacian()); rowData[4] = new Double(0); //residuals[k]); leftOutput.addRecord(outputPoint, rowData); outputPoint = new whitebox.geospatialfiles.shapefile.Point(x2, y2); rowData = new Object[5]; rowData[0] = new Double(k + 1); rowData[1] = new Double(target.getOrientation()); rowData[2] = new Double(target.getScale()); rowData[3] = new Double(target.getLaplacian()); rowData[4] = new Double(0); //residuals[k]); rightOutput.addRecord(outputPoint, rowData); k++; // } i++; } leftOutput.write(); rightOutput.write(); System.out.println("Done!"); } catch (Exception e) { e.printStackTrace(); } }
From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java
/** * @param m Input matrix//from ww w . j a v a2s .c om * @return Matrix representing the element-wise logarithm of m. */ private static RealMatrix log(final RealMatrix m) { final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()]; for (int r = 0; r < m.getRowDimension(); r++) { for (int c = 0; c < m.getColumnDimension(); c++) { d[r][c] = FastMath.log(m.getEntry(r, c)); } } return new Array2DRowRealMatrix(d, false); }
From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java
/** * @param m Input matrix./*from w w w.ja va 2s .com*/ * @return Matrix representing the element-wise square root of m. */ private static RealMatrix sqrt(final RealMatrix m) { final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()]; for (int r = 0; r < m.getRowDimension(); r++) { for (int c = 0; c < m.getColumnDimension(); c++) { d[r][c] = FastMath.sqrt(m.getEntry(r, c)); } } return new Array2DRowRealMatrix(d, false); }
From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java
/** * @param m Input matrix.// w w w. j a va 2 s . co m * @return Matrix representing the element-wise square of m. */ private static RealMatrix square(final RealMatrix m) { final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()]; for (int r = 0; r < m.getRowDimension(); r++) { for (int c = 0; c < m.getColumnDimension(); c++) { double e = m.getEntry(r, c); d[r][c] = e * e; } } return new Array2DRowRealMatrix(d, false); }
From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java
/** * @param m Input matrix 1.//w w w . j a va2 s. c o m * @param n Input matrix 2. * @return the matrix where the elements of m and n are element-wise multiplied. */ private static RealMatrix times(final RealMatrix m, final RealMatrix n) { final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()]; for (int r = 0; r < m.getRowDimension(); r++) { for (int c = 0; c < m.getColumnDimension(); c++) { d[r][c] = m.getEntry(r, c) * n.getEntry(r, c); } } return new Array2DRowRealMatrix(d, false); }