Example usage for org.apache.commons.math3.optimization.linear SimplexSolver SimplexSolver

List of usage examples for org.apache.commons.math3.optimization.linear SimplexSolver SimplexSolver

Introduction

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

Prototype

public SimplexSolver() 

Source Link

Document

Build a simplex solver with default settings.

Usage

From source file:eu.smartenit.sbox.eca.ReferenceVectorCalculator.java

/**
 * Calculates the reference vector using simplex method.
 * //from  w  w  w. j  av a2 s  . c o  m
 * @param S1 The DC traffic manipulation freedom 
 * @param S2 The DC traffic manipulation freedom 
 * @param aList The list of candidate areas
 * @param sourceAsNumber The number of the source AS
 * @return Returns an RVector containing the reference vector values.
 */
private LocalRVector calculateReferenceVector(double[] S1, double[] S2, List<Area> aList, int sourceAsNumber) {
    List<PointValuePair> solutionList = new ArrayList<PointValuePair>();
    for (Area a : aList) {

        Long x1Lower = a.getD1().getLowerBound(); // Corresponds to alpha1i
        Long x1Upper = a.getD1().getUpperBound(); // Corresponds to alpha1i+1
        Long x2Lower = a.getD2().getLowerBound(); // Corresponds to alpha2i
        Long x2Upper = a.getD2().getUpperBound(); // Corresponds to alpha2i+1

        Segment segment1 = costFunctionMap1.get(x1Lower); // Corresponds to the suitable cf segment for alpha1
        Segment segment2 = costFunctionMap2.get(x2Lower); // Corresponds to the suitable cf segment for alpha2

        // Function    f:  f1(x1) + f2(x2) + c //c corresponds to the sum of the constant part of f1 and f2
        // Constraints c1: x1       >  alpha1i
        //             c2: x1       <= alpha1i+1 
        //             c3:      x2  >  alpha2j
        //             c4:      x2  <= alpha2j+1
        //             c5: x1 + x2  == X_V[x1] + X_V[x2]
        //            c6: x1       >= X_V[x1] + S1[x1]
        //             c7: x1       <= X_V[x1] + S2[x1]
        //             c8: x2       >= X_V[x2] + S2[x2]
        //              c9: x2       <= X_V[x2] + S1[x2]

        LinearObjectiveFunction f = new LinearObjectiveFunction(
                new double[] { segment1.getB(), segment2.getB() }, (segment1.getA() + segment2.getA())); //f1(x1) + f2(x2)
        Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, x1Lower.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, x1Upper.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, x2Lower.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, x2Upper.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, X_V[x1] + X_V[x2]));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, X_V[x1] + S1[x1]));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, X_V[x1] + S2[x1]));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, X_V[x2] + S2[x2]));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, X_V[x2] + S1[x2]));

        try {
            PointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true);
            solutionList.add(solution);

            double x = solution.getPoint()[0];
            double y = solution.getPoint()[1];
            double value = solution.getValue();
            logger.info("\n");
            logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]");
            logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + "
                    + (segment1.getA() + segment2.getA()));
            logger.info("Reference vector x1=" + x + " x2=" + y + " f1(x1) + f2(x2)=" + value);
        } catch (NoFeasibleSolutionException e) {
            logger.info("\n");
            logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]");
            logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + "
                    + (segment1.getA() + segment2.getA()));
            logger.error("No feasible solution found: for area " + a);
        }

    }

    PointValuePair minimalSolution = getMinimalSolution(solutionList);
    LocalRVector referenceVector = constructReferenceVector(minimalSolution, sourceAsNumber);

    logger.info("Chosen reference vector: " + referenceVector.getVectorValues().get(0).getValue() + " "
            + referenceVector.getVectorValues().get(1).getValue());

    return referenceVector;
}

From source file:edu.byu.nlp.util.Matrices.java

/**
 * Finds an ordering that minimizes the passed-in loss function.
 * Formulates the problem as an instance of the 'assignment problem' 
 * and solves using a linear solver.//from w w w .j  av  a  2 s  .c  o  m
 * 
 * @param lossfunction takes as an argument a matrix row, and outputs the 
 * loss associated 
 * 
 * @return a vectors of new row assignments. For example, [0,1,2,3] indicate the trivial re-ordering. 
 */
public static int[] getRowReordering(double[][] mat, RowReorderingLossFunction lossFunction) {
    // In the assignment problem formulation, there will be one variable associated with 
    // each possible row->dst assignment. We calculate the coefficient of each of 
    // these using the passed-in loss function. Our coefficients are therefore a 
    // vectorized form of the loss matrix.
    int n = mat.length;
    double[] objCoeff = new double[n * n];
    for (int src = 0; src < n; src++) {
        for (int dst = 0; dst < n; dst++) {
            double loss = lossFunction.rowAssignmentLoss(mat[src], dst);
            objCoeff[n * src + dst] = loss;
            if (Double.isInfinite(loss) || Double.isNaN(loss)) {
                throw new IllegalArgumentException("loss function returned an invalid number (" + loss + ") "
                        + "when asked to consider \n\trow " + DoubleArrays.toString(mat[src])
                        + " \n\tin position " + dst);
            }
        }
    }

    // objective function
    double offset = 0;
    LinearObjectiveFunction f = new LinearObjectiveFunction(objCoeff, offset);

    // constraints
    Collection<LinearConstraint> constraints = Lists.newArrayList();
    // each src must have exactly one dst 
    for (int src = 0; src < n; src++) {
        double[] constCoeff = DoubleArrays.of(0, n * n);
        Arrays.fill(constCoeff, n * src, n * (src + 1), 1); // single row of 1s
        constraints.add(new LinearConstraint(constCoeff, Relationship.EQ, 1));
    }
    // each dst must have exactly one src
    for (int dst = 0; dst < n; dst++) {
        double[] constCoeff = DoubleArrays.of(0, n * n);
        for (int src = 0; src < n; src++) {
            constCoeff[n * src + dst] = 1; // single col of 1s
        }
        constraints.add(new LinearConstraint(constCoeff, Relationship.EQ, 1));
    }

    // solve
    boolean restrictToNonNegative = true;
    SimplexSolver solver = new SimplexSolver();
    solver.setMaxIterations(10000);
    PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, restrictToNonNegative);
    double[] assignmentMatrix = solution.getPoint();

    // the assignment matrix should be very simple; each x is either 0 or 1, 
    // and there is a single 1 per row and column
    // we can deterministically convert this to an int[]
    int[] result = new int[n];
    for (int src = 0; src < n; src++) {
        int rowNonZeroCount = 0;
        for (int dst = 0; dst < n; dst++) {
            double val = assignmentMatrix[n * src + dst];
            if (Math.abs(val - 1) < 1e-6) {
                result[src] = dst;
                rowNonZeroCount++;
            }
        }
        if (rowNonZeroCount != 1) {
            throw new IllegalStateException(
                    "The assignment problem linear solver returned an assignment matrix with "
                            + "invalid entries. This should never happen! Here is the matrix encoded as a vector "
                            + "with rows of length " + n + ":\n\t" + DoubleArrays.toString(assignmentMatrix));
        }
    }
    return result;
}