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.math3.optimization.linear;

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

  20. import org.apache.commons.math3.exception.MaxCountExceededException;
  21. import org.apache.commons.math3.optimization.PointValuePair;
  22. import org.apache.commons.math3.util.Precision;


  23. /**
  24.  * Solves a linear problem using the Two-Phase Simplex Method.
  25.  *
  26.  * @deprecated As of 3.1 (to be removed in 4.0).
  27.  * @since 2.0
  28.  */
  29. @Deprecated
  30. public class SimplexSolver extends AbstractLinearOptimizer {

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

  33.     /** Default amount of error to accept in floating point comparisons (as ulps). */
  34.     private static final int DEFAULT_ULPS = 10;

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

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

  39.     /**
  40.      * Build a simplex solver with default settings.
  41.      */
  42.     public SimplexSolver() {
  43.         this(DEFAULT_EPSILON, DEFAULT_ULPS);
  44.     }

  45.     /**
  46.      * Build a simplex solver with a specified accepted amount of error
  47.      * @param epsilon the amount of error to accept for algorithm convergence
  48.      * @param maxUlps amount of error to accept in floating point comparisons
  49.      */
  50.     public SimplexSolver(final double epsilon, final int maxUlps) {
  51.         this.epsilon = epsilon;
  52.         this.maxUlps = maxUlps;
  53.     }

  54.     /**
  55.      * Returns the column with the most negative coefficient in the objective function row.
  56.      * @param tableau simple tableau for the problem
  57.      * @return column with the most negative coefficient
  58.      */
  59.     private Integer getPivotColumn(SimplexTableau tableau) {
  60.         double minValue = 0;
  61.         Integer minPos = null;
  62.         for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
  63.             final double entry = tableau.getEntry(0, i);
  64.             // check if the entry is strictly smaller than the current minimum
  65.             // do not use a ulp/epsilon check
  66.             if (entry < minValue) {
  67.                 minValue = entry;
  68.                 minPos = i;
  69.             }
  70.         }
  71.         return minPos;
  72.     }

  73.     /**
  74.      * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
  75.      * @param tableau simple tableau for the problem
  76.      * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
  77.      * @return row with the minimum ratio
  78.      */
  79.     private Integer getPivotRow(SimplexTableau tableau, final int col) {
  80.         // create a list of all the rows that tie for the lowest score in the minimum ratio test
  81.         List<Integer> minRatioPositions = new ArrayList<Integer>();
  82.         double minRatio = Double.MAX_VALUE;
  83.         for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
  84.             final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
  85.             final double entry = tableau.getEntry(i, col);

  86.             if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
  87.                 final double ratio = rhs / entry;
  88.                 // check if the entry is strictly equal to the current min ratio
  89.                 // do not use a ulp/epsilon check
  90.                 final int cmp = Double.compare(ratio, minRatio);
  91.                 if (cmp == 0) {
  92.                     minRatioPositions.add(i);
  93.                 } else if (cmp < 0) {
  94.                     minRatio = ratio;
  95.                     minRatioPositions = new ArrayList<Integer>();
  96.                     minRatioPositions.add(i);
  97.                 }
  98.             }
  99.         }

  100.         if (minRatioPositions.size() == 0) {
  101.             return null;
  102.         } else if (minRatioPositions.size() > 1) {
  103.             // there's a degeneracy as indicated by a tie in the minimum ratio test

  104.             // 1. check if there's an artificial variable that can be forced out of the basis
  105.             if (tableau.getNumArtificialVariables() > 0) {
  106.                 for (Integer row : minRatioPositions) {
  107.                     for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
  108.                         int column = i + tableau.getArtificialVariableOffset();
  109.                         final double entry = tableau.getEntry(row, column);
  110.                         if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
  111.                             return row;
  112.                         }
  113.                     }
  114.                 }
  115.             }

  116.             // 2. apply Bland's rule to prevent cycling:
  117.             //    take the row for which the corresponding basic variable has the smallest index
  118.             //
  119.             // see http://www.stanford.edu/class/msande310/blandrule.pdf
  120.             // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
  121.             //
  122.             // Additional heuristic: if we did not get a solution after half of maxIterations
  123.             //                       revert to the simple case of just returning the top-most row
  124.             // This heuristic is based on empirical data gathered while investigating MATH-828.
  125.             if (getIterations() < getMaxIterations() / 2) {
  126.                 Integer minRow = null;
  127.                 int minIndex = tableau.getWidth();
  128.                 final int varStart = tableau.getNumObjectiveFunctions();
  129.                 final int varEnd = tableau.getWidth() - 1;
  130.                 for (Integer row : minRatioPositions) {
  131.                     for (int i = varStart; i < varEnd && !row.equals(minRow); i++) {
  132.                         final Integer basicRow = tableau.getBasicRow(i);
  133.                         if (basicRow != null && basicRow.equals(row) && i < minIndex) {
  134.                             minIndex = i;
  135.                             minRow = row;
  136.                         }
  137.                     }
  138.                 }
  139.                 return minRow;
  140.             }
  141.         }
  142.         return minRatioPositions.get(0);
  143.     }

  144.     /**
  145.      * Runs one iteration of the Simplex method on the given model.
  146.      * @param tableau simple tableau for the problem
  147.      * @throws MaxCountExceededException if the maximal iteration count has been exceeded
  148.      * @throws UnboundedSolutionException if the model is found not to have a bounded solution
  149.      */
  150.     protected void doIteration(final SimplexTableau tableau)
  151.         throws MaxCountExceededException, UnboundedSolutionException {

  152.         incrementIterationsCounter();

  153.         Integer pivotCol = getPivotColumn(tableau);
  154.         Integer pivotRow = getPivotRow(tableau, pivotCol);
  155.         if (pivotRow == null) {
  156.             throw new UnboundedSolutionException();
  157.         }

  158.         // set the pivot element to 1
  159.         double pivotVal = tableau.getEntry(pivotRow, pivotCol);
  160.         tableau.divideRow(pivotRow, pivotVal);

  161.         // set the rest of the pivot column to 0
  162.         for (int i = 0; i < tableau.getHeight(); i++) {
  163.             if (i != pivotRow) {
  164.                 final double multiplier = tableau.getEntry(i, pivotCol);
  165.                 tableau.subtractRow(i, pivotRow, multiplier);
  166.             }
  167.         }
  168.     }

  169.     /**
  170.      * Solves Phase 1 of the Simplex method.
  171.      * @param tableau simple tableau for the problem
  172.      * @throws MaxCountExceededException if the maximal iteration count has been exceeded
  173.      * @throws UnboundedSolutionException if the model is found not to have a bounded solution
  174.      * @throws NoFeasibleSolutionException if there is no feasible solution
  175.      */
  176.     protected void solvePhase1(final SimplexTableau tableau)
  177.         throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

  178.         // make sure we're in Phase 1
  179.         if (tableau.getNumArtificialVariables() == 0) {
  180.             return;
  181.         }

  182.         while (!tableau.isOptimal()) {
  183.             doIteration(tableau);
  184.         }

  185.         // if W is not zero then we have no feasible solution
  186.         if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
  187.             throw new NoFeasibleSolutionException();
  188.         }
  189.     }

  190.     /** {@inheritDoc} */
  191.     @Override
  192.     public PointValuePair doOptimize()
  193.         throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {
  194.         final SimplexTableau tableau =
  195.             new SimplexTableau(getFunction(),
  196.                                getConstraints(),
  197.                                getGoalType(),
  198.                                restrictToNonNegative(),
  199.                                epsilon,
  200.                                maxUlps);

  201.         solvePhase1(tableau);
  202.         tableau.dropPhase1Objective();

  203.         while (!tableau.isOptimal()) {
  204.             doIteration(tableau);
  205.         }
  206.         return tableau.getSolution();
  207.     }

  208. }