Example usage for org.apache.commons.math3.linear RealMatrix operate

List of usage examples for org.apache.commons.math3.linear RealMatrix operate

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealMatrix operate.

Prototype

RealVector operate(RealVector v) throws DimensionMismatchException;

Source Link

Document

Returns the result of multiplying this by the vector v .

Usage

From source file:com.joptimizer.optimizers.JOptimizerTest.java

/**
 * Quadratic objective, no constraints./* w w  w.  j a  v  a2  s  .  c  o m*/
 */
public void testNewtownUnconstrained() throws Exception {
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "testNewtownUnconstrained");
    RealMatrix PMatrix = new Array2DRowRealMatrix(
            new double[][] { { 1.68, 0.34, 0.38 }, { 0.34, 3.09, -1.59 }, { 0.38, -1.59, 1.54 } });
    RealVector qVector = new ArrayRealVector(new double[] { 0.018, 0.025, 0.01 });

    // Objective function.
    double theta = 0.01522;
    RealMatrix P = PMatrix.scalarMultiply(theta);
    RealVector q = qVector.mapMultiply(-1);
    PDQuadraticMultivariateRealFunction objectiveFunction = new PDQuadraticMultivariateRealFunction(P.getData(),
            q.toArray(), 0);

    OptimizationRequest or = new OptimizationRequest();
    or.setF0(objectiveFunction);
    or.setInitialPoint(new double[] { 0.04, 0.50, 0.46 });

    //optimization
    JOptimizer opt = new JOptimizer();
    opt.setOptimizationRequest(or);
    int returnCode = opt.optimize();

    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }

    OptimizationResponse response = opt.getOptimizationResponse();
    double[] sol = response.getSolution();
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "sol   : " + ArrayUtils.toString(sol));
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "value : " + objectiveFunction.value(sol));

    // we already know the analytic solution of the problem
    // sol = -invQ * C
    RealMatrix QInv = Utils.squareMatrixInverse(P);
    RealVector benchSol = QInv.operate(q).mapMultiply(-1);
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchSol   : " + ArrayUtils.toString(benchSol.toArray()));
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchValue : " + objectiveFunction.value(benchSol.toArray()));

    assertEquals(benchSol.getEntry(0), sol[0], 0.000000000000001);
    assertEquals(benchSol.getEntry(1), sol[1], 0.000000000000001);
    assertEquals(benchSol.getEntry(2), sol[2], 0.000000000000001);
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Problem in the form/*ww w .j  ava  2s  .  c  o  m*/
 * 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/*from  w w  w.  jav  a  2  s . c om*/
 * min(c.x) s.t.
 * A.x = b
 * lb <= x <= ub
 * 
 * This problem involves recursive column duplicate reductions.
 * This is a good for testing with a small size problem.
 */
public void testCAbLbUb5() throws Exception {
    log.debug("testCAbLbUb5");

    String problemId = "5";

    log.debug("problemId: " + problemId);
    double[] c = Utils.loadDoubleArrayFromFile("lp" + File.separator + "c" + 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];

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    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);

    //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 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 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//from  ww w. j av  a 2  s .  com
 * min(c.x) s.t.
 * A.x = b
 * lb <= x <= ub
 * 
 * This problem involves column duplicate reduction.
 * This is a good for testing with a small size problem.
 */
public void testCAbLbUb6() throws Exception {
    log.debug("testCAbLbUb6");

    String problemId = "6";

    log.debug("problemId: " + problemId);
    double[] c = Utils.loadDoubleArrayFromFile("lp" + File.separator + "c" + 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];

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    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);

    //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 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 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//from  www . j av a2 s .  c o m
 * min(c.x) s.t.
 * A.x = b
 * lb <= x <= ub
 */
