List of usage examples for org.apache.commons.math3.linear RealVector getDimension
public abstract int getDimension();
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form/*from w w w . ja va 2 s . co 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()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form/*ww w .j av a2s . co m*/ * min(c.x) s.t. * G.x < h * A.x = b * * This is a good for testing with a small size problem. * Submitted 01/09/2013 by Chris Myers. * * @see JOptimizerTest#testCGhAb1() */ public void testCGhAb1() throws Exception { log.debug("testCGhAb1"); String problemId = "1"; //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[][] 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 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.setA(A); or.setB(b); or.setCheckKKTSolutionAccuracy(true); or.setToleranceKKT(1.E-7); or.setToleranceFeas(1.E-7); or.setTolerance(1.E-7); or.setDumpProblem(true); or.setAlpha(0.75); or.setInitialPoint(new double[] { 0.9999998735888544, -999.0000001264111, 1000.0, 0.9999998735888544, 0.0, -999.0000001264111, 0.9999999661257591, 0.9999998735888544, 1000.0, 0.0, 0.9999998735888544, 0.0, 0.9999998735888544, 0.9999998735888544, 0.9999998735888544, 0.0, 0.0, 0.9999998735888544, -1000.0, 0.9999999198573067, 9.253690467190285E-8, 1000.0, -999.0000001264111, 0.9999998735888544, -1000.0, -1000.0 }); //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); 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);//not strictly because some constraint has been treated as a bound } RealVector Axb = AMatrix.operate(x).subtract(bvector); assertEquals(0., Axb.getNorm(), or.getToleranceFeas()); //check value assertEquals(expectedvalue, value, or.getTolerance()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form// w ww . ja v a 2 s . c om * min(c.x) s.t. * G.x < h * A.x = b * lb <= x <= ub * */ public void testCGhAbLbUb11() throws Exception { log.debug("testCGhAbLbUb11"); String problemId = "10"; 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[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "lb" + problemId + ".txt"); double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "ub" + problemId + ".txt"); double[] expectedSol = Utils.loadDoubleArrayFromFile("lp" + File.separator + "sol" + problemId + ".txt"); double expectedValue = Utils .loadDoubleArrayFromFile("lp" + File.separator + "value" + problemId + ".txt")[0]; //the unbounded bounds are saved on the files with NaN values, so substitute them with acceptable values lb = Utils.replaceValues(lb, Double.NaN, LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND); ub = Utils.replaceValues(ub, Double.NaN, LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND); //check expected sol RealVector expectedX = MatrixUtils.createRealVector(expectedSol); RealMatrix GMatrix = MatrixUtils.createRealMatrix(G); RealVector hvector = MatrixUtils.createRealVector(h); RealMatrix AMatrix = MatrixUtils.createRealMatrix(A); RealVector bvector = MatrixUtils.createRealVector(b); for (int i = 0; i < lb.length; i++) { assertTrue(lb[i] <= expectedX.getEntry(i)); } RealVector Gxh = GMatrix.operate(expectedX).subtract(hvector); for (int i = 0; i < Gxh.getDimension(); i++) { assertTrue(Gxh.getEntry(i) <= 0); } RealVector Axb = AMatrix.operate(expectedX).subtract(bvector); assertEquals(0., Axb.getNorm(), 1.E-6); LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setA(A); or.setB(b); or.setLb(lb); or.setUb(ub); or.setCheckKKTSolutionAccuracy(true); or.setDumpProblem(true); //or.setPresolvingDisabled(true); //or.setRescalingDisabled(true); //optimization 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); log.debug("expectedValue : " + expectedValue); assertEquals(expectedValue, value, or.getTolerance()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form// w w w .j a va 2 s . co m * min(c.x) s.t. * G.x < h * A.x = b * lb <= x <= ub * */ public void testCGhAbLbUb7() throws Exception { log.debug("testCGhAbLbUb7"); String problemId = "7"; 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[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "lb" + problemId + ".txt"); double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "ub" + problemId + ".txt"); double[] expectedSol = Utils.loadDoubleArrayFromFile("lp" + File.separator + "sol" + problemId + ".txt"); double expectedvalue = Utils .loadDoubleArrayFromFile("lp" + File.separator + "value" + problemId + ".txt")[0]; //the unbounded bounds are saved on the files with NaN values, so substitute them with acceptable values lb = Utils.replaceValues(lb, Double.NaN, LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND); ub = Utils.replaceValues(ub, Double.NaN, LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND); LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setA(A); or.setB(b); or.setLb(lb); or.setUb(ub); or.setCheckKKTSolutionAccuracy(true); // or.setToleranceKKT(1.e-7); // or.setToleranceFeas(1.E-7); // or.setTolerance(1.E-7); or.setDumpProblem(true); //or.setPresolvingDisabled(true); //or.setRescalingDisabled(true); //optimization 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 assertEquals(lb.length, sol.length); assertEquals(ub.length, sol.length); 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); for (int i = 0; i < lb.length; i++) { assertTrue(lb[i] <= x.getEntry(i)); } for (int i = 0; i < ub.length; i++) { double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i]; assertTrue(di <= x.getEntry(i)); } RealVector Gxh = GMatrix.operate(x).subtract(hvector); for (int i = 0; i < Gxh.getDimension(); i++) { double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i]; assertTrue(di >= x.getEntry(i)); } 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()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form// w ww.j av a 2 s. c om * min(c.x) s.t. * G.x < h * A.x = b * lb <= x <= ub * */ public void testCGhAbLbUb10() throws Exception { log.debug("testCGhAbLbUb10"); String problemId = "10"; 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[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "lb" + problemId + ".txt"); double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "ub" + problemId + ".txt"); double[] expectedSol = Utils.loadDoubleArrayFromFile("lp" + File.separator + "sol" + problemId + ".txt"); double expectedvalue = Utils .loadDoubleArrayFromFile("lp" + File.separator + "value" + problemId + ".txt")[0]; //the unbounded bounds are saved on the files with NaN values, so substitute them with acceptable values lb = Utils.replaceValues(lb, Double.NaN, LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND); ub = Utils.replaceValues(ub, Double.NaN, LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND); LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setA(A); or.setB(b); or.setLb(lb); or.setUb(ub); or.setCheckKKTSolutionAccuracy(true); // or.setToleranceKKT(1.e-7); // or.setToleranceFeas(1.E-7); // or.setTolerance(1.E-7); or.setDumpProblem(true); //or.setPresolvingDisabled(true); //or.setRescalingDisabled(true); //optimization 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 assertEquals(lb.length, sol.length); assertEquals(ub.length, sol.length); 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); for (int i = 0; i < lb.length; i++) { assertTrue(lb[i] <= x.getEntry(i)); } for (int i = 0; i < ub.length; i++) { double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i]; assertTrue(di <= x.getEntry(i)); } RealVector Gxh = GMatrix.operate(x).subtract(hvector); for (int i = 0; i < Gxh.getDimension(); i++) { double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i]; assertTrue(di >= x.getEntry(i)); } 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()); }
From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java
/** * Problem in the form//from ww w . j ava 2 s . co m * min(c.x) s.t. * G.x < h * A.x = b * lb <= x <= ub * * This is the same as testCGhAb3, but lb and ub are outside G. * The presolved problem has a deterministic solution, that is, all the variables have a fixed value. * Submitted 01/09/2013 by Chris Myers. */ public void testCGhAbLbUb2() throws Exception { log.debug("testCGhAbLbUb2"); String problemId = "2"; 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[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "lb" + problemId + ".txt"); double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "ub" + 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 do 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.setLb(lb); or.setUb(ub); //or.setInitialPoint(new double[] {100000.00000000377, 2000000.0000000752, 100000.00000000095, 2000000.0000000189, 100000.00000000095, 2000000.0000000189, 100000.00000000095, 2000000.0000000189, 100000.00000000095, 2000000.0000000189}); 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 assertEquals(lb.length, sol.length); assertEquals(ub.length, sol.length); 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); for (int i = 0; i < lb.length; i++) { double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i]; assertTrue(di <= x.getEntry(i)); } for (int i = 0; i < ub.length; i++) { double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i]; assertTrue(di >= x.getEntry(i)); } 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], 1.e-7); // } log.debug("expectedvalue : " + expectedvalue); //assertEquals(expectedvalue, value, or.getTolerance()); assertTrue(expectedvalue > value); }
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); }// ww w .j a va 2s.co 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.colocalization3d.correction.PositionCorrector.java
/** * Applies an existing correction to the positions of a set of objects, using a specified reference * and correction channel.//from www . j a v a 2s . c om * * @param imageObjects A Vector containing all the ImageObjects to be corrected. * @param c The Correction object to be used, which could have been generated with determineCorrection, or loaded from disk. * @return A RealVector with one entry per ImageObject, containing the corrected scalar distance between the object in the reference channel and the channel being corrected. */ public RealVector applyCorrection(Correction c, java.util.List<ImageObject> imageObjects) { int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM); int channelToCorrect = this.parameters.getIntValueForKey(CORR_CH_PARAM); RealVector diffs = new ArrayRealVector(imageObjects.size(), 0.0); RealVector averageVectorDiffs = null; for (int i = 0; i < imageObjects.size(); i++) { diffs.setEntry(i, imageObjects.get(i).getScalarDifferenceBetweenChannels(referenceChannel, channelToCorrect, this.pixelToDistanceConversions)); if (i == 0) { averageVectorDiffs = imageObjects.get(i) .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).copy(); } else { averageVectorDiffs = averageVectorDiffs.add(imageObjects.get(i) .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).map(new Abs())); } } averageVectorDiffs.mapDivideToSelf(imageObjects.size()); averageVectorDiffs = averageVectorDiffs.ebeMultiply(this.pixelToDistanceConversions); java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d") .info("mean separation uncorrected = " + diffs.getL1Norm() / diffs.getDimension()); java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d") .info("mean separation components uncorrected = " + averageVectorDiffs.toString()); RealVector newDiffs = new ArrayRealVector(imageObjects.size(), 0.0); if (this.parameters.getBooleanValueForKey("correct_images")) { for (int i = 0; i < imageObjects.size(); i++) { try { newDiffs.setEntry(i, this.correctSingleObjectVectorDifference(c, imageObjects.get(i), referenceChannel, channelToCorrect).getNorm()); imageObjects.get(i).setCorrectionSuccessful(true); } catch (UnableToCorrectException e) { newDiffs.setEntry(i, -1.0 * Double.MAX_VALUE); imageObjects.get(i).setCorrectionSuccessful(false); } } java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d") .info("mean separation corrected = " + newDiffs.getL1Norm() / newDiffs.getDimension()); } else { newDiffs = diffs; } return newDiffs; }
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. *//*from ww w . j av a 2 s. c o 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.correction.PositionCorrector.java
/** * Creates a correction from a set of objects whose positions should be the same in each channel. * * @param imageObjects A Vector containing all the ImageObjects to be used for the correction * or in the order it appears in a multiwavelength image file. * @return A Correction object that can be used to correct the positions of other objects based upon the standards provided. *///from ww w . j a v a 2s . co m public Correction getCorrection(java.util.List<ImageObject> imageObjects) { int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM); int channelToCorrect = this.parameters.getIntValueForKey(CORR_CH_PARAM); if (!this.parameters.hasKeyAndTrue(DET_CORR_PARAM)) { try { return Correction.readFromDisk(FileUtils.getCorrectionFilename(this.parameters)); } catch (java.io.IOException e) { java.util.logging.Logger .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME) .severe("Exception encountered while reading correction from disk: "); e.printStackTrace(); } catch (ClassNotFoundException e) { java.util.logging.Logger .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME) .severe("Exception encountered while reading correction from disk: "); e.printStackTrace(); } return null; } int numberOfPointsToFit = this.parameters.getIntValueForKey(NUM_POINT_PARAM); RealMatrix correctionX = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters); RealMatrix correctionY = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters); RealMatrix correctionZ = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters); RealVector distanceCutoffs = new ArrayRealVector(imageObjects.size(), 0.0); RealVector ones = new ArrayRealVector(numberOfPointsToFit, 1.0); RealVector distancesToObjects = new ArrayRealVector(imageObjects.size(), 0.0); RealMatrix allCorrectionParametersMatrix = new Array2DRowRealMatrix(numberOfPointsToFit, numberOfCorrectionParameters); for (int i = 0; i < imageObjects.size(); i++) { RealVector ithPos = imageObjects.get(i).getPositionForChannel(referenceChannel); for (int j = 0; j < imageObjects.size(); j++) { double d = imageObjects.get(j).getPositionForChannel(referenceChannel).subtract(ithPos).getNorm(); distancesToObjects.setEntry(j, d); } //the sorting becomes a bottleneck once the number of points gets large //reverse comparator so we can use the priority queue and get the max element at the head Comparator<Double> cdReverse = new Comparator<Double>() { public int compare(Double o1, Double o2) { if (o1.equals(o2)) return 0; if (o1 > o2) return -1; return 1; } }; PriorityQueue<Double> pq = new PriorityQueue<Double>(numberOfPointsToFit + 2, cdReverse); double maxElement = Double.MAX_VALUE; for (int p = 0; p < numberOfPointsToFit + 1; p++) { pq.add(distancesToObjects.getEntry(p)); } maxElement = pq.peek(); for (int p = numberOfPointsToFit + 1; p < distancesToObjects.getDimension(); p++) { double value = distancesToObjects.getEntry(p); if (value < maxElement) { pq.poll(); pq.add(value); maxElement = pq.peek(); } } double firstExclude = pq.poll(); double lastDist = pq.poll(); double distanceCutoff = (lastDist + firstExclude) / 2.0; distanceCutoffs.setEntry(i, distanceCutoff); RealVector xPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0); RealVector yPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0); RealVector zPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0); RealMatrix differencesToFit = new Array2DRowRealMatrix(numberOfPointsToFit, imageObjects.get(0).getPositionForChannel(referenceChannel).getDimension()); int toFitCounter = 0; for (int j = 0; j < imageObjects.size(); j++) { if (distancesToObjects.getEntry(j) < distanceCutoff) { xPositionsToFit.setEntry(toFitCounter, imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(0)); yPositionsToFit.setEntry(toFitCounter, imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(1)); zPositionsToFit.setEntry(toFitCounter, imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(2)); differencesToFit.setRowVector(toFitCounter, imageObjects.get(j) .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect)); toFitCounter++; } } RealVector x = xPositionsToFit.mapSubtractToSelf(ithPos.getEntry(0)); RealVector y = yPositionsToFit.mapSubtractToSelf(ithPos.getEntry(1)); allCorrectionParametersMatrix.setColumnVector(0, ones); allCorrectionParametersMatrix.setColumnVector(1, x); allCorrectionParametersMatrix.setColumnVector(2, y); allCorrectionParametersMatrix.setColumnVector(3, x.map(new Power(2))); allCorrectionParametersMatrix.setColumnVector(4, y.map(new Power(2))); allCorrectionParametersMatrix.setColumnVector(5, x.ebeMultiply(y)); DecompositionSolver solver = (new QRDecomposition(allCorrectionParametersMatrix)).getSolver(); RealVector cX = solver.solve(differencesToFit.getColumnVector(0)); RealVector cY = solver.solve(differencesToFit.getColumnVector(1)); RealVector cZ = solver.solve(differencesToFit.getColumnVector(2)); correctionX.setRowVector(i, cX); correctionY.setRowVector(i, cY); correctionZ.setRowVector(i, cZ); } Correction c = new Correction(correctionX, correctionY, correctionZ, distanceCutoffs, imageObjects, referenceChannel, channelToCorrect); return c; }