SimplexSolver.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math4.legacy.optim.linear;

  18. import java.util.ArrayList;
  19. import java.util.List;

  20. import org.apache.commons.math4.legacy.exception.TooManyIterationsException;
  21. import org.apache.commons.math4.legacy.optim.OptimizationData;
  22. import org.apache.commons.math4.legacy.optim.PointValuePair;
  23. import org.apache.commons.math4.core.jdkmath.JdkMath;
  24. import org.apache.commons.numbers.core.Precision;

  25. /**
  26.  * Solves a linear problem using the "Two-Phase Simplex" method.
  27.  * <p>
  28.  * The {@link SimplexSolver} supports the following {@link OptimizationData} data provided
  29.  * as arguments to {@link #optimize(OptimizationData...)}:
  30.  * <ul>
  31.  *   <li>objective function: {@link LinearObjectiveFunction} - mandatory</li>
  32.  *   <li>linear constraints {@link LinearConstraintSet} - mandatory</li>
  33.  *   <li>type of optimization: {@link org.apache.commons.math4.legacy.optim.nonlinear.scalar.GoalType GoalType}
  34.  *    - optional, default: {@link org.apache.commons.math4.legacy.optim.nonlinear.scalar.GoalType#MINIMIZE MINIMIZE}</li>
  35.  *   <li>whether to allow negative values as solution: {@link NonNegativeConstraint} - optional, default: true</li>
  36.  *   <li>pivot selection rule: {@link PivotSelectionRule} - optional, default {@link PivotSelectionRule#DANTZIG}</li>
  37.  *   <li>callback for the best solution: {@link SolutionCallback} - optional</li>
  38.  *   <li>maximum number of iterations: {@link org.apache.commons.math4.legacy.optim.MaxIter} - optional, default: {@link Integer#MAX_VALUE}</li>
  39.  * </ul>
  40.  * <p>
  41.  * <b>Note:</b> Depending on the problem definition, the default convergence criteria
  42.  * may be too strict, resulting in {@link NoFeasibleSolutionException} or
  43.  * {@link TooManyIterationsException}. In such a case it is advised to adjust these
  44.  * criteria with more appropriate values, e.g. relaxing the epsilon value.
  45.  * <p>
  46.  * Default convergence criteria:
  47.  * <ul>
  48.  *   <li>Algorithm convergence: 1e-6</li>
  49.  *   <li>Floating-point comparisons: 10 ulp</li>
  50.  *   <li>Cut-Off value: 1e-10</li>
  51.   * </ul>
  52.  * <p>
  53.  * The cut-off value has been introduced to handle the case of very small pivot elements
  54.  * in the Simplex tableau, as these may lead to numerical instabilities and degeneracy.
  55.  * Potential pivot elements smaller than this value will be treated as if they were zero
  56.  * and are thus not considered by the pivot selection mechanism. The default value is safe
  57.  * for many problems, but may need to be adjusted in case of very small coefficients
  58.  * used in either the {@link LinearConstraint} or {@link LinearObjectiveFunction}.
  59.  *
  60.  * @since 2.0
  61.  */
  62. public class SimplexSolver extends LinearOptimizer {
  63.     /** Default amount of error to accept in floating point comparisons (as ulps). */
  64.     static final int DEFAULT_ULPS = 10;

  65.     /** Default cut-off value. */
  66.     static final double DEFAULT_CUT_OFF = 1e-10;

  67.     /** Default amount of error to accept for algorithm convergence. */
  68.     private static final double DEFAULT_EPSILON = 1.0e-6;

  69.     /** Amount of error to accept for algorithm convergence. */
  70.     private final double epsilon;

  71.     /** Amount of error to accept in floating point comparisons (as ulps). */
  72.     private final int maxUlps;

  73.     /**
  74.      * Cut-off value for entries in the tableau: values smaller than the cut-off
  75.      * are treated as zero to improve numerical stability.
  76.      */
  77.     private final double cutOff;

  78.     /** The pivot selection method to use. */
  79.     private PivotSelectionRule pivotSelection;

  80.     /**
  81.      * The solution callback to access the best solution found so far in case
  82.      * the optimizer fails to find an optimal solution within the iteration limits.
  83.      */
  84.     private SolutionCallback solutionCallback;

  85.     /**
  86.      * Builds a simplex solver with default settings.
  87.      */
  88.     public SimplexSolver() {
  89.         this(DEFAULT_EPSILON, DEFAULT_ULPS, DEFAULT_CUT_OFF);
  90.     }

  91.     /**
  92.      * Builds a simplex solver with a specified accepted amount of error.
  93.      *
  94.      * @param epsilon Amount of error to accept for algorithm convergence.
  95.      */
  96.     public SimplexSolver(final double epsilon) {
  97.         this(epsilon, DEFAULT_ULPS, DEFAULT_CUT_OFF);
  98.     }

  99.     /**
  100.      * Builds a simplex solver with a specified accepted amount of error.
  101.      *
  102.      * @param epsilon Amount of error to accept for algorithm convergence.
  103.      * @param maxUlps Amount of error to accept in floating point comparisons.
  104.      */
  105.     public SimplexSolver(final double epsilon, final int maxUlps) {
  106.         this(epsilon, maxUlps, DEFAULT_CUT_OFF);
  107.     }

  108.     /**
  109.      * Builds a simplex solver with a specified accepted amount of error.
  110.      *
  111.      * @param epsilon Amount of error to accept for algorithm convergence.
  112.      * @param maxUlps Amount of error to accept in floating point comparisons.
  113.      * @param cutOff Values smaller than the cutOff are treated as zero.
  114.      */
  115.     public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff) {
  116.         this.epsilon = epsilon;
  117.         this.maxUlps = maxUlps;
  118.         this.cutOff = cutOff;
  119.         this.pivotSelection = PivotSelectionRule.DANTZIG;
  120.     }

  121.     /**
  122.      * {@inheritDoc}
  123.      *
  124.      * @param optData Optimization data. In addition to those documented in
  125.      * {@link LinearOptimizer#optimize(OptimizationData...)
  126.      * LinearOptimizer}, this method will register the following data:
  127.      * <ul>
  128.      *  <li>{@link SolutionCallback}</li>
  129.      *  <li>{@link PivotSelectionRule}</li>
  130.      * </ul>
  131.      *
  132.      * @return {@inheritDoc}
  133.      * @throws TooManyIterationsException if the maximal number of iterations is exceeded.
  134.      * @throws org.apache.commons.math4.legacy.exception.DimensionMismatchException if the dimension
  135.      * of the constraints does not match the dimension of the objective function
  136.      */
  137.     @Override
  138.     public PointValuePair optimize(OptimizationData... optData)
  139.         throws TooManyIterationsException {
  140.         // Set up base class and perform computation.
  141.         return super.optimize(optData);
  142.     }

  143.     /**
  144.      * {@inheritDoc}
  145.      *
  146.      * @param optData Optimization data.
  147.      * In addition to those documented in
  148.      * {@link LinearOptimizer#parseOptimizationData(OptimizationData[])
  149.      * LinearOptimizer}, this method will register the following data:
  150.      * <ul>
  151.      *  <li>{@link SolutionCallback}</li>
  152.      *  <li>{@link PivotSelectionRule}</li>
  153.      * </ul>
  154.      */
  155.     @Override
  156.     protected void parseOptimizationData(OptimizationData... optData) {
  157.         // Allow base class to register its own data.
  158.         super.parseOptimizationData(optData);

  159.         // reset the callback before parsing
  160.         solutionCallback = null;

  161.         for (OptimizationData data : optData) {
  162.             if (data instanceof SolutionCallback) {
  163.                 solutionCallback = (SolutionCallback) data;
  164.                 continue;
  165.             }
  166.             if (data instanceof PivotSelectionRule) {
  167.                 pivotSelection = (PivotSelectionRule) data;
  168.                 continue;
  169.             }
  170.         }
  171.     }

  172.     /**
  173.      * Returns the column with the most negative coefficient in the objective function row.
  174.      *
  175.      * @param tableau Simple tableau for the problem.
  176.      * @return the column with the most negative coefficient.
  177.      */
  178.     private Integer getPivotColumn(SimplexTableau tableau) {
  179.         double minValue = 0;
  180.         Integer minPos = null;
  181.         for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
  182.             final double entry = tableau.getEntry(0, i);
  183.             // check if the entry is strictly smaller than the current minimum
  184.             // do not use a ulp/epsilon check
  185.             if (entry < minValue) {
  186.                 minValue = entry;
  187.                 minPos = i;

  188.                 // Bland's rule: chose the entering column with the lowest index
  189.                 if (pivotSelection == PivotSelectionRule.BLAND && isValidPivotColumn(tableau, i)) {
  190.                     break;
  191.                 }
  192.             }
  193.         }
  194.         return minPos;
  195.     }

  196.     /**
  197.      * Checks whether the given column is valid pivot column, i.e. will result
  198.      * in a valid pivot row.
  199.      * <p>
  200.      * When applying Bland's rule to select the pivot column, it may happen that
  201.      * there is no corresponding pivot row. This method will check if the selected
  202.      * pivot column will return a valid pivot row.
  203.      *
  204.      * @param tableau simplex tableau for the problem
  205.      * @param col the column to test
  206.      * @return {@code true} if the pivot column is valid, {@code false} otherwise
  207.      */
  208.     private boolean isValidPivotColumn(SimplexTableau tableau, int col) {
  209.         for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
  210.             final double entry = tableau.getEntry(i, col);

  211.             // do the same check as in getPivotRow
  212.             if (Precision.compareTo(entry, 0d, cutOff) > 0) {
  213.                 return true;
  214.             }
  215.         }
  216.         return false;
  217.     }

  218.     /**
  219.      * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
  220.      *
  221.      * @param tableau Simplex tableau for the problem.
  222.      * @param col Column to test the ratio of (see {@link #getPivotColumn(SimplexTableau)}).
  223.      * @return the row with the minimum ratio.
  224.      */
  225.     private Integer getPivotRow(SimplexTableau tableau, final int col) {
  226.         // create a list of all the rows that tie for the lowest score in the minimum ratio test
  227.         List<Integer> minRatioPositions = new ArrayList<>();
  228.         double minRatio = Double.MAX_VALUE;
  229.         for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
  230.             final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
  231.             final double entry = tableau.getEntry(i, col);

  232.             // only consider pivot elements larger than the cutOff threshold
  233.             // selecting others may lead to degeneracy or numerical instabilities
  234.             if (Precision.compareTo(entry, 0d, cutOff) > 0) {
  235.                 final double ratio = JdkMath.abs(rhs / entry);
  236.                 // check if the entry is strictly equal to the current min ratio
  237.                 // do not use a ulp/epsilon check
  238.                 final int cmp = Double.compare(ratio, minRatio);
  239.                 if (cmp == 0) {
  240.                     minRatioPositions.add(i);
  241.                 } else if (cmp < 0) {
  242.                     minRatio = ratio;
  243.                     minRatioPositions.clear();
  244.                     minRatioPositions.add(i);
  245.                 }
  246.             }
  247.         }

  248.         if (minRatioPositions.isEmpty()) {
  249.             return null;
  250.         } else if (minRatioPositions.size() > 1) {
  251.             // there's a degeneracy as indicated by a tie in the minimum ratio test

  252.             // 1. check if there's an artificial variable that can be forced out of the basis
  253.             if (tableau.getNumArtificialVariables() > 0) {
  254.                 for (Integer row : minRatioPositions) {
  255.                     for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
  256.                         int column = i + tableau.getArtificialVariableOffset();
  257.                         final double entry = tableau.getEntry(row, column);
  258.                         if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
  259.                             return row;
  260.                         }
  261.                     }
  262.                 }
  263.             }

  264.             // 2. apply Bland's rule to prevent cycling:
  265.             //    take the row for which the corresponding basic variable has the smallest index
  266.             //
  267.             // see http://www.stanford.edu/class/msande310/blandrule.pdf
  268.             // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)

  269.             Integer minRow = null;
  270.             int minIndex = tableau.getWidth();
  271.             for (Integer row : minRatioPositions) {
  272.                 final int basicVar = tableau.getBasicVariable(row);
  273.                 if (basicVar < minIndex) {
  274.                     minIndex = basicVar;
  275.                     minRow = row;
  276.                 }
  277.             }
  278.             return minRow;
  279.         }
  280.         return minRatioPositions.get(0);
  281.     }

  282.     /**
  283.      * Runs one iteration of the Simplex method on the given model.
  284.      *
  285.      * @param tableau Simple tableau for the problem.
  286.      * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
  287.      * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
  288.      */
  289.     protected void doIteration(final SimplexTableau tableau)
  290.         throws TooManyIterationsException,
  291.                UnboundedSolutionException {

  292.         incrementIterationCount();

  293.         Integer pivotCol = getPivotColumn(tableau);
  294.         Integer pivotRow = getPivotRow(tableau, pivotCol);
  295.         if (pivotRow == null) {
  296.             throw new UnboundedSolutionException();
  297.         }

  298.         tableau.performRowOperations(pivotCol, pivotRow);
  299.     }

  300.     /**
  301.      * Solves Phase 1 of the Simplex method.
  302.      *
  303.      * @param tableau Simple tableau for the problem.
  304.      * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
  305.      * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
  306.      * @throws NoFeasibleSolutionException if there is no feasible solution?
  307.      */
  308.     protected void solvePhase1(final SimplexTableau tableau)
  309.         throws TooManyIterationsException,
  310.                UnboundedSolutionException,
  311.                NoFeasibleSolutionException {

  312.         // make sure we're in Phase 1
  313.         if (tableau.getNumArtificialVariables() == 0) {
  314.             return;
  315.         }

  316.         while (!tableau.isOptimal()) {
  317.             doIteration(tableau);
  318.         }

  319.         // if W is not zero then we have no feasible solution
  320.         if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
  321.             throw new NoFeasibleSolutionException();
  322.         }
  323.     }

  324.     /** {@inheritDoc} */
  325.     @Override
  326.     public PointValuePair doOptimize()
  327.         throws TooManyIterationsException,
  328.                UnboundedSolutionException,
  329.                NoFeasibleSolutionException {

  330.         // reset the tableau to indicate a non-feasible solution in case
  331.         // we do not pass phase 1 successfully
  332.         if (solutionCallback != null) {
  333.             solutionCallback.setTableau(null);
  334.         }

  335.         final SimplexTableau tableau =
  336.             new SimplexTableau(getFunction(),
  337.                                getConstraints(),
  338.                                getGoalType(),
  339.                                isRestrictedToNonNegative(),
  340.                                epsilon,
  341.                                maxUlps);

  342.         solvePhase1(tableau);
  343.         tableau.dropPhase1Objective();

  344.         // after phase 1, we are sure to have a feasible solution
  345.         if (solutionCallback != null) {
  346.             solutionCallback.setTableau(tableau);
  347.         }

  348.         while (!tableau.isOptimal()) {
  349.             doIteration(tableau);
  350.         }

  351.         // check that the solution respects the nonNegative restriction in case
  352.         // the epsilon/cutOff values are too large for the actual linear problem
  353.         // (e.g. with very small constraint coefficients), the solver might actually
  354.         // find a non-valid solution (with negative coefficients).
  355.         final PointValuePair solution = tableau.getSolution();
  356.         if (isRestrictedToNonNegative()) {
  357.             final double[] coeff = solution.getPoint();
  358.             for (int i = 0; i < coeff.length; i++) {
  359.                 if (Precision.compareTo(coeff[i], 0, epsilon) < 0) {
  360.                     throw new NoFeasibleSolutionException();
  361.                 }
  362.             }
  363.         }
  364.         return solution;
  365.     }
  366. }