public void testCAbLbUb8() throws Exception {
    log.debug("testCAbLbUb8");

    String problemId = "8";

    log.debug("problemId: " + problemId);
    double[] c = Utils.loadDoubleArrayFromFile("lp" + File.separator + "c" + 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.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.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 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 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/*  www  . j a  va2  s . com*/
 * 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/*from  www  .  j a  v a2s.co  m*/
 * 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//  www  . j av a 2s.  c  o  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:edu.oregonstate.eecs.mcplan.ml.InformationTheoreticMetricLearner.java

/**
 * Execute the algorithm.//www  .  ja  v  a 2 s  . co  m
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    System.out.println("\tITML run()");

    final RealMatrix A = A0_.copy();
    final int[] idx = Fn.range(0, Nc_);

    int iter_count = 0;
    final int logging_interval = 1;
    double cumulative_update = 0.0;
    while (iter_count++ < iteration_limit_) {
        if (iter_count % logging_interval == 0) {
            System.out.println("\tIteration " + iter_count);
        }
        Fn.shuffle(rng_, idx);
        double update_magnitude = 0.0;
        for (int c = 0; c < Nc_; ++c) {
            final int[] constraint;
            final RealVector xdiff;
            final int delta;
            if (c < S_.size()) {
                //               constraint = S_.get( c );
                xdiff = new ArrayRealVector(S_.get(c));
                delta = 1;
            } else {
                //               constraint = D_.get( c - S_.size() );
                xdiff = new ArrayRealVector(D_.get(c - S_.size()));
                delta = -1;
            }

            //            final int i = constraint[0];
            //            final int j = constraint[1];
            //            final RealVector xdiff = X_.get( i ).subtract( X_.get( j ) );
            //            final double p = xdiff.dotProduct( A.operate( xdiff ) );

            //            if( p == 0.0 ) {
            //               System.out.println( "! p == 0.0" );
            //            }
            //            if( xi_[c] == 0.0 ) {
            //               System.out.println( "! xi_[c] == 0.0" );
            //            }

            final double p = HilbertSpace.inner_prod(xdiff, A, xdiff);

            final double alpha;
            if (p == 0.0) {
                alpha = lambda_[c];
            } else {
                alpha = Math.min(lambda_[c], (delta / 2.0) * ((1.0 / p) - (gamma_ / xi_[c])));
            }
            final double beta = (delta * alpha) / (1 - delta * alpha * p);
            xi_[c] = (gamma_ * xi_[c]) / (gamma_ + delta * alpha * xi_[c]);
            lambda_[c] -= alpha;
            // This implements: A += beta * A xdiff xdiff^T A
            final RealVector Ax = A.operate(xdiff);
            //            final RealMatrix outer_prod = Ax.outerProduct( Ax );
            for (int row = 0; row < A.getRowDimension(); ++row) {
                final double axi = Ax.getEntry(row);
                for (int col = 0; col < A.getColumnDimension(); ++col) {
                    final double a = axi * Ax.getEntry(col);
                    A.addToEntry(row, col, a * beta);
                }
            }
            //            final RealMatrix outer_prod = xdiff.outerProduct( xdiff );
            //            final RealMatrix update = A.multiply( outer_prod ).multiply( A ).scalarMultiply( beta );
            //            A = A.add( update );
            update_magnitude += alpha * alpha; //update.getFrobeniusNorm();
        }
        cumulative_update += update_magnitude;
        if (iter_count % logging_interval == 0) {
            System.out.println("\tupdate = " + (cumulative_update / logging_interval));
            cumulative_update = 0.0;
        }
        // Declare convergence if all updates were small.
        if (Math.sqrt(update_magnitude) < convergence_tolerance_) {
            break;
        }
    }

    A_ = A;
    //      A_ = MatrixAlgorithms.makePositiveDefinite( A, 1e-4 );

    //      System.out.println( "Metric:" );
    //      for( int i = 0; i < A_.getRowDimension(); ++i ) {
    //         System.out.println( A_.getRowVector( i ) );
    //      }

    // Check for positive-definiteness
    //      final EigenDecomposition eig = new EigenDecomposition( A_ );
    //      final double det = eig.getDeterminant();
    //      assert( det > 0.0 );
}

From source file:com.joptimizer.optimizers.LPPresolver.java

/**
 * This method is just for testing scope.
 *//*from   w w w.  ja va2  s . c  om*/
private void checkProgress(DoubleMatrix1D c, DoubleMatrix2D A, DoubleMatrix1D b, DoubleMatrix1D lb,
        DoubleMatrix1D ub, DoubleMatrix1D ylb, DoubleMatrix1D yub, DoubleMatrix1D zlb, DoubleMatrix1D zub) {

    if (this.expectedSolution == null) {
        return;
    }

    if (Double.isNaN(this.expectedTolerance)) {
        //for this to work properly, this method must be called at least one time before presolving operations start
        RealVector X = MatrixUtils.createRealVector(expectedSolution);
        RealMatrix AMatrix = MatrixUtils.createRealMatrix(A.toArray());
        RealVector Bvector = MatrixUtils.createRealVector(b.toArray());
        RealVector Axb = AMatrix.operate(X).subtract(Bvector);
        double norm = Axb.getNorm();
        this.expectedTolerance = Math.max(1.e-7, 1.5 * norm);
    }

    double tolerance = this.expectedTolerance;
    log.debug("tolerance: " + tolerance);

    RealVector X = MatrixUtils.createRealVector(expectedSolution);
    RealMatrix AMatrix = MatrixUtils.createRealMatrix(A.toArray());
    RealVector Bvector = MatrixUtils.createRealVector(b.toArray());
    //logger.debug("A.X-b: " + ArrayUtils.toString(originalA.operate(X).subtract(originalB)));

    //nz rows
    for (int i = 0; i < vRowPositions.length; i++) {
        short[] vRowPositionsI = vRowPositions[i];
        for (short nzJ : vRowPositionsI) {
            if (Double.compare(A.getQuick(i, nzJ), 0.) == 0) {
                log.debug("entry " + i + "," + nzJ + " est zero: " + A.getQuick(i, nzJ));
                throw new IllegalStateException();
            }
        }
    }

    //nz columns
    for (int j = 0; j < vColPositions.length; j++) {
        short[] vColPositionsJ = vColPositions[j];
        for (short nzI : vColPositionsJ) {
            if (Double.compare(A.getQuick(nzI, j), 0.) == 0) {
                log.debug("entry (" + nzI + "," + j + ") est zero: " + A.getQuick(nzI, j));
                throw new IllegalStateException();
            }
        }
    }

    //nz Aij
    for (int i = 0; i < A.rows(); i++) {
        short[] vRowPositionsI = vRowPositions[i];
        for (int j = 0; j < A.columns(); j++) {
            if (Double.compare(Math.abs(A.getQuick(i, j)), 0.) != 0) {
                if (!ArrayUtils.contains(vRowPositionsI, (short) j)) {
                    log.debug("entry " + i + "," + j + " est non-zero: " + A.getQuick(i, j));
                    throw new IllegalStateException();
                }
                if (!ArrayUtils.contains(vColPositions[j], (short) i)) {
                    log.debug("entry " + i + "," + j + " est non-zero: " + A.getQuick(i, j));
                    throw new IllegalStateException();
                }
            }
        }
    }

    //      //boolean deepCheckA = true;
    //      boolean deepCheckA = false;
    //      if(deepCheckA){
    //         //check for 0-rows
    //         List<Integer> zeroRows = new ArrayList<Integer>();
    //         for(int i=0; i<A.rows(); i++){
    //            boolean isNotZero = false;
    //            for(int j=0;!isNotZero && j<A.columns(); j++){
    //               isNotZero = Double.compare(0., A.getQuick(i, j))!=0;
    //            }
    //            if(!isNotZero){
    //               zeroRows.add(zeroRows.size(), i);
    //            }
    //         }
    //         if(!zeroRows.isEmpty()){
    //            log.debug("All 0 entries in rows " + ArrayUtils.toString(zeroRows));
    //            //log.debug(ArrayUtils.toString(A.toArray()));
    //            throw new IllegalStateException();
    //         }
    //         
    //         //check for 0-columns
    //         List<Integer> zeroCols = new ArrayList<Integer>();
    //         for(int j=0; j<A.columns(); j++){
    //            boolean isNotZero = false;
    //            for(int i=0;!isNotZero && i<A.rows(); i++){
    //               isNotZero = Double.compare(0., A.getQuick(i, j))!=0;
    //            }
    //            if(!isNotZero){
    //               zeroCols.add(zeroCols.size(), j);
    //            }
    //         }
    //         if(!zeroCols.isEmpty()){
    //            log.debug("All 0 entries in columns " + ArrayUtils.toString(zeroCols));
    //            //log.debug(ArrayUtils.toString(A.toArray()));
    //            throw new IllegalStateException();
    //         }
    //         
    //         // check rank(A): must be A pXn with rank(A)=p < n
    //         QRSparseFactorization qr = null;
    //         boolean factOK = true;
    //         try{
    //            qr = new QRSparseFactorization((SparseDoubleMatrix2D)A);
    //            qr.factorize();
    //         }catch(Exception e){
    //            factOK = false;
    //            log.warn("Warning", e);
    //         }
    //         if(factOK){
    //            log.debug("p        : " + AMatrix.getRowDimension());
    //            log.debug("n        : " + AMatrix.getColumnDimension());
    //            log.debug("full rank: " + qr.hasFullRank());
    //            if(!(A.rows() < A.columns())){
    //               log.debug("!( p < n )");
    //               throw new IllegalStateException();
    //            }
    //            if(!qr.hasFullRank()){
    //               log.debug("not full rank A matrix");
    //               throw new IllegalStateException();
    //            }
    //         }
    //      }

    //A.x = b
    RealVector Axb = AMatrix.operate(X).subtract(Bvector);
    double norm = Axb.getNorm();
    log.debug("|| A.x-b ||: " + norm);
    if (norm > tolerance) {
        //where is the error?
        for (int i = 0; i < Axb.getDimension(); i++) {
            if (Math.abs(Axb.getEntry(i)) > tolerance) {
                log.debug("entry " + i + ": " + Axb.getEntry(i));
                throw new IllegalStateException();
            }
        }
        throw new IllegalStateException();
    }

    //upper e lower
    for (int i = 0; i < X.getDimension(); i++) {
        if (X.getEntry(i) + tolerance < lb.getQuick(i)) {
            log.debug("lower bound " + i + " not respected: lb=" + lb.getQuick(i) + ", value=" + X.getEntry(i));
            throw new IllegalStateException();
        }
        if (X.getEntry(i) > ub.getQuick(i) + tolerance) {
            log.debug("upper bound " + i + " not respected: ub=" + ub.getQuick(i) + ", value=" + X.getEntry(i));
            throw new IllegalStateException();
        }
    }
}