List of usage examples for org.apache.commons.math3.linear RealVector getEntry
public abstract double getEntry(int index) throws OutOfRangeException;
From source file:com.datumbox.framework.core.machinelearning.featureselection.PCA.java
/** {@inheritDoc} */ @Override/*from w w w.j ava 2 s . co m*/ protected void _fit(Dataframe trainingData) { ModelParameters modelParameters = knowledgeBase.getModelParameters(); int n = trainingData.size(); int d = trainingData.xColumnSize(); //convert data into matrix Map<Object, Integer> featureIds = modelParameters.getFeatureIds(); DataframeMatrix matrixDataset = DataframeMatrix.newInstance(trainingData, false, null, featureIds); RealMatrix X = matrixDataset.getX(); //calculate means and subtract them from data RealVector meanValues = new OpenMapRealVector(d); for (Integer columnId : featureIds.values()) { double mean = 0.0; for (int row = 0; row < n; row++) { mean += X.getEntry(row, columnId); } mean /= n; for (int row = 0; row < n; row++) { X.addToEntry(row, columnId, -mean); } meanValues.setEntry(columnId, mean); } modelParameters.setMean(meanValues); //dxd matrix RealMatrix covarianceDD = (X.transpose().multiply(X)).scalarMultiply(1.0 / (n - 1.0)); EigenDecomposition decomposition = new EigenDecomposition(covarianceDD); RealVector eigenValues = new ArrayRealVector(decomposition.getRealEigenvalues(), false); RealMatrix components = decomposition.getV(); //Whiten Components W = U*L^0.5; To whiten them we multiply with L^0.5. if (knowledgeBase.getTrainingParameters().isWhitened()) { RealMatrix sqrtEigenValues = new DiagonalMatrix(d); for (int i = 0; i < d; i++) { sqrtEigenValues.setEntry(i, i, FastMath.sqrt(eigenValues.getEntry(i))); } components = components.multiply(sqrtEigenValues); } //the eigenvalues and their components are sorted by descending order no need to resort them Integer maxDimensions = knowledgeBase.getTrainingParameters().getMaxDimensions(); Double variancePercentageThreshold = knowledgeBase.getTrainingParameters().getVariancePercentageThreshold(); if (variancePercentageThreshold != null && variancePercentageThreshold <= 1) { double totalVariance = 0.0; for (int i = 0; i < d; i++) { totalVariance += eigenValues.getEntry(i); } double sum = 0.0; int varCounter = 0; for (int i = 0; i < d; i++) { sum += eigenValues.getEntry(i) / totalVariance; varCounter++; if (sum >= variancePercentageThreshold) { break; } } if (maxDimensions == null || maxDimensions > varCounter) { maxDimensions = varCounter; } } if (maxDimensions != null && maxDimensions < d) { //keep only the maximum selected eigenvalues eigenValues = eigenValues.getSubVector(0, maxDimensions); //keep only the maximum selected eigenvectors components = components.getSubMatrix(0, components.getRowDimension() - 1, 0, maxDimensions - 1); } modelParameters.setEigenValues(eigenValues); modelParameters.setComponents(components); }
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. *//*from w ww .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.joptimizer.optimizers.LPPresolverTest.java
private void doPresolving(double[] c, double[][] A, double[] b, double[] lb, double[] ub, double s, double[] expectedSolution, double expectedValue, double expectedTolerance) throws Exception { RealMatrix AMatrix = MatrixUtils.createRealMatrix(A); SingularValueDecomposition dec = new SingularValueDecomposition(AMatrix); int rankA = dec.getRank(); log.debug("p: " + AMatrix.getRowDimension()); log.debug("n: " + AMatrix.getColumnDimension()); log.debug("rank: " + rankA); LPPresolver lpPresolver = new LPPresolver(); lpPresolver.setNOfSlackVariables((short) s); lpPresolver.setExpectedSolution(expectedSolution);//this is just for test! //lpPresolver.setExpectedTolerance(expectedTolerance);//this is just for test! lpPresolver.presolve(c, A, b, lb, ub); int n = lpPresolver.getPresolvedN(); double[] presolvedC = lpPresolver.getPresolvedC().toArray(); double[][] presolvedA = lpPresolver.getPresolvedA().toArray(); double[] presolvedB = lpPresolver.getPresolvedB().toArray(); double[] presolvedLb = lpPresolver.getPresolvedLB().toArray(); double[] presolvedUb = lpPresolver.getPresolvedUB().toArray(); double[] presolvedYlb = lpPresolver.getPresolvedYlb().toArray(); double[] presolvedYub = lpPresolver.getPresolvedYub().toArray(); double[] presolvedZlb = lpPresolver.getPresolvedZlb().toArray(); double[] presolvedZub = lpPresolver.getPresolvedZub().toArray(); log.debug("n : " + n); log.debug("presolvedC : " + ArrayUtils.toString(presolvedC)); log.debug("presolvedA : " + ArrayUtils.toString(presolvedA)); log.debug("presolvedB : " + ArrayUtils.toString(presolvedB)); log.debug("presolvedLb : " + ArrayUtils.toString(presolvedLb)); log.debug("presolvedUb : " + ArrayUtils.toString(presolvedUb)); log.debug("presolvedYlb: " + ArrayUtils.toString(presolvedYlb)); log.debug("presolvedYub: " + ArrayUtils.toString(presolvedYub)); log.debug("presolvedZlb: " + ArrayUtils.toString(presolvedZlb)); log.debug("presolvedZub: " + ArrayUtils.toString(presolvedZub)); //check objective function double delta = expectedTolerance; RealVector presolvedX = MatrixUtils.createRealVector(lpPresolver.presolve(expectedSolution)); log.debug("presolved value: " + MatrixUtils.createRealVector(presolvedC).dotProduct(presolvedX)); RealVector postsolvedX = MatrixUtils.createRealVector(lpPresolver.postsolve(presolvedX.toArray())); double value = MatrixUtils.createRealVector(c).dotProduct(postsolvedX); assertEquals(expectedValue, value, delta); //check postsolved constraints for (int i = 0; i < lb.length; i++) { double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i]; assertTrue(di <= postsolvedX.getEntry(i) + delta); }//from ww w . j a v a 2 s. c o m for (int i = 0; i < ub.length; i++) { double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i]; assertTrue(di + delta >= postsolvedX.getEntry(i)); } RealVector Axmb = AMatrix.operate(postsolvedX).subtract(MatrixUtils.createRealVector(b)); assertEquals(0., Axmb.getNorm(), expectedTolerance); //check presolved constraints assertEquals(presolvedLb.length, presolvedX.getDimension()); assertEquals(presolvedUb.length, presolvedX.getDimension()); AMatrix = MatrixUtils.createRealMatrix(presolvedA); RealVector bvector = MatrixUtils.createRealVector(presolvedB); for (int i = 0; i < presolvedLb.length; i++) { double di = Double.isNaN(presolvedLb[i]) ? -Double.MAX_VALUE : presolvedLb[i]; assertTrue(di <= presolvedX.getEntry(i) + delta); } for (int i = 0; i < presolvedUb.length; i++) { double di = Double.isNaN(presolvedUb[i]) ? Double.MAX_VALUE : presolvedUb[i]; assertTrue(di + delta >= presolvedX.getEntry(i)); } Axmb = AMatrix.operate(presolvedX).subtract(bvector); assertEquals(0., Axmb.getNorm(), expectedTolerance); //check rank(A): must be A pXn with rank(A)=p < n AMatrix = MatrixUtils.createRealMatrix(presolvedA); dec = new SingularValueDecomposition(AMatrix); rankA = dec.getRank(); log.debug("p: " + AMatrix.getRowDimension()); log.debug("n: " + AMatrix.getColumnDimension()); log.debug("rank: " + rankA); assertEquals(AMatrix.getRowDimension(), rankA); assertTrue(rankA < AMatrix.getColumnDimension()); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.DifferentialEvolutionMinimizer.java
/** * Performs a minimization of a function starting with an single initial guess; a full population is generated based on this guess and the parameter 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. * @param initialGuess A guess at the value of each parameter at the optimum. * @return The parameter values at the minimal function value found. *//*from ww w.ja va 2s. com*/ public RealVector minimizeWithInitial(ObjectiveFunction f, RealVector parameterLowerBounds, RealVector parameterUpperBounds, int populationSize, double scaleFactor, int maxIterations, double crossoverFrequency, double tol, RealVector initialGuess) { int numberOfParameters = parameterLowerBounds.getDimension(); //generate the initial population RealMatrix population = new Array2DRowRealMatrix(populationSize, numberOfParameters); for (int i = 1; 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)); } } population.setRowVector(0, initialGuess); return minimizeWithPopulation(population, f, parameterLowerBounds, parameterUpperBounds, populationSize, scaleFactor, maxIterations, crossoverFrequency, tol); }
From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java
@Override public void setSubVector(int index, RealVector v) { checkIndex(index);// ww w .ja v a 2s.c om checkIndex(index + v.getDimension() - 1); for (int i = 0; i < v.getDimension(); i++) { setEntry(i + index, v.getEntry(i)); } }
From source file:de.thkwalter.et.ortskurve.Startpunktbestimmung.java
/** * Diese Methode berechnet den Startpunkt aus den ersten drei Messpunkten. * //from www . j a v a 2 s. 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:com.cloudera.oryx.common.math.OpenMapRealVector.java
/** * Generic copy constructor./*from w w w. j a v a2s . com*/ * * @param v Instance to copy from. */ public OpenMapRealVector(RealVector v) { virtualSize = v.getDimension(); entries = new OpenIntToDoubleHashMap(0.0); epsilon = DEFAULT_ZERO_TOLERANCE; for (int key = 0; key < virtualSize; key++) { double value = v.getEntry(key); if (!isDefaultValue(value)) { entries.put(key, value); } } }
From source file:edu.stanford.cfuller.colocalization3d.correction.PositionCorrector.java
private RealVector correctSingleObjectVectorDifference(Correction c, ImageObject obj, int referenceChannel, int correctionChannel) throws UnableToCorrectException { RealVector corr = c.correctPosition(obj.getPositionForChannel(referenceChannel).getEntry(0), obj.getPositionForChannel(referenceChannel).getEntry(1)); boolean flip = this.parameters.getBooleanValueForKey("flip_channels_at_end"); if (flip)//from w w w . java 2s . c o m corr.mapMultiplyToSelf(-1.0); boolean invert_z = this.parameters.hasKeyAndTrue(INVERT_Z_PARAM); if (invert_z) corr.setEntry(2, -1.0 * corr.getEntry(2)); obj.applyCorrectionVectorToChannel(correctionChannel, corr); RealVector correctedVectorDiff = obj .getCorrectedVectorDifferenceBetweenChannels(referenceChannel, correctionChannel) .ebeMultiply(this.pixelToDistanceConversions); return correctedVectorDiff; }
From source file:com.joptimizer.optimizers.LPPresolverNetlibTest.java
/** * Tests the presolving of a netlib problem. * If checkExpectedSolution, the presolving is checked step by step against * a (beforehand) known solution of the problem. * NOTE: this known solution might differ from the solution given by the presolver * (e.g. in the presence of a weakly dominated column @see {@link LPPresolver#removeDominatedColumns}, * or if it is calculated with simplex method * or if bounds are not exactly the same), so sometimes it is not a good test. */// ww w .j a v a2s . co m public void doTesting(String problemName, boolean checkExpectedSolution, double myExpectedTolerance) throws Exception { log.debug("doTesting: " + problemName); int s = (int) Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardS.txt")[0]; double[] c = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardC.txt"); double[][] A = Utils.loadDoubleMatrixFromFile( "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardA.csv", ",".charAt(0)); double[] b = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardB.txt"); double[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardLB.txt"); double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardUB.txt"); double[] expectedSolution = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardSolution.txt"); double expectedValue = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardValue.txt")[0]; double expectedTolerance = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardTolerance.txt")[0]; //in order to compare with tha Math results, we must have the same bounds for (int i = 0; i < lb.length; i++) { if (Double.isNaN(lb[i])) { lb[i] = -9999999d; //the same as the notebook value } } for (int i = 0; i < ub.length; i++) { if (Double.isNaN(ub[i])) { ub[i] = +9999999d; //the same as the notebook value } } RealMatrix AMatrix = MatrixUtils.createRealMatrix(A); RealVector bVector = MatrixUtils.createRealVector(b); //expectedTolerance = Math.max(expectedTolerance, AMatrix.operate(MatrixUtils.createRealVector(expectedSolution)).subtract(bVector).getNorm()); expectedTolerance = Math.max(1.e-9, expectedTolerance); // must be: A pXn with rank(A)=p < n QRSparseFactorization qr = new QRSparseFactorization(new SparseDoubleMatrix2D(A)); qr.factorize(); log.debug("p : " + AMatrix.getRowDimension()); log.debug("n : " + AMatrix.getColumnDimension()); log.debug("full rank: " + qr.hasFullRank()); LPPresolver lpPresolver = new LPPresolver(); lpPresolver.setNOfSlackVariables((short) s); if (checkExpectedSolution) { lpPresolver.setExpectedSolution(expectedSolution);// this is just for test! lpPresolver.setExpectedTolerance(myExpectedTolerance);// this is just for test! } // lpPresolver.setAvoidFillIn(true); // lpPresolver.setZeroTolerance(1.e-13); lpPresolver.presolve(c, A, b, lb, ub); int n = lpPresolver.getPresolvedN(); DoubleMatrix1D presolvedC = lpPresolver.getPresolvedC(); DoubleMatrix2D presolvedA = lpPresolver.getPresolvedA(); DoubleMatrix1D presolvedB = lpPresolver.getPresolvedB(); DoubleMatrix1D presolvedLb = lpPresolver.getPresolvedLB(); DoubleMatrix1D presolvedUb = lpPresolver.getPresolvedUB(); DoubleMatrix1D presolvedYlb = lpPresolver.getPresolvedYlb(); DoubleMatrix1D presolvedYub = lpPresolver.getPresolvedYub(); DoubleMatrix1D presolvedZlb = lpPresolver.getPresolvedZlb(); DoubleMatrix1D presolvedZub = lpPresolver.getPresolvedZub(); log.debug("n : " + n); if (log.isDebugEnabled() && n > 0) { log.debug("presolvedC : " + ArrayUtils.toString(presolvedC.toArray())); log.debug("presolvedA : " + ArrayUtils.toString(presolvedA.toArray())); log.debug("presolvedB : " + ArrayUtils.toString(presolvedB.toArray())); log.debug("presolvedLb : " + ArrayUtils.toString(presolvedLb.toArray())); log.debug("presolvedUb : " + ArrayUtils.toString(presolvedUb.toArray())); log.debug("presolvedYlb: " + ArrayUtils.toString(presolvedYlb.toArray())); log.debug("presolvedYub: " + ArrayUtils.toString(presolvedYub.toArray())); log.debug("presolvedZlb: " + ArrayUtils.toString(presolvedZlb.toArray())); log.debug("presolvedZub: " + ArrayUtils.toString(presolvedZub.toArray())); } if (n == 0) { // deterministic problem double[] sol = lpPresolver.postsolve(new double[] {}); assertEquals(expectedSolution.length, sol.length); for (int i = 0; i < sol.length; i++) { // log.debug("i: " + i); assertEquals(expectedSolution[i], sol[i], 1.e-9); } } else { Utils.writeDoubleArrayToFile(presolvedC.toArray(), "target" + File.separator + "presolvedC_" + problemName + ".txt"); Utils.writeDoubleMatrixToFile(presolvedA.toArray(), "target" + File.separator + "presolvedA_" + problemName + ".csv"); Utils.writeDoubleArrayToFile(presolvedB.toArray(), "target" + File.separator + "presolvedB_" + problemName + ".txt"); Utils.writeDoubleArrayToFile(presolvedLb.toArray(), "target" + File.separator + "presolvedLB_" + problemName + ".txt"); Utils.writeDoubleArrayToFile(presolvedUb.toArray(), "target" + File.separator + "presolvedUB_" + problemName + ".txt"); // check objective function double delta = expectedTolerance; RealVector presolvedES = MatrixUtils.createRealVector(lpPresolver.presolve(expectedSolution)); double presolvedEV = MatrixUtils.createRealVector(presolvedC.toArray()).dotProduct(presolvedES);// in general it is different from the optimal value log.debug("presolved expected value: " + presolvedEV); RealVector postsolvedES = MatrixUtils.createRealVector(lpPresolver.postsolve(presolvedES.toArray())); double postsolvedEV = MatrixUtils.createRealVector(c).dotProduct(postsolvedES); //assertEquals(expectedValue, postsolvedEV, delta); assertTrue(Math.abs((expectedValue - postsolvedEV) / expectedValue) < delta); // check postsolved constraints for (int i = 0; i < lb.length; i++) { double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i]; assertTrue(di <= postsolvedES.getEntry(i) + delta); } for (int i = 0; i < ub.length; i++) { double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i]; assertTrue(di + delta >= postsolvedES.getEntry(i)); } RealVector Axmb = AMatrix.operate(postsolvedES).subtract(bVector); assertEquals(0., Axmb.getNorm(), 1.5 * expectedTolerance); // check presolved constraints assertEquals(presolvedLb.size(), presolvedES.getDimension()); assertEquals(presolvedUb.size(), presolvedES.getDimension()); AMatrix = MatrixUtils.createRealMatrix(presolvedA.toArray());//reassigned to avoid memory consumption bVector = MatrixUtils.createRealVector(presolvedB.toArray()); for (int i = 0; i < presolvedLb.size(); i++) { double di = Double.isNaN(presolvedLb.getQuick(i)) ? -Double.MAX_VALUE : presolvedLb.getQuick(i); assertTrue(di <= presolvedES.getEntry(i) + delta); } for (int i = 0; i < presolvedUb.size(); i++) { double di = Double.isNaN(presolvedUb.getQuick(i)) ? Double.MAX_VALUE : presolvedUb.getQuick(i); assertTrue(di + delta >= presolvedES.getEntry(i)); } Axmb = AMatrix.operate(presolvedES).subtract(bVector); assertEquals(0., Axmb.getNorm(), 1.5 * expectedTolerance); //check for 0-rows List<Integer> zeroRows = new ArrayList<Integer>(); for (int i = 0; i < presolvedA.rows(); i++) { boolean isNotZero = false; for (int j = 0; !isNotZero && j < presolvedA.columns(); j++) { isNotZero = Double.compare(0., presolvedA.getQuick(i, j)) != 0; } if (!isNotZero) { zeroRows.add(zeroRows.size(), i); } } if (!zeroRows.isEmpty()) { log.debug("All 0 entries in rows " + ArrayUtils.toString(zeroRows)); fail(); } //check for 0-columns List<Integer> zeroCols = new ArrayList<Integer>(); for (int j = 0; j < presolvedA.columns(); j++) { boolean isNotZero = false; for (int i = 0; !isNotZero && i < presolvedA.rows(); i++) { isNotZero = Double.compare(0., presolvedA.getQuick(i, j)) != 0; } if (!isNotZero) { zeroCols.add(zeroCols.size(), j); } } if (!zeroCols.isEmpty()) { log.debug("All 0 entries in columns " + ArrayUtils.toString(zeroCols)); fail(); } // check rank(A): must be A pXn with rank(A)=p < n qr = new QRSparseFactorization(new SparseDoubleMatrix2D(presolvedA.toArray())); qr.factorize(); boolean isFullRank = qr.hasFullRank(); log.debug("p : " + AMatrix.getRowDimension()); log.debug("n : " + AMatrix.getColumnDimension()); log.debug("full rank: " + isFullRank); assertTrue(AMatrix.getRowDimension() < AMatrix.getColumnDimension()); assertTrue(isFullRank); } }
From source file:edu.stanford.cfuller.colocalization3d.Colocalization3DMain.java
private String formatPositionData(java.util.List<ImageObject> imageObjects, Correction c) { StringBuilder sb = new StringBuilder(); StringBuilder sbSingle = new StringBuilder(); String currentImageName = ""; File lastFile = null;//from w w w.j a v a 2 s.co m for (int o = 0; o < imageObjects.size(); o++) { ImageObject currObject = imageObjects.get(o); String objectImageName = currObject.getImageID(); if (!currentImageName.equals(objectImageName)) { if (!(sbSingle.length() == 0)) { sb.append(sbSingle.toString()); sbSingle = new StringBuilder(); } sb.append(objectImageName + "\n"); currentImageName = objectImageName; } RealVector correction = null; try { correction = c.correctPosition( currObject.getPositionForChannel(c.getReferenceChannelIndex()).getEntry(0), currObject.getPositionForChannel(c.getReferenceChannelIndex()).getEntry(1)); } catch (UnableToCorrectException e) { continue; } sbSingle.append(currObject.getLabel()); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getReferenceChannelIndex()).getEntry(0)); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getReferenceChannelIndex()).getEntry(1)); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getReferenceChannelIndex()).getEntry(2)); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getCorrectionChannelIndex()).getEntry(0)); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getCorrectionChannelIndex()).getEntry(1)); sbSingle.append(" "); sbSingle.append(currObject.getPositionForChannel(c.getCorrectionChannelIndex()).getEntry(2)); sbSingle.append(" "); RealVector corrPos = null; RealVector modCorrection = correction; if (this.parameters.hasKeyAndTrue("flip_channels_at_end")) { modCorrection = correction.mapMultiply(-1.0); } if (this.parameters.hasKeyAndTrue("inverted_z_axis")) { modCorrection = correction.mapMultiply(1.0); modCorrection.setEntry(2, -1.0 * modCorrection.getEntry(2)); } corrPos = currObject.getPositionForChannel(c.getCorrectionChannelIndex()).subtract(modCorrection); sbSingle.append(corrPos.getEntry(0)); sbSingle.append(" "); sbSingle.append(corrPos.getEntry(1)); sbSingle.append(" "); sbSingle.append(corrPos.getEntry(2)); sbSingle.append(" "); sbSingle.append( currObject.getFitParametersByChannel().get(c.getReferenceChannelIndex()).getAmplitude()); sbSingle.append(" "); sbSingle.append( currObject.getFitParametersByChannel().get(c.getCorrectionChannelIndex()).getAmplitude()); sbSingle.append("\n"); } sb.append(sbSingle.toString()); return sb.toString(); }