List of usage examples for org.apache.commons.math3.linear DecompositionSolver solve
RealMatrix solve(final RealMatrix b);
From source file:ch.zhaw.iamp.rct.weights.Weights.java
/** * Calculates a pseudo-inverse using the values in the given files. They are * first read, then converted to a matrix, and finally used for the * calculation of the inverse, using Singular value decomposition (SVD). * * @param pathToA The file which contains the matrix A, represented in * comma-separated-value format.// w ww. j a va 2s .co m * @param targetTrajectoryFile The file which contains the target * trajectory, represented in comma-separated-value format. * @param weightsFile The file, to which the calculated weights should be * written to. * @param offset The numbers of first steps to ignore (to skip fading-memory * initialization steps). */ public static void calculateWeights(final String pathToA, final String targetTrajectoryFile, final String weightsFile, final int offset) { try { RealMatrix A = csvToMatrix(pathToA); // cut first n elements A = A.getSubMatrix(offset, A.getRowDimension() - 1, 0, A.getColumnDimension() - 1); A = addNoise(A); RealMatrix b = csvToMatrix(targetTrajectoryFile); // adjust b to cutting int n = offset % b.getRowDimension(); if (n > 0) { RealMatrix tmp = b.getSubMatrix(n, b.getRowDimension() - 1, 0, b.getColumnDimension() - 1); b = b.getSubMatrix(0, n - 1, 0, b.getColumnDimension() - 1); double[][] tmpArray = tmp.getData(); double[][] tmpArray2 = b.getData(); b = MatrixUtils.createRealMatrix(concat(tmpArray, tmpArray2)); tmpArray = b.getData(); for (int i = 0; tmpArray.length < A.getRowDimension(); ++i) { tmpArray2 = new double[1][tmpArray[0].length]; for (int j = 0; j < tmpArray[i].length; ++j) { tmpArray2[0][j] = tmpArray[i][j]; } tmpArray = concat(tmpArray, tmpArray2); } b = MatrixUtils.createRealMatrix(tmpArray); } DecompositionSolver solver = new SingularValueDecomposition(A).getSolver(); RealMatrix x = solver.solve(b).transpose(); matrixToCsv(x, weightsFile); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Could not read a file: " + ex.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "Could not read a file: {0}", ex); } catch (DimensionMismatchException ex) { JOptionPane.showMessageDialog(null, "<html>Could not calculate the " + "pseudo-inverse since a dimension mismatch occurred.<br />" + "Please make sure that all lines of the CSV file posses " + "the same amount of entries.<br />Hint: Remove the last " + "line and try it again.</html>", "Matrix Dimension Mismatch", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "A dimension mismatch occurred: {0}", ex); } }
From source file:com.ibm.bi.dml.runtime.matrix.data.LibCommonsMath.java
/** * Function to solve a given system of equations. * /*from w ww. ja v a 2 s . c om*/ * @param in1 * @param in2 * @return * @throws DMLRuntimeException */ private static MatrixBlock computeSolve(MatrixObject in1, MatrixObject in2) throws DMLRuntimeException { Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in1); Array2DRowRealMatrix vectorInput = DataConverter.convertToArray2DRowRealMatrix(in2); /*LUDecompositionImpl ludecompose = new LUDecompositionImpl(matrixInput); DecompositionSolver lusolver = ludecompose.getSolver(); RealMatrix solutionMatrix = lusolver.solve(vectorInput);*/ // Setup a solver based on QR Decomposition QRDecomposition qrdecompose = new QRDecomposition(matrixInput); DecompositionSolver solver = qrdecompose.getSolver(); // Invoke solve RealMatrix solutionMatrix = solver.solve(vectorInput); MatrixBlock solution = DataConverter.convertToMatrixBlock(solutionMatrix.getData()); return solution; }
From source file:de.thkwalter.et.ortskurve.Startpunktbestimmung.java
/** * Diese Methode berechnet den Startpunkt aus den ersten drei Messpunkten. * // w ww .j a v a 2s .c om * @return Der Startpunkt. Die erste Komponente des Feldes reprsentiert die x-Komponente des Mittelpunktes, die zweite * Komponente die y-Komponente, die dritte Komponente den Radius. */ private static double[] startpunktBestimmen(Vector2D[] messpunkteZurStartpunktbestimmung) { // Die Felder fr die Koeffizientenmatrix und die Inhomogenitt werden definiert. double[][] koeffizienten = new double[3][]; double[] inhomogenitaet = new double[3]; // Einige Hilfsgren werden deklariert. double[] zeile = null; double x = Double.NaN; double y = Double.NaN; // In der folgenden Schleife werden die Koeffizientenmatrix und die Inhomogenitt initialisiert. for (int i = 0; i < 3; i++) { // Die x- und y-Komponente eines Punktes werden gelesen. x = messpunkteZurStartpunktbestimmung[i].getX(); y = messpunkteZurStartpunktbestimmung[i].getY(); // Eine Zeile der Koeffizientenmatrix wird initialisiert zeile = new double[3]; zeile[0] = 1; zeile[1] = -x; zeile[2] = -y; koeffizienten[i] = zeile; // Eine Komponente des Inhomogenittsvektors wird initialisiert. inhomogenitaet[i] = -(x * x + y * y); } // Die Koeffizientenmatrix wird erzeugt. RealMatrix koeffizientenmatrix = new Array2DRowRealMatrix(koeffizienten); // Der Inhomogenittsvektor wird erzeugt. RealVector inhomogenitaetsvektor = new ArrayRealVector(inhomogenitaet, false); // Der Lsungsalgorithmus fr das lineare Gleichungssystem wird erzeugt. DecompositionSolver alorithmus = new LUDecomposition(koeffizientenmatrix).getSolver(); // Das inhomogene Gleichungssystem wird gelst. RealVector loesung = null; try { loesung = alorithmus.solve(inhomogenitaetsvektor); } catch (SingularMatrixException singularMatrixException) { // Die Fehlermeldung fr den Entwickler wird erzeugt und protokolliert. String fehlermeldung = "Die Matrix aus den Punkten " + messpunkteZurStartpunktbestimmung[0] + ", " + messpunkteZurStartpunktbestimmung[1] + " und " + messpunkteZurStartpunktbestimmung[2] + " ist singulr."; Startpunktbestimmung.logger.severe(fehlermeldung); // Die Ausnahme wird erzeugt und mit der Fehlermeldung fr den Benutzer initialisiert. String jsfMeldung = "Eine von den Messpunkten (" + messpunkteZurStartpunktbestimmung[0].getX() + ", " + messpunkteZurStartpunktbestimmung[0].getY() + "), (" + messpunkteZurStartpunktbestimmung[1].getX() + ", " + messpunkteZurStartpunktbestimmung[1].getY() + ") und (" + messpunkteZurStartpunktbestimmung[2].getX() + ", " + messpunkteZurStartpunktbestimmung[2].getY() + ")" + " abhngige Matrix ist singur. Der " + "Berechnungsalgorithmus bentigt jedoch eine regulre Matrix! Entfernen Sie bitte einen der oben " + "angegebenen Messpunkte."; ApplicationRuntimeException applicationRuntimeException = new ApplicationRuntimeException(jsfMeldung); throw applicationRuntimeException; } // Der Startpunkt wird aus der Lsung des linearen Gleichungssystems bestimmt. double xMittelpunkt = 0.5 * loesung.getEntry(1); double yMittelpunkt = 0.5 * loesung.getEntry(2); double radius = Math.sqrt(xMittelpunkt * xMittelpunkt + yMittelpunkt * yMittelpunkt - loesung.getEntry(0)); // Der Startpunkt wird zurckgegeben. return new double[] { xMittelpunkt, yMittelpunkt, radius }; }
From source file:SGFilterModified.java
/** * Computes Savitzky-Golay coefficients for given parameters * //from w w w. j a v a2 s . co m * @param nl * numer of past data points filter will use * @param nr * number of future data points filter will use * @param degree * order of smoothin polynomial * @return Savitzky-Golay coefficients * @throws IllegalArgumentException * if {@code nl < 0} or {@code nr < 0} or {@code nl + nr < * degree} */ public static double[] computeSGCoefficients(int nl, int nr, int degree) { if (nl < 0 || nr < 0 || nl + nr < degree) throw new IllegalArgumentException("Bad arguments"); //create a matrix Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(degree + 1, degree + 1); double[][] a = matrix.getDataRef(); double sum; for (int i = 0; i <= degree; i++) { for (int j = 0; j <= degree; j++) { sum = (i == 0 && j == 0) ? 1 : 0; for (int k = 1; k <= nr; k++) sum += pow(k, i + j); for (int k = 1; k <= nl; k++) sum += pow(-k, i + j); a[i][j] = sum; } } double[] b = new double[degree + 1]; b[0] = 1; // make a vector RealVector bVec = new ArrayRealVector(b); // get LUDecompostion solver DecompositionSolver solver = new LUDecomposition(matrix).getSolver(); // Finally solve matrices bVec = solver.solve(bVec); double[] coeffs = new double[nl + nr + 1]; for (int n = -nl; n <= nr; n++) { sum = bVec.getEntry(0); for (int m = 1; m <= degree; m++) sum += bVec.getEntry(m) * pow(n, m); coeffs[n + nl] = sum; } return coeffs; }
From source file:imagingbook.lib.math.Matrix.java
public static double[] solve(final double[][] A, double[] b) { RealMatrix AA = MatrixUtils.createRealMatrix(A); RealVector bb = MatrixUtils.createRealVector(b); DecompositionSolver solver = new LUDecomposition(AA).getSolver(); double[] x = null; try {//from w w w .j ava 2 s. c o m x = solver.solve(bb).toArray(); } catch (SingularMatrixException e) { } return x; }
From source file:edu.tum.cs.vis.model.util.algorithm.ACCUM.java
/** * Calculate curvature for vertices of triangle * //from w ww. j a va 2s .c o m * @param curvatures * vertex curvature mapping * @param tri * triangle to calculate curvature for */ static void calculateCurvatureForTriangle(HashMap<Vertex, Curvature> curvatures, Triangle tri) { // Edges Vector3f e[] = tri.getEdges(); // N-T-B coordinate system per face Vector3f t = new Vector3f(e[0]); t.normalize(); Vector3f n = new Vector3f(); n.cross(e[0], e[1]); Vector3f b = new Vector3f(); b.cross(n, t); b.normalize(); // Estimate curvature based on variation of normals // along edges float m[] = { 0, 0, 0 }; double w[][] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; for (int j = 0; j < 3; j++) { float u = e[j].dot(t); float v = e[j].dot(b); w[0][0] += u * u; w[0][1] += u * v; // w[1][1] += v*v + u*u; // w[1][2] += u*v; w[2][2] += v * v; Vector3f dn = new Vector3f(tri.getPosition()[(j + 2) % 3].getNormalVector()); dn.sub(tri.getPosition()[(j + 1) % 3].getNormalVector()); float dnu = dn.dot(t); float dnv = dn.dot(b); m[0] += dnu * u; m[1] += dnu * v + dnv * u; m[2] += dnv * v; } w[1][1] = w[0][0] + w[2][2]; w[1][2] = w[0][1]; RealMatrix coefficients = new Array2DRowRealMatrix(w, false); DecompositionSolver solver = new LUDecomposition(coefficients).getSolver(); if (!solver.isNonSingular()) { return; } RealVector constants = new ArrayRealVector(new double[] { m[0], m[1], m[2] }, false); RealVector solution = solver.solve(constants); m[0] = (float) solution.getEntry(0); m[1] = (float) solution.getEntry(1); m[2] = (float) solution.getEntry(2); // Push it back out to the vertices for (int j = 0; j < 3; j++) { Vertex vj = tri.getPosition()[j]; float c1, c12, c2; float ret[] = proj_curv(t, b, m[0], m[1], m[2], curvatures.get(vj).getPrincipleDirectionMax(), curvatures.get(vj).getPrincipleDirectionMin()); c1 = ret[0]; c12 = ret[1]; c2 = ret[2]; Curvature c = curvatures.get(vj); double wt; if (j == 0) wt = tri.getCornerarea().x / vj.getPointarea(); else if (j == 1) wt = tri.getCornerarea().y / vj.getPointarea(); else wt = tri.getCornerarea().z / vj.getPointarea(); synchronized (c) { c.setCurvatureMax((float) (c.getCurvatureMax() + wt * c1)); c.setCurvatureMinMax((float) (c.getCurvatureMinMax() + wt * c12)); c.setCurvatureMin((float) (c.getCurvatureMin() + wt * c2)); } } }
From source file:io.yields.math.concepts.operator.Smoothness.java
private RealMatrix computeDistance(List<Tuple> normalizedData) { RealMatrix a = new Array2DRowRealMatrix(normalizedData.size(), order + 1); RealMatrix b = new Array2DRowRealMatrix(normalizedData.size(), 1); int row = 0;//from w w w .ja va2 s . c o m for (Tuple tuple : normalizedData) { final int currentRow = row; IntStream.rangeClosed(0, order) .forEach(power -> a.setEntry(currentRow, power, Math.pow(tuple.getX(), power))); b.setEntry(currentRow, 0, tuple.getY()); row++; } DecompositionSolver solver = new QRDecomposition(a, EPS).getSolver(); if (solver.isNonSingular() && !isConstant(b)) { RealMatrix solution = solver.solve(b); return a.multiply(solution).subtract(b); } else { return new Array2DRowRealMatrix(normalizedData.size(), 1); } }
From source file:com.github.kingtim1.jmdp.discounted.MatrixInversePolicyEvaluation.java
@Override public DiscountedVFunction<S> eval(StationaryPolicy<S, A> policy) { int n = _smdp.numberOfStates(); List<S> states = new ArrayList<S>(n); Iterable<S> istates = _smdp.states(); for (S state : istates) { states.add(state);// w w w . j a v a2 s . c om } // Construct matrix A and vector b RealMatrix id = MatrixUtils.createRealIdentityMatrix(n); RealMatrix gpp = gammaPPi(policy, states); RealMatrix A = id.subtract(gpp); RealVector b = rPi(policy, states); // Solve for V^{\pi} SingularValueDecomposition decomp = new SingularValueDecomposition(A); DecompositionSolver dsolver = decomp.getSolver(); RealVector vpi = dsolver.solve(b); // Construct the value function Map<S, Double> valueMap = new HashMap<S, Double>(); for (int i = 0; i < states.size(); i++) { S state = states.get(i); double val = vpi.getEntry(i); valueMap.put(state, val); } return new MapVFunction<S>(valueMap, 0); }
From source file:com.gordoni.opal.UtilityJoinSlope.java
public UtilityJoinSlope(Config config, String join_function, Utility utility1, Utility utility2, double c1, double c2) { this.config = config; this.utility1 = utility1; this.utility2 = utility2; this.c1 = c1; this.c2 = c2; if (c1 < c2) { if (join_function.equals("slope-cubic-monotone") || join_function.equals("slope-cubic-smooth")) { RealMatrix a = new Array2DRowRealMatrix( new double[][] { { c1 * c1 * c1, c1 * c1, c1, 1 }, { c2 * c2 * c2, c2 * c2, c2, 1 }, { 3 * c1 * c1, 2 * c1, 1, 0 }, { 3 * c2 * c2, 2 * c2, 1, 0 } }); double s1 = utility1.slope(c1); double s2 = utility2.slope(c2); double s2_1 = utility1.slope2(c1); double s2_2 = utility2.slope2(c2); double secant = (s2 - s1) / (c2 - c1); assert (secant < 0); double alpha = s2_1 / secant; double beta = s2_2 / secant; if (!monotone(alpha, beta)) { assert (!join_function.equals("slope-cubic-smooth")); // Guarantee monotonicity at the cost of a discontinuity in slope2 space. s2_1 = Math.max(s2_1, 3 * secant); // Can do better (see paper), but this is good enough. alpha = s2_1 / secant;//from w ww.j a va 2 s . c om if (!monotone(alpha, beta)) { s2_2 = 3 * secant; beta = s2_2 / secant; } } RealVector b = new ArrayRealVector(new double[] { s1, s2, s2_1, s2_2 }); DecompositionSolver solver = new LUDecomposition(a).getSolver(); RealVector solution = solver.solve(b); this.w = solution.getEntry(0); this.x = solution.getEntry(1); this.y = solution.getEntry(2); this.z = solution.getEntry(3); } else if (join_function.equals("slope-linear")) { this.w = 0; this.x = 0; this.y = (utility2.slope(c2) - utility1.slope(c1)) / (c2 - c1); this.z = utility1.slope(c1) - this.y * c1; } else assert (false); } else { this.w = 0; this.x = 0; this.y = 0; this.z = 0; } this.zero1 = utility(c1) - utility1.utility(c1); this.zero2 = utility2.utility(c2) - utility(c2); this.u1 = utility(c1); this.u2 = utility(c2); set_constants(); }
From source file:com.github.thorbenlindhauer.math.MathUtil.java
public RealMatrix invert() { if (!matrix.isSquare()) { throw new FactorOperationException("Cannot invert non-square matrix"); }//ww w .j a v a 2s . co m ensureLUDecompositionInitialized(); int matrixDimension = matrix.getRowDimension(); RealMatrix inverseMatrix = new Array2DRowRealMatrix(matrixDimension, matrixDimension); RealMatrix identityMatrix = MatrixUtils.createRealIdentityMatrix(matrixDimension); DecompositionSolver solver = luDecomposition.getSolver(); for (int i = 0; i < matrixDimension; i++) { RealVector identityColumn = identityMatrix.getColumnVector(i); RealVector inverseColumn = solver.solve(identityColumn); inverseMatrix.setColumnVector(i, inverseColumn); } return inverseMatrix; }