View Javadoc
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  
18  package org.apache.commons.math3.optimization.linear;
19  
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  import org.apache.commons.math3.exception.MaxCountExceededException;
24  import org.apache.commons.math3.optimization.PointValuePair;
25  import org.apache.commons.math3.util.Precision;
26  
27  
28  /**
29   * Solves a linear problem using the Two-Phase Simplex Method.
30   *
31   * @version $Id: SimplexSolver.java 1524213 2013-09-17 20:32:50Z tn $
32   * @deprecated As of 3.1 (to be removed in 4.0).
33   * @since 2.0
34   */
35  @Deprecated
36  public class SimplexSolver extends AbstractLinearOptimizer {
37  
38      /** Default amount of error to accept for algorithm convergence. */
39      private static final double DEFAULT_EPSILON = 1.0e-6;
40  
41      /** Default amount of error to accept in floating point comparisons (as ulps). */
42      private static final int DEFAULT_ULPS = 10;
43  
44      /** Amount of error to accept for algorithm convergence. */
45      private final double epsilon;
46  
47      /** Amount of error to accept in floating point comparisons (as ulps). */
48      private final int maxUlps;
49  
50      /**
51       * Build a simplex solver with default settings.
52       */
53      public SimplexSolver() {
54          this(DEFAULT_EPSILON, DEFAULT_ULPS);
55      }
56  
57      /**
58       * Build a simplex solver with a specified accepted amount of error
59       * @param epsilon the amount of error to accept for algorithm convergence
60       * @param maxUlps amount of error to accept in floating point comparisons
61       */
62      public SimplexSolver(final double epsilon, final int maxUlps) {
63          this.epsilon = epsilon;
64          this.maxUlps = maxUlps;
65      }
66  
67      /**
68       * Returns the column with the most negative coefficient in the objective function row.
69       * @param tableau simple tableau for the problem
70       * @return column with the most negative coefficient
71       */
72      private Integer getPivotColumn(SimplexTableau tableau) {
73          double minValue = 0;
74          Integer minPos = null;
75          for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
76              final double entry = tableau.getEntry(0, i);
77              // check if the entry is strictly smaller than the current minimum
78              // do not use a ulp/epsilon check
79              if (entry < minValue) {
80                  minValue = entry;
81                  minPos = i;
82              }
83          }
84          return minPos;
85      }
86  
87      /**
88       * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
89       * @param tableau simple tableau for the problem
90       * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
91       * @return row with the minimum ratio
92       */
93      private Integer getPivotRow(SimplexTableau tableau, final int col) {
94          // create a list of all the rows that tie for the lowest score in the minimum ratio test
95          List<Integer> minRatioPositions = new ArrayList<Integer>();
96          double minRatio = Double.MAX_VALUE;
97          for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
98              final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
99              final double entry = tableau.getEntry(i, col);
100 
101             if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
102                 final double ratio = rhs / entry;
103                 // check if the entry is strictly equal to the current min ratio
104                 // do not use a ulp/epsilon check
105                 final int cmp = Double.compare(ratio, minRatio);
106                 if (cmp == 0) {
107                     minRatioPositions.add(i);
108                 } else if (cmp < 0) {
109                     minRatio = ratio;
110                     minRatioPositions = new ArrayList<Integer>();
111                     minRatioPositions.add(i);
112                 }
113             }
114         }
115 
116         if (minRatioPositions.size() == 0) {
117             return null;
118         } else if (minRatioPositions.size() > 1) {
119             // there's a degeneracy as indicated by a tie in the minimum ratio test
120 
121             // 1. check if there's an artificial variable that can be forced out of the basis
122             if (tableau.getNumArtificialVariables() > 0) {
123                 for (Integer row : minRatioPositions) {
124                     for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
125                         int column = i + tableau.getArtificialVariableOffset();
126                         final double entry = tableau.getEntry(row, column);
127                         if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
128                             return row;
129                         }
130                     }
131                 }
132             }
133 
134             // 2. apply Bland's rule to prevent cycling:
135             //    take the row for which the corresponding basic variable has the smallest index
136             //
137             // see http://www.stanford.edu/class/msande310/blandrule.pdf
138             // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
139             //
140             // Additional heuristic: if we did not get a solution after half of maxIterations
141             //                       revert to the simple case of just returning the top-most row
142             // This heuristic is based on empirical data gathered while investigating MATH-828.
143             if (getIterations() < getMaxIterations() / 2) {
144                 Integer minRow = null;
145                 int minIndex = tableau.getWidth();
146                 final int varStart = tableau.getNumObjectiveFunctions();
147                 final int varEnd = tableau.getWidth() - 1;
148                 for (Integer row : minRatioPositions) {
149                     for (int i = varStart; i < varEnd && !row.equals(minRow); i++) {
150                         final Integer basicRow = tableau.getBasicRow(i);
151                         if (basicRow != null && basicRow.equals(row) && i < minIndex) {
152                             minIndex = i;
153                             minRow = row;
154                         }
155                     }
156                 }
157                 return minRow;
158             }
159         }
160         return minRatioPositions.get(0);
161     }
162 
163     /**
164      * Runs one iteration of the Simplex method on the given model.
165      * @param tableau simple tableau for the problem
166      * @throws MaxCountExceededException if the maximal iteration count has been exceeded
167      * @throws UnboundedSolutionException if the model is found not to have a bounded solution
168      */
169     protected void doIteration(final SimplexTableau tableau)
170         throws MaxCountExceededException, UnboundedSolutionException {
171 
172         incrementIterationsCounter();
173 
174         Integer pivotCol = getPivotColumn(tableau);
175         Integer pivotRow = getPivotRow(tableau, pivotCol);
176         if (pivotRow == null) {
177             throw new UnboundedSolutionException();
178         }
179 
180         // set the pivot element to 1
181         double pivotVal = tableau.getEntry(pivotRow, pivotCol);
182         tableau.divideRow(pivotRow, pivotVal);
183 
184         // set the rest of the pivot column to 0
185         for (int i = 0; i < tableau.getHeight(); i++) {
186             if (i != pivotRow) {
187                 final double multiplier = tableau.getEntry(i, pivotCol);
188                 tableau.subtractRow(i, pivotRow, multiplier);
189             }
190         }
191     }
192 
193     /**
194      * Solves Phase 1 of the Simplex method.
195      * @param tableau simple tableau for the problem
196      * @throws MaxCountExceededException if the maximal iteration count has been exceeded
197      * @throws UnboundedSolutionException if the model is found not to have a bounded solution
198      * @throws NoFeasibleSolutionException if there is no feasible solution
199      */
200     protected void solvePhase1(final SimplexTableau tableau)
201         throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {
202 
203         // make sure we're in Phase 1
204         if (tableau.getNumArtificialVariables() == 0) {
205             return;
206         }
207 
208         while (!tableau.isOptimal()) {
209             doIteration(tableau);
210         }
211 
212         // if W is not zero then we have no feasible solution
213         if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
214             throw new NoFeasibleSolutionException();
215         }
216     }
217 
218     /** {@inheritDoc} */
219     @Override
220     public PointValuePair doOptimize()
221         throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {
222         final SimplexTableau tableau =
223             new SimplexTableau(getFunction(),
224                                getConstraints(),
225                                getGoalType(),
226                                restrictToNonNegative(),
227                                epsilon,
228                                maxUlps);
229 
230         solvePhase1(tableau);
231         tableau.dropPhase1Objective();
232 
233         while (!tableau.isOptimal()) {
234             doIteration(tableau);
235         }
236         return tableau.getSolution();
237     }
238 
239 }