List of usage examples for org.apache.commons.math3.linear RealVector getEntry
public abstract double getEntry(int index) throws OutOfRangeException;
From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java
@Override public OpenMapRealVector append(RealVector v) { if (v instanceof OpenMapRealVector) { return append((OpenMapRealVector) v); }/*from ww w .j a va 2 s. c o m*/ OpenMapRealVector res = new OpenMapRealVector(this, v.getDimension()); for (int i = 0; i < v.getDimension(); i++) { res.setEntry(i + virtualSize, v.getEntry(i)); } return res; }
From source file:edu.utexas.cs.tactex.servercustomers.factoredcustomer.DefaultCapacityOriginator.java
/** * NOTE: subtle conversion that caused a bug - we use predictions * starting next time-step, but forecastCapacities are assumed * to be from current - so to return data to broker we need to * offset the record by 1/*w w w .j av a 2 s.c om*/ */ @Override public void convertEnergyProfileFromBrokerToServer(RealVector originatorEnergy, int currentTimeslot) { final int brokerEnergyRecordLength = originatorEnergy.getDimension(); for (int i = 0; i < CapacityProfile.NUM_TIMESLOTS; ++i) { //log.info("updateForecastCapacities(" + (currentTimeslot + i) + ")=" + originatorEnergy.getEntry(i)); int i_minus_1_that_will_work_for_modulo = CapacityProfile.NUM_TIMESLOTS + i - 1; forecastCapacities.put(currentTimeslot + i, originatorEnergy.getEntry(i_minus_1_that_will_work_for_modulo % CapacityProfile.NUM_TIMESLOTS)); } }
From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java
@SuppressWarnings("deprecation") @Deprecated/*from www. j ava2s . co m*/ @Override public OpenMapRealVector ebeMultiply(RealVector v) { checkVectorDimensions(v.getDimension()); OpenMapRealVector res = new OpenMapRealVector(this); OpenIntToDoubleHashMap.Iterator iter = entries.iterator(); while (iter.hasNext()) { iter.advance(); res.setEntry(iter.key(), iter.value() * v.getEntry(iter.key())); } /* * MATH-803: the above loop assumes that 0d * x = 0d for any double x, * which allows to consider only the non-zero entries of this. However, * this fails if this[i] == 0d and (v[i] = NaN or v[i] = Infinity). * * These special cases are handled below. */ if (v.isNaN() || v.isInfinite()) { int n = getDimension(); for (int i = 0; i < n; i++) { double y = v.getEntry(i); if (Double.isNaN(y)) { res.setEntry(i, Double.NaN); } else if (Double.isInfinite(y)) { double x = this.getEntry(i); res.setEntry(i, x * y); } } } return res; }
From source file:edu.stanford.cfuller.colocalization3d.correction.PositionCorrector.java
/** * Creates an in situ cellular aberration correction. This will take a specified group of datasets from the parameters file and perform a robust linar fit between * the aberrations in two pairs of channels (also specified in the parameters file). * * @return a RealVector with three elements: the slope of the linear fit in the x, y, and z directions. *///from ww w . j a va 2s .co m public RealVector determineInSituAberrationCorrection() { int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM); int inSituAberrCorrChannel = this.parameters.getIntValueForKey(IN_SITU_ABERR_SECOND_CH_PARAM); int measurementChannel = this.parameters.getIntValueForKey(CORR_CH_PARAM); List<ImageObject> iobjsForInSituAberrCorr = null; try { iobjsForInSituAberrCorr = FileUtils.readInSituAberrCorrPositionData(this.parameters); } catch (java.io.IOException e) { java.util.logging.Logger .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME) .severe("Exception encountered while reading data for in situ aberration correction from disk: " + e.getMessage()); } catch (ClassNotFoundException e) { java.util.logging.Logger .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME) .severe("Exception encountered while reading data for in situ aberration correction from disk: " + e.getMessage()); } RealVector xForCorr = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); RealVector xForExpt = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); RealVector yForCorr = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); RealVector yForExpt = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); RealVector zForCorr = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); RealVector zForExpt = new org.apache.commons.math3.linear.ArrayRealVector(iobjsForInSituAberrCorr.size(), 0.0); for (int i = 0; i < iobjsForInSituAberrCorr.size(); i++) { ImageObject currObj = iobjsForInSituAberrCorr.get(i); RealVector corrDiff = currObj .getCorrectedVectorDifferenceBetweenChannels(referenceChannel, inSituAberrCorrChannel) .ebeMultiply(this.pixelToDistanceConversions); RealVector exptDiff = currObj .getCorrectedVectorDifferenceBetweenChannels(referenceChannel, measurementChannel) .ebeMultiply(this.pixelToDistanceConversions); xForCorr.setEntry(i, corrDiff.getEntry(0)); yForCorr.setEntry(i, corrDiff.getEntry(1)); zForCorr.setEntry(i, corrDiff.getEntry(2)); xForExpt.setEntry(i, exptDiff.getEntry(0)); yForExpt.setEntry(i, exptDiff.getEntry(1)); zForExpt.setEntry(i, exptDiff.getEntry(2)); } BisquareLinearFit bslf = new BisquareLinearFit(); bslf.disableIntercept(); RealVector xFit = bslf.fit(xForCorr, xForExpt); RealVector yFit = bslf.fit(yForCorr, yForExpt); RealVector zFit = bslf.fit(zForCorr, zForExpt); RealVector allSlopes = new org.apache.commons.math3.linear.ArrayRealVector(3, 0.0); allSlopes.setEntry(0, xFit.getEntry(0)); allSlopes.setEntry(1, yFit.getEntry(0)); allSlopes.setEntry(2, zFit.getEntry(0)); return allSlopes; }
From source file:monitor.processing.OLD.Drawing3D.java
public void drawTree(BaseNode n, RealVector v, PGraphics g3) { if (n instanceof TransformNode) { //v = ((TransformNode) n).getTrasformMatrix().operate(v); v = ((TransformNode) n).getTrasformMatrix().getColumnVector(3); }/*from w ww .j a va 2s. c o m*/ int argb = -(n.getAddress() + 2); int a = (argb >> 24) & 0xFF; int r = (argb >> 16) & 0xFF; // Faster way of getting red(argb) int g = (argb >> 8) & 0xFF; // Faster way of getting green(argb) int b = argb & 0xFF; // Faster way of getting blue(argb) // System.out.println("gravou: " + r + " " + g + " " + b + " " + a + " :: " + -(argb+2)); g3.fill(r, g, b, a); g3.pushMatrix(); g3.translate((float) (scale * v.getEntry(0)), (float) (-scale * v.getEntry(1)), (float) (scale * v.getEntry(2))); g3.box(0.05f * scale); g3.popMatrix(); for (int i = n.getChildren().size() - 1; i >= 0; i--) { drawTree(((ArrayList<BaseNode>) n.getChildren()).get(i), v, g3); } }
From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java
@SuppressWarnings("deprecation") @Deprecated//from w ww.ja v a 2 s .co m @Override public OpenMapRealVector ebeDivide(RealVector v) { checkVectorDimensions(v.getDimension()); OpenMapRealVector res = new OpenMapRealVector(this); /* * MATH-803: it is not sufficient to loop through non zero entries of * this only. Indeed, if this[i] = 0d and v[i] = 0d, then * this[i] / v[i] = NaN, and not 0d. */ int n = getDimension(); for (int i = 0; i < n; i++) { res.setEntry(i, this.getEntry(i) / v.getEntry(i)); } return res; }
From source file:lirmm.inria.fr.math.BigSparseRealMatrixTest.java
/** * test examples in user guide//from w w w.j a v a 2s . co m */ @Test public void testExamples() { // Create a real matrix with two rows and three columns double[][] matrixData = { { 1d, 2d, 3d }, { 2d, 5d, 3d } }; RealMatrix m = new BigSparseRealMatrix(matrixData); // One more with three rows, two columns double[][] matrixData2 = { { 1d, 2d }, { 2d, 5d }, { 1d, 7d } }; RealMatrix n = new BigSparseRealMatrix(matrixData2); // Now specialOperation m by n RealMatrix p = m.multiply(n); Assert.assertEquals(2, p.getRowDimension()); Assert.assertEquals(2, p.getColumnDimension()); // Invert p RealMatrix pInverse = new LUDecomposition(p).getSolver().getInverse(); Assert.assertEquals(2, pInverse.getRowDimension()); Assert.assertEquals(2, pInverse.getColumnDimension()); // Solve example double[][] coefficientsData = { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }; RealMatrix coefficients = new BigSparseRealMatrix(coefficientsData); RealVector constants = new ArrayRealVector(new double[] { 1, -2, 1 }, false); RealVector solution = new LUDecomposition(coefficients).getSolver().solve(constants); final double cst0 = constants.getEntry(0); final double cst1 = constants.getEntry(1); final double cst2 = constants.getEntry(2); final double sol0 = solution.getEntry(0); final double sol1 = solution.getEntry(1); final double sol2 = solution.getEntry(2); Assert.assertEquals(2 * sol0 + 3 * sol1 - 2 * sol2, cst0, 1E-12); Assert.assertEquals(-1 * sol0 + 7 * sol1 + 6 * sol2, cst1, 1E-12); Assert.assertEquals(4 * sol0 - 3 * sol1 - 5 * sol2, cst2, 1E-12); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.NelderMeadMinimizer.java
/** * Runs the minimization of the specified function starting from an initial simplex. * @param f The ObjectiveFunction to be minimized. * @param initialSimplex The initial simplex to use to start optimization, as might be returned from {@link #generateInitialSimplex} * @return The parameters at the function minimum in the same order as specified for each point on the simplex. *//*from www . j a v a 2s. c o m*/ public RealVector optimize(ObjectiveFunction f, RealMatrix initialSimplex) { RealMatrix currentSimplex = initialSimplex.copy(); double currTolVal = 1.0e6; RealVector values = new ArrayRealVector(initialSimplex.getRowDimension(), 0.0); RealVector centerOfMass = new ArrayRealVector(initialSimplex.getColumnDimension(), 0.0); boolean shouldEvaluate = false; long iterCounter = 0; while (Math.abs(currTolVal) > this.tol) { int maxIndex = 0; int minIndex = 0; double maxValue = -1.0 * Double.MAX_VALUE; double minValue = Double.MAX_VALUE; double secondMaxValue = -1.0 * Double.MAX_VALUE; centerOfMass.mapMultiplyToSelf(0.0); if (shouldEvaluate) { for (int i = 0; i < currentSimplex.getRowDimension(); i++) { RealVector currRow = currentSimplex.getRowVector(i); values.setEntry(i, f.evaluate(currRow)); } } for (int i = 0; i < currentSimplex.getRowDimension(); i++) { double currValue = values.getEntry(i); if (currValue < minValue) { minValue = currValue; minIndex = i; } if (currValue > maxValue) { secondMaxValue = maxValue; maxValue = currValue; maxIndex = i; } else if (currValue > secondMaxValue) { secondMaxValue = currValue; } } for (int i = 0; i < currentSimplex.getRowDimension(); i++) { if (i == maxIndex) continue; centerOfMass = centerOfMass.add(currentSimplex.getRowVector(i)); } centerOfMass.mapDivideToSelf(currentSimplex.getRowDimension() - 1); RealVector oldPoint = currentSimplex.getRowVector(maxIndex); RealVector newPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(a).add(centerOfMass); // newpoint = COM + a*(COM-oldpoint) double newValue = f.evaluate(newPoint); if (newValue < secondMaxValue) { // success if (newValue < minValue) { // best found so far //expansion RealVector expPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(g).add(centerOfMass); double expValue = f.evaluate(expPoint); if (expValue < newValue) { currentSimplex.setRowVector(maxIndex, expPoint); currTolVal = 2.0 * (expValue - maxValue) / (1.0e-20 + expValue + maxValue); values.setEntry(maxIndex, expValue); shouldEvaluate = false; continue; } } //reflection currentSimplex.setRowVector(maxIndex, newPoint); currTolVal = 2.0 * (newValue - maxValue) / (1.0e-20 + newValue + maxValue); values.setEntry(maxIndex, newValue); shouldEvaluate = false; continue; } //contraction RealVector conPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(r).add(centerOfMass); double conValue = f.evaluate(conPoint); if (conValue < maxValue) { currentSimplex.setRowVector(maxIndex, conPoint); currTolVal = 2.0 * (conValue - maxValue) / (1.0e-20 + conValue + maxValue); values.setEntry(maxIndex, conValue); shouldEvaluate = false; continue; } //reduction for (int i = 0; i < currentSimplex.getRowDimension(); i++) { if (i == minIndex) continue; currentSimplex.setRowVector(i, currentSimplex.getRowVector(i).subtract(currentSimplex.getRowVector(minIndex)) .mapMultiplyToSelf(s).add(currentSimplex.getRowVector(minIndex))); } double redValue = f.evaluate(currentSimplex.getRowVector(maxIndex)); currTolVal = 2.0 * (redValue - maxValue) / (1.0e-20 + redValue + maxValue); shouldEvaluate = true; if (iterCounter++ > 100000) { System.out.println("stalled? tol: " + currTolVal + " minValue: " + minValue); } } double minValue = Double.MAX_VALUE; RealVector minVector = null; for (int i = 0; i < currentSimplex.getRowDimension(); i++) { values.setEntry(i, f.evaluate(currentSimplex.getRowVector(i))); if (values.getEntry(i) < minValue) { minValue = values.getEntry(i); minVector = currentSimplex.getRowVector(i); } } return minVector; }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form/*ww w .j a v a 2 s .com*/ * min(c.x) s.t. * G.x < h * The objective function of the presolved problem has a 0-gradient. */ public void testCGh4() throws Exception { log.debug("testCGh4"); String problemId = "4"; //the original problem: ok until precision 1.E-7 double[] c = Utils.loadDoubleArrayFromFile("lp" + File.separator + "c" + problemId + ".txt"); double[][] G = Utils.loadDoubleMatrixFromFile("lp" + File.separator + "G" + problemId + ".csv", ",".charAt(0)); double[] h = Utils.loadDoubleArrayFromFile("lp" + File.separator + "h" + problemId + ".txt"); ; double[] expectedSol = Utils.loadDoubleArrayFromFile("lp" + File.separator + "sol" + problemId + ".txt"); double expectedValue = Utils .loadDoubleArrayFromFile("lp" + File.separator + "value" + problemId + ".txt")[0]; //double norm = MatrixUtils.createRealMatrix(A).operate(MatrixUtils.createRealVector(expectedSol)).subtract(MatrixUtils.createRealVector(b)).getNorm(); //assertTrue(norm < 1.e-10); LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setCheckKKTSolutionAccuracy(true); or.setToleranceKKT(1.E-7); or.setToleranceFeas(1.E-6); or.setTolerance(1.E-5); or.setDumpProblem(true); or.setRescalingDisabled(true);//this fails with false //optimization //LPPrimalDualMethodOLD opt = new LPPrimalDualMethodOLD(); LPPrimalDualMethod opt = new LPPrimalDualMethod(); opt.setLPOptimizationRequest(or); int returnCode = opt.optimize(); if (returnCode == OptimizationResponse.FAILED) { fail(); } LPOptimizationResponse response = opt.getLPOptimizationResponse(); double[] sol = response.getSolution(); RealVector cVector = new ArrayRealVector(c); RealVector solVector = new ArrayRealVector(sol); double value = cVector.dotProduct(solVector); log.debug("sol : " + ArrayUtils.toString(sol)); log.debug("value : " + value); //check constraints RealVector x = MatrixUtils.createRealVector(sol); RealMatrix GMatrix = MatrixUtils.createRealMatrix(G); RealVector hvector = MatrixUtils.createRealVector(h); RealVector Gxh = GMatrix.operate(x).subtract(hvector); for (int i = 0; i < Gxh.getDimension(); i++) { assertTrue(Gxh.getEntry(i) <= 0);//not strictly because some constraint has been treated as a bound } //check value assertEquals(expectedValue, value, or.getTolerance()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form//from w w w .j av a 2 s . c o m * min(c.x) s.t. * G.x < h * A.x = b * * This is the same as testCGhAbLbUb2, but lb and ub are into G. * The presolved problem has a deterministic solution, that is, all the variables have a fixed value. */ public void testCGhAb3() throws Exception { log.debug("testCGhAb3"); String problemId = "3"; log.debug("problemId: " + problemId); double[] c = Utils.loadDoubleArrayFromFile("lp" + File.separator + "c" + problemId + ".txt"); double[][] G = Utils.loadDoubleMatrixFromFile("lp" + File.separator + "G" + problemId + ".csv", ",".charAt(0)); double[] h = Utils.loadDoubleArrayFromFile("lp" + File.separator + "h" + problemId + ".txt"); ; double[][] A = Utils.loadDoubleMatrixFromFile("lp" + File.separator + "A" + problemId + ".csv", ",".charAt(0)); double[] b = Utils.loadDoubleArrayFromFile("lp" + File.separator + "b" + problemId + ".txt"); double[] expectedSol = Utils.loadDoubleArrayFromFile("lp" + File.separator + "sol" + problemId + ".txt"); double expectedvalue = Utils .loadDoubleArrayFromFile("lp" + File.separator + "value" + problemId + ".txt")[0]; double minLb = 0; double maxUb = 1.0E15;//it is so high because of the very high values of the elements of h LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setA(A); or.setB(b); or.setCheckKKTSolutionAccuracy(true); //or.setToleranceKKT(1.e-5); // or.setToleranceFeas(5.E-5); // or.setTolerance(1.E-7); or.setDumpProblem(true); //or.setPresolvingDisabled(true); //optimization LPPrimalDualMethod opt = new LPPrimalDualMethod(minLb, maxUb); opt.setLPOptimizationRequest(or); int returnCode = opt.optimize(); if (returnCode == OptimizationResponse.FAILED) { fail(); } LPOptimizationResponse response = opt.getLPOptimizationResponse(); double[] sol = response.getSolution(); RealVector cVector = new ArrayRealVector(c); RealVector solVector = new ArrayRealVector(sol); double value = cVector.dotProduct(solVector); log.debug("sol : " + ArrayUtils.toString(sol)); log.debug("value : " + value); //check constraints RealVector x = MatrixUtils.createRealVector(sol); RealMatrix GMatrix = MatrixUtils.createRealMatrix(G); RealVector hvector = MatrixUtils.createRealVector(h); RealMatrix AMatrix = MatrixUtils.createRealMatrix(A); RealVector bvector = MatrixUtils.createRealVector(b); RealVector Gxh = GMatrix.operate(x).subtract(hvector); for (int i = 0; i < Gxh.getDimension(); i++) { assertTrue(Gxh.getEntry(i) <= 0); } RealVector Axb = AMatrix.operate(x).subtract(bvector); assertEquals(0., Axb.getNorm(), or.getToleranceFeas()); assertEquals(expectedSol.length, sol.length); // for(int i=0; i<sol.length; i++){ // assertEquals(expectedSol[0], sol[0], or.getTolerance()); // } assertEquals(expectedvalue, value, or.getTolerance()); }