001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.optim.linear;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.math3.exception.TooManyIterationsException;
023import org.apache.commons.math3.optim.OptimizationData;
024import org.apache.commons.math3.optim.PointValuePair;
025import org.apache.commons.math3.util.FastMath;
026import org.apache.commons.math3.util.Precision;
027
028/**
029 * Solves a linear problem using the "Two-Phase Simplex" method.
030 * <p>
031 * The {@link SimplexSolver} supports the following {@link OptimizationData} data provided
032 * as arguments to {@link #optimize(OptimizationData...)}:
033 * <ul>
034 *   <li>objective function: {@link LinearObjectiveFunction} - mandatory</li>
035 *   <li>linear constraints {@link LinearConstraintSet} - mandatory</li>
036 *   <li>type of optimization: {@link org.apache.commons.math3.optim.nonlinear.scalar.GoalType GoalType}
037 *    - optional, default: {@link org.apache.commons.math3.optim.nonlinear.scalar.GoalType#MINIMIZE MINIMIZE}</li>
038 *   <li>whether to allow negative values as solution: {@link NonNegativeConstraint} - optional, default: true</li>
039 *   <li>pivot selection rule: {@link PivotSelectionRule} - optional, default {@link PivotSelectionRule#DANTZIG}</li>
040 *   <li>callback for the best solution: {@link SolutionCallback} - optional</li>
041 *   <li>maximum number of iterations: {@link org.apache.commons.math3.optim.MaxIter} - optional, default: {@link Integer#MAX_VALUE}</li>
042 * </ul>
043 * <p>
044 * <b>Note:</b> Depending on the problem definition, the default convergence criteria
045 * may be too strict, resulting in {@link NoFeasibleSolutionException} or
046 * {@link TooManyIterationsException}. In such a case it is advised to adjust these
047 * criteria with more appropriate values, e.g. relaxing the epsilon value.
048 * <p>
049 * Default convergence criteria:
050 * <ul>
051 *   <li>Algorithm convergence: 1e-6</li>
052 *   <li>Floating-point comparisons: 10 ulp</li>
053 *   <li>Cut-Off value: 1e-10</li>
054  * </ul>
055 * <p>
056 * The cut-off value has been introduced to handle the case of very small pivot elements
057 * in the Simplex tableau, as these may lead to numerical instabilities and degeneracy.
058 * Potential pivot elements smaller than this value will be treated as if they were zero
059 * and are thus not considered by the pivot selection mechanism. The default value is safe
060 * for many problems, but may need to be adjusted in case of very small coefficients
061 * used in either the {@link LinearConstraint} or {@link LinearObjectiveFunction}.
062 *
063 * @since 2.0
064 */
065public class SimplexSolver extends LinearOptimizer {
066    /** Default amount of error to accept in floating point comparisons (as ulps). */
067    static final int DEFAULT_ULPS = 10;
068
069    /** Default cut-off value. */
070    static final double DEFAULT_CUT_OFF = 1e-10;
071
072    /** Default amount of error to accept for algorithm convergence. */
073    private static final double DEFAULT_EPSILON = 1.0e-6;
074
075    /** Amount of error to accept for algorithm convergence. */
076    private final double epsilon;
077
078    /** Amount of error to accept in floating point comparisons (as ulps). */
079    private final int maxUlps;
080
081    /**
082     * Cut-off value for entries in the tableau: values smaller than the cut-off
083     * are treated as zero to improve numerical stability.
084     */
085    private final double cutOff;
086
087    /** The pivot selection method to use. */
088    private PivotSelectionRule pivotSelection;
089
090    /**
091     * The solution callback to access the best solution found so far in case
092     * the optimizer fails to find an optimal solution within the iteration limits.
093     */
094    private SolutionCallback solutionCallback;
095
096    /**
097     * Builds a simplex solver with default settings.
098     */
099    public SimplexSolver() {
100        this(DEFAULT_EPSILON, DEFAULT_ULPS, DEFAULT_CUT_OFF);
101    }
102
103    /**
104     * Builds a simplex solver with a specified accepted amount of error.
105     *
106     * @param epsilon Amount of error to accept for algorithm convergence.
107     */
108    public SimplexSolver(final double epsilon) {
109        this(epsilon, DEFAULT_ULPS, DEFAULT_CUT_OFF);
110    }
111
112    /**
113     * Builds a simplex solver with a specified accepted amount of error.
114     *
115     * @param epsilon Amount of error to accept for algorithm convergence.
116     * @param maxUlps Amount of error to accept in floating point comparisons.
117     */
118    public SimplexSolver(final double epsilon, final int maxUlps) {
119        this(epsilon, maxUlps, DEFAULT_CUT_OFF);
120    }
121
122    /**
123     * Builds a simplex solver with a specified accepted amount of error.
124     *
125     * @param epsilon Amount of error to accept for algorithm convergence.
126     * @param maxUlps Amount of error to accept in floating point comparisons.
127     * @param cutOff Values smaller than the cutOff are treated as zero.
128     */
129    public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff) {
130        this.epsilon = epsilon;
131        this.maxUlps = maxUlps;
132        this.cutOff = cutOff;
133        this.pivotSelection = PivotSelectionRule.DANTZIG;
134    }
135
136    /**
137     * {@inheritDoc}
138     *
139     * @param optData Optimization data. In addition to those documented in
140     * {@link LinearOptimizer#optimize(OptimizationData...)
141     * LinearOptimizer}, this method will register the following data:
142     * <ul>
143     *  <li>{@link SolutionCallback}</li>
144     *  <li>{@link PivotSelectionRule}</li>
145     * </ul>
146     *
147     * @return {@inheritDoc}
148     * @throws TooManyIterationsException if the maximal number of iterations is exceeded.
149     */
150    @Override
151    public PointValuePair optimize(OptimizationData... optData)
152        throws TooManyIterationsException {
153        // Set up base class and perform computation.
154        return super.optimize(optData);
155    }
156
157    /**
158     * {@inheritDoc}
159     *
160     * @param optData Optimization data.
161     * In addition to those documented in
162     * {@link LinearOptimizer#parseOptimizationData(OptimizationData[])
163     * LinearOptimizer}, this method will register the following data:
164     * <ul>
165     *  <li>{@link SolutionCallback}</li>
166     *  <li>{@link PivotSelectionRule}</li>
167     * </ul>
168     */
169    @Override
170    protected void parseOptimizationData(OptimizationData... optData) {
171        // Allow base class to register its own data.
172        super.parseOptimizationData(optData);
173
174        // reset the callback before parsing
175        solutionCallback = null;
176
177        for (OptimizationData data : optData) {
178            if (data instanceof SolutionCallback) {
179                solutionCallback = (SolutionCallback) data;
180                continue;
181            }
182            if (data instanceof PivotSelectionRule) {
183                pivotSelection = (PivotSelectionRule) data;
184                continue;
185            }
186        }
187    }
188
189    /**
190     * Returns the column with the most negative coefficient in the objective function row.
191     *
192     * @param tableau Simple tableau for the problem.
193     * @return the column with the most negative coefficient.
194     */
195    private Integer getPivotColumn(SimplexTableau tableau) {
196        double minValue = 0;
197        Integer minPos = null;
198        for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
199            final double entry = tableau.getEntry(0, i);
200            // check if the entry is strictly smaller than the current minimum
201            // do not use a ulp/epsilon check
202            if (entry < minValue) {
203                minValue = entry;
204                minPos = i;
205
206                // Bland's rule: chose the entering column with the lowest index
207                if (pivotSelection == PivotSelectionRule.BLAND && isValidPivotColumn(tableau, i)) {
208                    break;
209                }
210            }
211        }
212        return minPos;
213    }
214
215    /**
216     * Checks whether the given column is valid pivot column, i.e. will result
217     * in a valid pivot row.
218     * <p>
219     * When applying Bland's rule to select the pivot column, it may happen that
220     * there is no corresponding pivot row. This method will check if the selected
221     * pivot column will return a valid pivot row.
222     *
223     * @param tableau simplex tableau for the problem
224     * @param col the column to test
225     * @return {@code true} if the pivot column is valid, {@code false} otherwise
226     */
227    private boolean isValidPivotColumn(SimplexTableau tableau, int col) {
228        for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
229            final double entry = tableau.getEntry(i, col);
230
231            // do the same check as in getPivotRow
232            if (Precision.compareTo(entry, 0d, cutOff) > 0) {
233                return true;
234            }
235        }
236        return false;
237    }
238
239    /**
240     * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
241     *
242     * @param tableau Simplex tableau for the problem.
243     * @param col Column to test the ratio of (see {@link #getPivotColumn(SimplexTableau)}).
244     * @return the row with the minimum ratio.
245     */
246    private Integer getPivotRow(SimplexTableau tableau, final int col) {
247        // create a list of all the rows that tie for the lowest score in the minimum ratio test
248        List<Integer> minRatioPositions = new ArrayList<Integer>();
249        double minRatio = Double.MAX_VALUE;
250        for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
251            final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
252            final double entry = tableau.getEntry(i, col);
253
254            // only consider pivot elements larger than the cutOff threshold
255            // selecting others may lead to degeneracy or numerical instabilities
256            if (Precision.compareTo(entry, 0d, cutOff) > 0) {
257                final double ratio = FastMath.abs(rhs / entry);
258                // check if the entry is strictly equal to the current min ratio
259                // do not use a ulp/epsilon check
260                final int cmp = Double.compare(ratio, minRatio);
261                if (cmp == 0) {
262                    minRatioPositions.add(i);
263                } else if (cmp < 0) {
264                    minRatio = ratio;
265                    minRatioPositions.clear();
266                    minRatioPositions.add(i);
267                }
268            }
269        }
270
271        if (minRatioPositions.size() == 0) {
272            return null;
273        } else if (minRatioPositions.size() > 1) {
274            // there's a degeneracy as indicated by a tie in the minimum ratio test
275
276            // 1. check if there's an artificial variable that can be forced out of the basis
277            if (tableau.getNumArtificialVariables() > 0) {
278                for (Integer row : minRatioPositions) {
279                    for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
280                        int column = i + tableau.getArtificialVariableOffset();
281                        final double entry = tableau.getEntry(row, column);
282                        if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
283                            return row;
284                        }
285                    }
286                }
287            }
288
289            // 2. apply Bland's rule to prevent cycling:
290            //    take the row for which the corresponding basic variable has the smallest index
291            //
292            // see http://www.stanford.edu/class/msande310/blandrule.pdf
293            // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
294
295            Integer minRow = null;
296            int minIndex = tableau.getWidth();
297            for (Integer row : minRatioPositions) {
298                final int basicVar = tableau.getBasicVariable(row);
299                if (basicVar < minIndex) {
300                    minIndex = basicVar;
301                    minRow = row;
302                }
303            }
304            return minRow;
305        }
306        return minRatioPositions.get(0);
307    }
308
309    /**
310     * Runs one iteration of the Simplex method on the given model.
311     *
312     * @param tableau Simple tableau for the problem.
313     * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
314     * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
315     */
316    protected void doIteration(final SimplexTableau tableau)
317        throws TooManyIterationsException,
318               UnboundedSolutionException {
319
320        incrementIterationCount();
321
322        Integer pivotCol = getPivotColumn(tableau);
323        Integer pivotRow = getPivotRow(tableau, pivotCol);
324        if (pivotRow == null) {
325            throw new UnboundedSolutionException();
326        }
327
328        tableau.performRowOperations(pivotCol, pivotRow);
329    }
330
331    /**
332     * Solves Phase 1 of the Simplex method.
333     *
334     * @param tableau Simple tableau for the problem.
335     * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
336     * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
337     * @throws NoFeasibleSolutionException if there is no feasible solution?
338     */
339    protected void solvePhase1(final SimplexTableau tableau)
340        throws TooManyIterationsException,
341               UnboundedSolutionException,
342               NoFeasibleSolutionException {
343
344        // make sure we're in Phase 1
345        if (tableau.getNumArtificialVariables() == 0) {
346            return;
347        }
348
349        while (!tableau.isOptimal()) {
350            doIteration(tableau);
351        }
352
353        // if W is not zero then we have no feasible solution
354        if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
355            throw new NoFeasibleSolutionException();
356        }
357    }
358
359    /** {@inheritDoc} */
360    @Override
361    public PointValuePair doOptimize()
362        throws TooManyIterationsException,
363               UnboundedSolutionException,
364               NoFeasibleSolutionException {
365
366        // reset the tableau to indicate a non-feasible solution in case
367        // we do not pass phase 1 successfully
368        if (solutionCallback != null) {
369            solutionCallback.setTableau(null);
370        }
371
372        final SimplexTableau tableau =
373            new SimplexTableau(getFunction(),
374                               getConstraints(),
375                               getGoalType(),
376                               isRestrictedToNonNegative(),
377                               epsilon,
378                               maxUlps);
379
380        solvePhase1(tableau);
381        tableau.dropPhase1Objective();
382
383        // after phase 1, we are sure to have a feasible solution
384        if (solutionCallback != null) {
385            solutionCallback.setTableau(tableau);
386        }
387
388        while (!tableau.isOptimal()) {
389            doIteration(tableau);
390        }
391
392        // check that the solution respects the nonNegative restriction in case
393        // the epsilon/cutOff values are too large for the actual linear problem
394        // (e.g. with very small constraint coefficients), the solver might actually
395        // find a non-valid solution (with negative coefficients).
396        final PointValuePair solution = tableau.getSolution();
397        if (isRestrictedToNonNegative()) {
398            final double[] coeff = solution.getPoint();
399            for (int i = 0; i < coeff.length; i++) {
400                if (Precision.compareTo(coeff[i], 0, epsilon) < 0) {
401                    throw new NoFeasibleSolutionException();
402                }
403            }
404        }
405        return solution;
406    }
407}