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 */
017
018package org.apache.commons.math3.optimization.linear;
019
020import java.util.ArrayList;
021import java.util.List;
022
023import org.apache.commons.math3.exception.MaxCountExceededException;
024import org.apache.commons.math3.optimization.PointValuePair;
025import org.apache.commons.math3.util.Precision;
026
027
028/**
029 * Solves a linear problem using the Two-Phase Simplex Method.
030 *
031 * @version $Id: SimplexSolver.java 1524213 2013-09-17 20:32:50Z tn $
032 * @deprecated As of 3.1 (to be removed in 4.0).
033 * @since 2.0
034 */
035@Deprecated
036public class SimplexSolver extends AbstractLinearOptimizer {
037
038    /** Default amount of error to accept for algorithm convergence. */
039    private static final double DEFAULT_EPSILON = 1.0e-6;
040
041    /** Default amount of error to accept in floating point comparisons (as ulps). */
042    private static final int DEFAULT_ULPS = 10;
043
044    /** Amount of error to accept for algorithm convergence. */
045    private final double epsilon;
046
047    /** Amount of error to accept in floating point comparisons (as ulps). */
048    private final int maxUlps;
049
050    /**
051     * Build a simplex solver with default settings.
052     */
053    public SimplexSolver() {
054        this(DEFAULT_EPSILON, DEFAULT_ULPS);
055    }
056
057    /**
058     * Build a simplex solver with a specified accepted amount of error
059     * @param epsilon the amount of error to accept for algorithm convergence
060     * @param maxUlps amount of error to accept in floating point comparisons
061     */
062    public SimplexSolver(final double epsilon, final int maxUlps) {
063        this.epsilon = epsilon;
064        this.maxUlps = maxUlps;
065    }
066
067    /**
068     * Returns the column with the most negative coefficient in the objective function row.
069     * @param tableau simple tableau for the problem
070     * @return column with the most negative coefficient
071     */
072    private Integer getPivotColumn(SimplexTableau tableau) {
073        double minValue = 0;
074        Integer minPos = null;
075        for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
076            final double entry = tableau.getEntry(0, i);
077            // check if the entry is strictly smaller than the current minimum
078            // do not use a ulp/epsilon check
079            if (entry < minValue) {
080                minValue = entry;
081                minPos = i;
082            }
083        }
084        return minPos;
085    }
086
087    /**
088     * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
089     * @param tableau simple tableau for the problem
090     * @param col the column to test the ratio of.  See {@link #getPivotColumn(SimplexTableau)}
091     * @return row with the minimum ratio
092     */
093    private Integer getPivotRow(SimplexTableau tableau, final int col) {
094        // create a list of all the rows that tie for the lowest score in the minimum ratio test
095        List<Integer> minRatioPositions = new ArrayList<Integer>();
096        double minRatio = Double.MAX_VALUE;
097        for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
098            final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
099            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}