1 | //===- Simplex.cpp - MLIR Simplex Class -----------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "mlir/Analysis/Presburger/Simplex.h" |
10 | #include "mlir/Analysis/Presburger/Fraction.h" |
11 | #include "mlir/Analysis/Presburger/IntegerRelation.h" |
12 | #include "mlir/Analysis/Presburger/MPInt.h" |
13 | #include "mlir/Analysis/Presburger/Matrix.h" |
14 | #include "mlir/Analysis/Presburger/PresburgerSpace.h" |
15 | #include "mlir/Analysis/Presburger/Utils.h" |
16 | #include "mlir/Support/LLVM.h" |
17 | #include "mlir/Support/LogicalResult.h" |
18 | #include "llvm/ADT/STLExtras.h" |
19 | #include "llvm/ADT/SmallBitVector.h" |
20 | #include "llvm/ADT/SmallVector.h" |
21 | #include "llvm/Support/Compiler.h" |
22 | #include "llvm/Support/ErrorHandling.h" |
23 | #include "llvm/Support/raw_ostream.h" |
24 | #include <cassert> |
25 | #include <functional> |
26 | #include <limits> |
27 | #include <optional> |
28 | #include <tuple> |
29 | #include <utility> |
30 | |
31 | using namespace mlir; |
32 | using namespace presburger; |
33 | |
34 | using Direction = Simplex::Direction; |
35 | |
36 | const int nullIndex = std::numeric_limits<int>::max(); |
37 | |
38 | // Return a + scale*b; |
39 | LLVM_ATTRIBUTE_UNUSED |
40 | static SmallVector<MPInt, 8> |
41 | scaleAndAddForAssert(ArrayRef<MPInt> a, const MPInt &scale, ArrayRef<MPInt> b) { |
42 | assert(a.size() == b.size()); |
43 | SmallVector<MPInt, 8> res; |
44 | res.reserve(N: a.size()); |
45 | for (unsigned i = 0, e = a.size(); i < e; ++i) |
46 | res.push_back(Elt: a[i] + scale * b[i]); |
47 | return res; |
48 | } |
49 | |
50 | SimplexBase::SimplexBase(unsigned nVar, bool mustUseBigM) |
51 | : usingBigM(mustUseBigM), nRedundant(0), nSymbol(0), |
52 | tableau(0, getNumFixedCols() + nVar), empty(false) { |
53 | colUnknown.insert(I: colUnknown.begin(), NumToInsert: getNumFixedCols(), Elt: nullIndex); |
54 | for (unsigned i = 0; i < nVar; ++i) { |
55 | var.emplace_back(Args: Orientation::Column, /*restricted=*/Args: false, |
56 | /*pos=*/Args: getNumFixedCols() + i); |
57 | colUnknown.push_back(Elt: i); |
58 | } |
59 | } |
60 | |
61 | SimplexBase::SimplexBase(unsigned nVar, bool mustUseBigM, |
62 | const llvm::SmallBitVector &isSymbol) |
63 | : SimplexBase(nVar, mustUseBigM) { |
64 | assert(isSymbol.size() == nVar && "invalid bitmask!" ); |
65 | // Invariant: nSymbol is the number of symbols that have been marked |
66 | // already and these occupy the columns |
67 | // [getNumFixedCols(), getNumFixedCols() + nSymbol). |
68 | for (unsigned symbolIdx : isSymbol.set_bits()) { |
69 | var[symbolIdx].isSymbol = true; |
70 | swapColumns(i: var[symbolIdx].pos, j: getNumFixedCols() + nSymbol); |
71 | ++nSymbol; |
72 | } |
73 | } |
74 | |
75 | const Simplex::Unknown &SimplexBase::unknownFromIndex(int index) const { |
76 | assert(index != nullIndex && "nullIndex passed to unknownFromIndex" ); |
77 | return index >= 0 ? var[index] : con[~index]; |
78 | } |
79 | |
80 | const Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) const { |
81 | assert(col < getNumColumns() && "Invalid column" ); |
82 | return unknownFromIndex(index: colUnknown[col]); |
83 | } |
84 | |
85 | const Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) const { |
86 | assert(row < getNumRows() && "Invalid row" ); |
87 | return unknownFromIndex(index: rowUnknown[row]); |
88 | } |
89 | |
90 | Simplex::Unknown &SimplexBase::unknownFromIndex(int index) { |
91 | assert(index != nullIndex && "nullIndex passed to unknownFromIndex" ); |
92 | return index >= 0 ? var[index] : con[~index]; |
93 | } |
94 | |
95 | Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) { |
96 | assert(col < getNumColumns() && "Invalid column" ); |
97 | return unknownFromIndex(index: colUnknown[col]); |
98 | } |
99 | |
100 | Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) { |
101 | assert(row < getNumRows() && "Invalid row" ); |
102 | return unknownFromIndex(index: rowUnknown[row]); |
103 | } |
104 | |
105 | unsigned SimplexBase::addZeroRow(bool makeRestricted) { |
106 | // Resize the tableau to accommodate the extra row. |
107 | unsigned newRow = tableau.appendExtraRow(); |
108 | assert(getNumRows() == getNumRows() && "Inconsistent tableau size" ); |
109 | rowUnknown.push_back(Elt: ~con.size()); |
110 | con.emplace_back(Args: Orientation::Row, Args&: makeRestricted, Args&: newRow); |
111 | undoLog.push_back(Elt: UndoLogEntry::RemoveLastConstraint); |
112 | tableau(newRow, 0) = 1; |
113 | return newRow; |
114 | } |
115 | |
116 | /// Add a new row to the tableau corresponding to the given constant term and |
117 | /// list of coefficients. The coefficients are specified as a vector of |
118 | /// (variable index, coefficient) pairs. |
119 | unsigned SimplexBase::addRow(ArrayRef<MPInt> coeffs, bool makeRestricted) { |
120 | assert(coeffs.size() == var.size() + 1 && |
121 | "Incorrect number of coefficients!" ); |
122 | assert(var.size() + getNumFixedCols() == getNumColumns() && |
123 | "inconsistent column count!" ); |
124 | |
125 | unsigned newRow = addZeroRow(makeRestricted); |
126 | tableau(newRow, 1) = coeffs.back(); |
127 | if (usingBigM) { |
128 | // When the lexicographic pivot rule is used, instead of the variables |
129 | // |
130 | // x, y, z ... |
131 | // |
132 | // we internally use the variables |
133 | // |
134 | // M, M + x, M + y, M + z, ... |
135 | // |
136 | // where M is the big M parameter. As such, when the user tries to add |
137 | // a row ax + by + cz + d, we express it in terms of our internal variables |
138 | // as -(a + b + c)M + a(M + x) + b(M + y) + c(M + z) + d. |
139 | // |
140 | // Symbols don't use the big M parameter since they do not get lex |
141 | // optimized. |
142 | MPInt bigMCoeff(0); |
143 | for (unsigned i = 0; i < coeffs.size() - 1; ++i) |
144 | if (!var[i].isSymbol) |
145 | bigMCoeff -= coeffs[i]; |
146 | // The coefficient to the big M parameter is stored in column 2. |
147 | tableau(newRow, 2) = bigMCoeff; |
148 | } |
149 | |
150 | // Process each given variable coefficient. |
151 | for (unsigned i = 0; i < var.size(); ++i) { |
152 | unsigned pos = var[i].pos; |
153 | if (coeffs[i] == 0) |
154 | continue; |
155 | |
156 | if (var[i].orientation == Orientation::Column) { |
157 | // If a variable is in column position at column col, then we just add the |
158 | // coefficient for that variable (scaled by the common row denominator) to |
159 | // the corresponding entry in the new row. |
160 | tableau(newRow, pos) += coeffs[i] * tableau(newRow, 0); |
161 | continue; |
162 | } |
163 | |
164 | // If the variable is in row position, we need to add that row to the new |
165 | // row, scaled by the coefficient for the variable, accounting for the two |
166 | // rows potentially having different denominators. The new denominator is |
167 | // the lcm of the two. |
168 | MPInt lcm = presburger::lcm(a: tableau(newRow, 0), b: tableau(pos, 0)); |
169 | MPInt nRowCoeff = lcm / tableau(newRow, 0); |
170 | MPInt idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0)); |
171 | tableau(newRow, 0) = lcm; |
172 | for (unsigned col = 1, e = getNumColumns(); col < e; ++col) |
173 | tableau(newRow, col) = |
174 | nRowCoeff * tableau(newRow, col) + idxRowCoeff * tableau(pos, col); |
175 | } |
176 | |
177 | tableau.normalizeRow(row: newRow); |
178 | // Push to undo log along with the index of the new constraint. |
179 | return con.size() - 1; |
180 | } |
181 | |
182 | namespace { |
183 | bool signMatchesDirection(const MPInt &elem, Direction direction) { |
184 | assert(elem != 0 && "elem should not be 0" ); |
185 | return direction == Direction::Up ? elem > 0 : elem < 0; |
186 | } |
187 | |
188 | Direction flippedDirection(Direction direction) { |
189 | return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up; |
190 | } |
191 | } // namespace |
192 | |
193 | /// We simply make the tableau consistent while maintaining a lexicopositive |
194 | /// basis transform, and then return the sample value. If the tableau becomes |
195 | /// empty, we return empty. |
196 | /// |
197 | /// Let the variables be x = (x_1, ... x_n). |
198 | /// Let the basis unknowns be y = (y_1, ... y_n). |
199 | /// We have that x = A*y + b for some n x n matrix A and n x 1 column vector b. |
200 | /// |
201 | /// As we will show below, A*y is either zero or lexicopositive. |
202 | /// Adding a lexicopositive vector to b will make it lexicographically |
203 | /// greater, so A*y + b is always equal to or lexicographically greater than b. |
204 | /// Thus, since we can attain x = b, that is the lexicographic minimum. |
205 | /// |
206 | /// We have that every column in A is lexicopositive, i.e., has at least |
207 | /// one non-zero element, with the first such element being positive. Since for |
208 | /// the tableau to be consistent we must have non-negative sample values not |
209 | /// only for the constraints but also for the variables, we also have x >= 0 and |
210 | /// y >= 0, by which we mean every element in these vectors is non-negative. |
211 | /// |
212 | /// Proof that if every column in A is lexicopositive, and y >= 0, then |
213 | /// A*y is zero or lexicopositive. Begin by considering A_1, the first row of A. |
214 | /// If this row is all zeros, then (A*y)_1 = (A_1)*y = 0; proceed to the next |
215 | /// row. If we run out of rows, A*y is zero and we are done; otherwise, we |
216 | /// encounter some row A_i that has a non-zero element. Every column is |
217 | /// lexicopositive and so has some positive element before any negative elements |
218 | /// occur, so the element in this row for any column, if non-zero, must be |
219 | /// positive. Consider (A*y)_i = (A_i)*y. All the elements in both vectors are |
220 | /// non-negative, so if this is non-zero then it must be positive. Then the |
221 | /// first non-zero element of A*y is positive so A*y is lexicopositive. |
222 | /// |
223 | /// Otherwise, if (A_i)*y is zero, then for every column j that had a non-zero |
224 | /// element in A_i, y_j is zero. Thus these columns have no contribution to A*y |
225 | /// and we can completely ignore these columns of A. We now continue downwards, |
226 | /// looking for rows of A that have a non-zero element other than in the ignored |
227 | /// columns. If we find one, say A_k, once again these elements must be positive |
228 | /// since they are the first non-zero element in each of these columns, so if |
229 | /// (A_k)*y is not zero then we have that A*y is lexicopositive and if not we |
230 | /// add these to the set of ignored columns and continue to the next row. If we |
231 | /// run out of rows, then A*y is zero and we are done. |
232 | MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::findRationalLexMin() { |
233 | if (restoreRationalConsistency().failed()) { |
234 | markEmpty(); |
235 | return OptimumKind::Empty; |
236 | } |
237 | return getRationalSample(); |
238 | } |
239 | |
240 | /// Given a row that has a non-integer sample value, add an inequality such |
241 | /// that this fractional sample value is cut away from the polytope. The added |
242 | /// inequality will be such that no integer points are removed. i.e., the |
243 | /// integer lexmin, if it exists, is the same with and without this constraint. |
244 | /// |
245 | /// Let the row be |
246 | /// (c + coeffM*M + a_1*s_1 + ... + a_m*s_m + b_1*y_1 + ... + b_n*y_n)/d, |
247 | /// where s_1, ... s_m are the symbols and |
248 | /// y_1, ... y_n are the other basis unknowns. |
249 | /// |
250 | /// For this to be an integer, we want |
251 | /// coeffM*M + a_1*s_1 + ... + a_m*s_m + b_1*y_1 + ... + b_n*y_n = -c (mod d) |
252 | /// Note that this constraint must always hold, independent of the basis, |
253 | /// becuse the row unknown's value always equals this expression, even if *we* |
254 | /// later compute the sample value from a different expression based on a |
255 | /// different basis. |
256 | /// |
257 | /// Let us assume that M has a factor of d in it. Imposing this constraint on M |
258 | /// does not in any way hinder us from finding a value of M that is big enough. |
259 | /// Moreover, this function is only called when the symbolic part of the sample, |
260 | /// a_1*s_1 + ... + a_m*s_m, is known to be an integer. |
261 | /// |
262 | /// Also, we can safely reduce the coefficients modulo d, so we have: |
263 | /// |
264 | /// (b_1%d)y_1 + ... + (b_n%d)y_n = (-c%d) + k*d for some integer `k` |
265 | /// |
266 | /// Note that all coefficient modulos here are non-negative. Also, all the |
267 | /// unknowns are non-negative here as both constraints and variables are |
268 | /// non-negative in LexSimplexBase. (We used the big M trick to make the |
269 | /// variables non-negative). Therefore, the LHS here is non-negative. |
270 | /// Since 0 <= (-c%d) < d, k is the quotient of dividing the LHS by d and |
271 | /// is therefore non-negative as well. |
272 | /// |
273 | /// So we have |
274 | /// ((b_1%d)y_1 + ... + (b_n%d)y_n - (-c%d))/d >= 0. |
275 | /// |
276 | /// The constraint is violated when added (it would be useless otherwise) |
277 | /// so we immediately try to move it to a column. |
278 | LogicalResult LexSimplexBase::addCut(unsigned row) { |
279 | MPInt d = tableau(row, 0); |
280 | unsigned cutRow = addZeroRow(/*makeRestricted=*/true); |
281 | tableau(cutRow, 0) = d; |
282 | tableau(cutRow, 1) = -mod(lhs: -tableau(row, 1), rhs: d); // -c%d. |
283 | tableau(cutRow, 2) = 0; |
284 | for (unsigned col = 3 + nSymbol, e = getNumColumns(); col < e; ++col) |
285 | tableau(cutRow, col) = mod(lhs: tableau(row, col), rhs: d); // b_i%d. |
286 | return moveRowUnknownToColumn(row: cutRow); |
287 | } |
288 | |
289 | std::optional<unsigned> LexSimplex::maybeGetNonIntegralVarRow() const { |
290 | for (const Unknown &u : var) { |
291 | if (u.orientation == Orientation::Column) |
292 | continue; |
293 | // If the sample value is of the form (a/d)M + b/d, we need b to be |
294 | // divisible by d. We assume M contains all possible |
295 | // factors and is divisible by everything. |
296 | unsigned row = u.pos; |
297 | if (tableau(row, 1) % tableau(row, 0) != 0) |
298 | return row; |
299 | } |
300 | return {}; |
301 | } |
302 | |
303 | MaybeOptimum<SmallVector<MPInt, 8>> LexSimplex::findIntegerLexMin() { |
304 | // We first try to make the tableau consistent. |
305 | if (restoreRationalConsistency().failed()) |
306 | return OptimumKind::Empty; |
307 | |
308 | // Then, if the sample value is integral, we are done. |
309 | while (std::optional<unsigned> maybeRow = maybeGetNonIntegralVarRow()) { |
310 | // Otherwise, for the variable whose row has a non-integral sample value, |
311 | // we add a cut, a constraint that remove this rational point |
312 | // while preserving all integer points, thus keeping the lexmin the same. |
313 | // We then again try to make the tableau with the new constraint |
314 | // consistent. This continues until the tableau becomes empty, in which |
315 | // case there is no integer point, or until there are no variables with |
316 | // non-integral sample values. |
317 | // |
318 | // Failure indicates that the tableau became empty, which occurs when the |
319 | // polytope is integer empty. |
320 | if (addCut(row: *maybeRow).failed()) |
321 | return OptimumKind::Empty; |
322 | if (restoreRationalConsistency().failed()) |
323 | return OptimumKind::Empty; |
324 | } |
325 | |
326 | MaybeOptimum<SmallVector<Fraction, 8>> sample = getRationalSample(); |
327 | assert(!sample.isEmpty() && "If we reached here the sample should exist!" ); |
328 | if (sample.isUnbounded()) |
329 | return OptimumKind::Unbounded; |
330 | return llvm::to_vector<8>( |
331 | Range: llvm::map_range(C&: *sample, F: std::mem_fn(pm: &Fraction::getAsInteger))); |
332 | } |
333 | |
334 | bool LexSimplex::isSeparateInequality(ArrayRef<MPInt> coeffs) { |
335 | SimplexRollbackScopeExit scopeExit(*this); |
336 | addInequality(coeffs); |
337 | return findIntegerLexMin().isEmpty(); |
338 | } |
339 | |
340 | bool LexSimplex::isRedundantInequality(ArrayRef<MPInt> coeffs) { |
341 | return isSeparateInequality(coeffs: getComplementIneq(ineq: coeffs)); |
342 | } |
343 | |
344 | SmallVector<MPInt, 8> |
345 | SymbolicLexSimplex::getSymbolicSampleNumerator(unsigned row) const { |
346 | SmallVector<MPInt, 8> sample; |
347 | sample.reserve(N: nSymbol + 1); |
348 | for (unsigned col = 3; col < 3 + nSymbol; ++col) |
349 | sample.push_back(Elt: tableau(row, col)); |
350 | sample.push_back(Elt: tableau(row, 1)); |
351 | return sample; |
352 | } |
353 | |
354 | SmallVector<MPInt, 8> |
355 | SymbolicLexSimplex::getSymbolicSampleIneq(unsigned row) const { |
356 | SmallVector<MPInt, 8> sample = getSymbolicSampleNumerator(row); |
357 | // The inequality is equivalent to the GCD-normalized one. |
358 | normalizeRange(range: sample); |
359 | return sample; |
360 | } |
361 | |
362 | void LexSimplexBase::appendSymbol() { |
363 | appendVariable(); |
364 | swapColumns(i: 3 + nSymbol, j: getNumColumns() - 1); |
365 | var.back().isSymbol = true; |
366 | nSymbol++; |
367 | } |
368 | |
369 | static bool isRangeDivisibleBy(ArrayRef<MPInt> range, const MPInt &divisor) { |
370 | assert(divisor > 0 && "divisor must be positive!" ); |
371 | return llvm::all_of(Range&: range, |
372 | P: [divisor](const MPInt &x) { return x % divisor == 0; }); |
373 | } |
374 | |
375 | bool SymbolicLexSimplex::isSymbolicSampleIntegral(unsigned row) const { |
376 | MPInt denom = tableau(row, 0); |
377 | return tableau(row, 1) % denom == 0 && |
378 | isRangeDivisibleBy(range: tableau.getRow(row).slice(N: 3, M: nSymbol), divisor: denom); |
379 | } |
380 | |
381 | /// This proceeds similarly to LexSimplexBase::addCut(). We are given a row that |
382 | /// has a symbolic sample value with fractional coefficients. |
383 | /// |
384 | /// Let the row be |
385 | /// (c + coeffM*M + sum_i a_i*s_i + sum_j b_j*y_j)/d, |
386 | /// where s_1, ... s_m are the symbols and |
387 | /// y_1, ... y_n are the other basis unknowns. |
388 | /// |
389 | /// As in LexSimplex::addCut, for this to be an integer, we want |
390 | /// |
391 | /// coeffM*M + sum_j b_j*y_j = -c + sum_i (-a_i*s_i) (mod d) |
392 | /// |
393 | /// This time, a_1*s_1 + ... + a_m*s_m may not be an integer. We find that |
394 | /// |
395 | /// sum_i (b_i%d)y_i = ((-c%d) + sum_i (-a_i%d)s_i)%d + k*d for some integer k |
396 | /// |
397 | /// where we take a modulo of the whole symbolic expression on the right to |
398 | /// bring it into the range [0, d - 1]. Therefore, as in addCut(), |
399 | /// k is the quotient on dividing the LHS by d, and since LHS >= 0, we have |
400 | /// k >= 0 as well. If all the a_i are divisible by d, then we can add the |
401 | /// constraint directly. Otherwise, we realize the modulo of the symbolic |
402 | /// expression by adding a division variable |
403 | /// |
404 | /// q = ((-c%d) + sum_i (-a_i%d)s_i)/d |
405 | /// |
406 | /// to the symbol domain, so the equality becomes |
407 | /// |
408 | /// sum_i (b_i%d)y_i = (-c%d) + sum_i (-a_i%d)s_i - q*d + k*d for some integer k |
409 | /// |
410 | /// So the cut is |
411 | /// (sum_i (b_i%d)y_i - (-c%d) - sum_i (-a_i%d)s_i + q*d)/d >= 0 |
412 | /// This constraint is violated when added so we immediately try to move it to a |
413 | /// column. |
414 | LogicalResult SymbolicLexSimplex::addSymbolicCut(unsigned row) { |
415 | MPInt d = tableau(row, 0); |
416 | if (isRangeDivisibleBy(range: tableau.getRow(row).slice(N: 3, M: nSymbol), divisor: d)) { |
417 | // The coefficients of symbols in the symbol numerator are divisible |
418 | // by the denominator, so we can add the constraint directly, |
419 | // i.e., ignore the symbols and add a regular cut as in addCut(). |
420 | return addCut(row); |
421 | } |
422 | |
423 | // Construct the division variable `q = ((-c%d) + sum_i (-a_i%d)s_i)/d`. |
424 | SmallVector<MPInt, 8> divCoeffs; |
425 | divCoeffs.reserve(N: nSymbol + 1); |
426 | MPInt divDenom = d; |
427 | for (unsigned col = 3; col < 3 + nSymbol; ++col) |
428 | divCoeffs.push_back(Elt: mod(lhs: -tableau(row, col), rhs: divDenom)); // (-a_i%d)s_i |
429 | divCoeffs.push_back(Elt: mod(lhs: -tableau(row, 1), rhs: divDenom)); // -c%d. |
430 | normalizeDiv(num: divCoeffs, denom&: divDenom); |
431 | |
432 | domainSimplex.addDivisionVariable(coeffs: divCoeffs, denom: divDenom); |
433 | domainPoly.addLocalFloorDiv(dividend: divCoeffs, divisor: divDenom); |
434 | |
435 | // Update `this` to account for the additional symbol we just added. |
436 | appendSymbol(); |
437 | |
438 | // Add the cut (sum_i (b_i%d)y_i - (-c%d) + sum_i -(-a_i%d)s_i + q*d)/d >= 0. |
439 | unsigned cutRow = addZeroRow(/*makeRestricted=*/true); |
440 | tableau(cutRow, 0) = d; |
441 | tableau(cutRow, 2) = 0; |
442 | |
443 | tableau(cutRow, 1) = -mod(lhs: -tableau(row, 1), rhs: d); // -(-c%d). |
444 | for (unsigned col = 3; col < 3 + nSymbol - 1; ++col) |
445 | tableau(cutRow, col) = -mod(lhs: -tableau(row, col), rhs: d); // -(-a_i%d)s_i. |
446 | tableau(cutRow, 3 + nSymbol - 1) = d; // q*d. |
447 | |
448 | for (unsigned col = 3 + nSymbol, e = getNumColumns(); col < e; ++col) |
449 | tableau(cutRow, col) = mod(lhs: tableau(row, col), rhs: d); // (b_i%d)y_i. |
450 | return moveRowUnknownToColumn(row: cutRow); |
451 | } |
452 | |
453 | void SymbolicLexSimplex::recordOutput(SymbolicLexOpt &result) const { |
454 | IntMatrix output(0, domainPoly.getNumVars() + 1); |
455 | output.reserveRows(rows: result.lexopt.getNumOutputs()); |
456 | for (const Unknown &u : var) { |
457 | if (u.isSymbol) |
458 | continue; |
459 | |
460 | if (u.orientation == Orientation::Column) { |
461 | // M + u has a sample value of zero so u has a sample value of -M, i.e, |
462 | // unbounded. |
463 | result.unboundedDomain.unionInPlace(disjunct: domainPoly); |
464 | return; |
465 | } |
466 | |
467 | MPInt denom = tableau(u.pos, 0); |
468 | if (tableau(u.pos, 2) < denom) { |
469 | // M + u has a sample value of fM + something, where f < 1, so |
470 | // u = (f - 1)M + something, which has a negative coefficient for M, |
471 | // and so is unbounded. |
472 | result.unboundedDomain.unionInPlace(disjunct: domainPoly); |
473 | return; |
474 | } |
475 | assert(tableau(u.pos, 2) == denom && |
476 | "Coefficient of M should not be greater than 1!" ); |
477 | |
478 | SmallVector<MPInt, 8> sample = getSymbolicSampleNumerator(row: u.pos); |
479 | for (MPInt &elem : sample) { |
480 | assert(elem % denom == 0 && "coefficients must be integral!" ); |
481 | elem /= denom; |
482 | } |
483 | output.appendExtraRow(elems: sample); |
484 | } |
485 | |
486 | // Store the output in a MultiAffineFunction and add it the result. |
487 | PresburgerSpace funcSpace = result.lexopt.getSpace(); |
488 | funcSpace.insertVar(kind: VarKind::Local, pos: 0, num: domainPoly.getNumLocalVars()); |
489 | |
490 | result.lexopt.addPiece( |
491 | piece: {.domain: PresburgerSet(domainPoly), |
492 | .output: MultiAffineFunction(funcSpace, output, domainPoly.getLocalReprs())}); |
493 | } |
494 | |
495 | std::optional<unsigned> SymbolicLexSimplex::maybeGetAlwaysViolatedRow() { |
496 | // First look for rows that are clearly violated just from the big M |
497 | // coefficient, without needing to perform any simplex queries on the domain. |
498 | for (unsigned row = 0, e = getNumRows(); row < e; ++row) |
499 | if (tableau(row, 2) < 0) |
500 | return row; |
501 | |
502 | for (unsigned row = 0, e = getNumRows(); row < e; ++row) { |
503 | if (tableau(row, 2) > 0) |
504 | continue; |
505 | if (domainSimplex.isSeparateInequality(coeffs: getSymbolicSampleIneq(row))) { |
506 | // Sample numerator always takes negative values in the symbol domain. |
507 | return row; |
508 | } |
509 | } |
510 | return {}; |
511 | } |
512 | |
513 | std::optional<unsigned> SymbolicLexSimplex::maybeGetNonIntegralVarRow() { |
514 | for (const Unknown &u : var) { |
515 | if (u.orientation == Orientation::Column) |
516 | continue; |
517 | assert(!u.isSymbol && "Symbol should not be in row orientation!" ); |
518 | if (!isSymbolicSampleIntegral(row: u.pos)) |
519 | return u.pos; |
520 | } |
521 | return {}; |
522 | } |
523 | |
524 | /// The non-branching pivots are just the ones moving the rows |
525 | /// that are always violated in the symbol domain. |
526 | LogicalResult SymbolicLexSimplex::doNonBranchingPivots() { |
527 | while (std::optional<unsigned> row = maybeGetAlwaysViolatedRow()) |
528 | if (moveRowUnknownToColumn(row: *row).failed()) |
529 | return failure(); |
530 | return success(); |
531 | } |
532 | |
533 | SymbolicLexOpt SymbolicLexSimplex::computeSymbolicIntegerLexMin() { |
534 | SymbolicLexOpt result(PresburgerSpace::getRelationSpace( |
535 | /*numDomain=*/domainPoly.getNumDimVars(), |
536 | /*numRange=*/var.size() - nSymbol, |
537 | /*numSymbols=*/domainPoly.getNumSymbolVars())); |
538 | |
539 | /// The algorithm is more naturally expressed recursively, but we implement |
540 | /// it iteratively here to avoid potential issues with stack overflows in the |
541 | /// compiler. We explicitly maintain the stack frames in a vector. |
542 | /// |
543 | /// To "recurse", we store the current "stack frame", i.e., state variables |
544 | /// that we will need when we "return", into `stack`, increment `level`, and |
545 | /// `continue`. To "tail recurse", we just `continue`. |
546 | /// To "return", we decrement `level` and `continue`. |
547 | /// |
548 | /// When there is no stack frame for the current `level`, this indicates that |
549 | /// we have just "recursed" or "tail recursed". When there does exist one, |
550 | /// this indicates that we have just "returned" from recursing. There is only |
551 | /// one point at which non-tail calls occur so we always "return" there. |
552 | unsigned level = 1; |
553 | struct StackFrame { |
554 | int splitIndex; |
555 | unsigned snapshot; |
556 | unsigned domainSnapshot; |
557 | IntegerRelation::CountsSnapshot domainPolyCounts; |
558 | }; |
559 | SmallVector<StackFrame, 8> stack; |
560 | |
561 | while (level > 0) { |
562 | assert(level >= stack.size()); |
563 | if (level > stack.size()) { |
564 | if (empty || domainSimplex.findIntegerLexMin().isEmpty()) { |
565 | // No integer points; return. |
566 | --level; |
567 | continue; |
568 | } |
569 | |
570 | if (doNonBranchingPivots().failed()) { |
571 | // Could not find pivots for violated constraints; return. |
572 | --level; |
573 | continue; |
574 | } |
575 | |
576 | SmallVector<MPInt, 8> symbolicSample; |
577 | unsigned splitRow = 0; |
578 | for (unsigned e = getNumRows(); splitRow < e; ++splitRow) { |
579 | if (tableau(splitRow, 2) > 0) |
580 | continue; |
581 | assert(tableau(splitRow, 2) == 0 && |
582 | "Non-branching pivots should have been handled already!" ); |
583 | |
584 | symbolicSample = getSymbolicSampleIneq(row: splitRow); |
585 | if (domainSimplex.isRedundantInequality(coeffs: symbolicSample)) |
586 | continue; |
587 | |
588 | // It's neither redundant nor separate, so it takes both positive and |
589 | // negative values, and hence constitutes a row for which we need to |
590 | // split the domain and separately run each case. |
591 | assert(!domainSimplex.isSeparateInequality(symbolicSample) && |
592 | "Non-branching pivots should have been handled already!" ); |
593 | break; |
594 | } |
595 | |
596 | if (splitRow < getNumRows()) { |
597 | unsigned domainSnapshot = domainSimplex.getSnapshot(); |
598 | IntegerRelation::CountsSnapshot domainPolyCounts = |
599 | domainPoly.getCounts(); |
600 | |
601 | // First, we consider the part of the domain where the row is not |
602 | // violated. We don't have to do any pivots for the row in this case, |
603 | // but we record the additional constraint that defines this part of |
604 | // the domain. |
605 | domainSimplex.addInequality(coeffs: symbolicSample); |
606 | domainPoly.addInequality(inEq: symbolicSample); |
607 | |
608 | // Recurse. |
609 | // |
610 | // On return, the basis as a set is preserved but not the internal |
611 | // ordering within rows or columns. Thus, we take note of the index of |
612 | // the Unknown that caused the split, which may be in a different |
613 | // row when we come back from recursing. We will need this to recurse |
614 | // on the other part of the split domain, where the row is violated. |
615 | // |
616 | // Note that we have to capture the index above and not a reference to |
617 | // the Unknown itself, since the array it lives in might get |
618 | // reallocated. |
619 | int splitIndex = rowUnknown[splitRow]; |
620 | unsigned snapshot = getSnapshot(); |
621 | stack.push_back( |
622 | Elt: {.splitIndex: splitIndex, .snapshot: snapshot, .domainSnapshot: domainSnapshot, .domainPolyCounts: domainPolyCounts}); |
623 | ++level; |
624 | continue; |
625 | } |
626 | |
627 | // The tableau is rationally consistent for the current domain. |
628 | // Now we look for non-integral sample values and add cuts for them. |
629 | if (std::optional<unsigned> row = maybeGetNonIntegralVarRow()) { |
630 | if (addSymbolicCut(row: *row).failed()) { |
631 | // No integral points; return. |
632 | --level; |
633 | continue; |
634 | } |
635 | |
636 | // Rerun this level with the added cut constraint (tail recurse). |
637 | continue; |
638 | } |
639 | |
640 | // Record output and return. |
641 | recordOutput(result); |
642 | --level; |
643 | continue; |
644 | } |
645 | |
646 | if (level == stack.size()) { |
647 | // We have "returned" from "recursing". |
648 | const StackFrame &frame = stack.back(); |
649 | domainPoly.truncate(counts: frame.domainPolyCounts); |
650 | domainSimplex.rollback(snapshot: frame.domainSnapshot); |
651 | rollback(snapshot: frame.snapshot); |
652 | const Unknown &u = unknownFromIndex(index: frame.splitIndex); |
653 | |
654 | // Drop the frame. We don't need it anymore. |
655 | stack.pop_back(); |
656 | |
657 | // Now we consider the part of the domain where the unknown `splitIndex` |
658 | // was negative. |
659 | assert(u.orientation == Orientation::Row && |
660 | "The split row should have been returned to row orientation!" ); |
661 | SmallVector<MPInt, 8> splitIneq = |
662 | getComplementIneq(ineq: getSymbolicSampleIneq(row: u.pos)); |
663 | normalizeRange(range: splitIneq); |
664 | if (moveRowUnknownToColumn(row: u.pos).failed()) { |
665 | // The unknown can't be made non-negative; return. |
666 | --level; |
667 | continue; |
668 | } |
669 | |
670 | // The unknown can be made negative; recurse with the corresponding domain |
671 | // constraints. |
672 | domainSimplex.addInequality(coeffs: splitIneq); |
673 | domainPoly.addInequality(inEq: splitIneq); |
674 | |
675 | // We are now taking care of the second half of the domain and we don't |
676 | // need to do anything else here after returning, so it's a tail recurse. |
677 | continue; |
678 | } |
679 | } |
680 | |
681 | return result; |
682 | } |
683 | |
684 | bool LexSimplex::rowIsViolated(unsigned row) const { |
685 | if (tableau(row, 2) < 0) |
686 | return true; |
687 | if (tableau(row, 2) == 0 && tableau(row, 1) < 0) |
688 | return true; |
689 | return false; |
690 | } |
691 | |
692 | std::optional<unsigned> LexSimplex::maybeGetViolatedRow() const { |
693 | for (unsigned row = 0, e = getNumRows(); row < e; ++row) |
694 | if (rowIsViolated(row)) |
695 | return row; |
696 | return {}; |
697 | } |
698 | |
699 | /// We simply look for violated rows and keep trying to move them to column |
700 | /// orientation, which always succeeds unless the constraints have no solution |
701 | /// in which case we just give up and return. |
702 | LogicalResult LexSimplex::restoreRationalConsistency() { |
703 | if (empty) |
704 | return failure(); |
705 | while (std::optional<unsigned> maybeViolatedRow = maybeGetViolatedRow()) |
706 | if (moveRowUnknownToColumn(row: *maybeViolatedRow).failed()) |
707 | return failure(); |
708 | return success(); |
709 | } |
710 | |
711 | // Move the row unknown to column orientation while preserving lexicopositivity |
712 | // of the basis transform. The sample value of the row must be non-positive. |
713 | // |
714 | // We only consider pivots where the pivot element is positive. Suppose no such |
715 | // pivot exists, i.e., some violated row has no positive coefficient for any |
716 | // basis unknown. The row can be represented as (s + c_1*u_1 + ... + c_n*u_n)/d, |
717 | // where d is the denominator, s is the sample value and the c_i are the basis |
718 | // coefficients. If s != 0, then since any feasible assignment of the basis |
719 | // satisfies u_i >= 0 for all i, and we have s < 0 as well as c_i < 0 for all i, |
720 | // any feasible assignment would violate this row and therefore the constraints |
721 | // have no solution. |
722 | // |
723 | // We can preserve lexicopositivity by picking the pivot column with positive |
724 | // pivot element that makes the lexicographically smallest change to the sample |
725 | // point. |
726 | // |
727 | // Proof. Let |
728 | // x = (x_1, ... x_n) be the variables, |
729 | // z = (z_1, ... z_m) be the constraints, |
730 | // y = (y_1, ... y_n) be the current basis, and |
731 | // define w = (x_1, ... x_n, z_1, ... z_m) = B*y + s. |
732 | // B is basically the simplex tableau of our implementation except that instead |
733 | // of only describing the transform to get back the non-basis unknowns, it |
734 | // defines the values of all the unknowns in terms of the basis unknowns. |
735 | // Similarly, s is the column for the sample value. |
736 | // |
737 | // Our goal is to show that each column in B, restricted to the first n |
738 | // rows, is lexicopositive after the pivot if it is so before. This is |
739 | // equivalent to saying the columns in the whole matrix are lexicopositive; |
740 | // there must be some non-zero element in every column in the first n rows since |
741 | // the n variables cannot be spanned without using all the n basis unknowns. |
742 | // |
743 | // Consider a pivot where z_i replaces y_j in the basis. Recall the pivot |
744 | // transform for the tableau derived for SimplexBase::pivot: |
745 | // |
746 | // pivot col other col pivot col other col |
747 | // pivot row a b -> pivot row 1/a -b/a |
748 | // other row c d other row c/a d - bc/a |
749 | // |
750 | // Similarly, a pivot results in B changing to B' and c to c'; the difference |
751 | // between the tableau and these matrices B and B' is that there is no special |
752 | // case for the pivot row, since it continues to represent the same unknown. The |
753 | // same formula applies for all rows: |
754 | // |
755 | // B'.col(j) = B.col(j) / B(i,j) |
756 | // B'.col(k) = B.col(k) - B(i,k) * B.col(j) / B(i,j) for k != j |
757 | // and similarly, s' = s - s_i * B.col(j) / B(i,j). |
758 | // |
759 | // If s_i == 0, then the sample value remains unchanged. Otherwise, if s_i < 0, |
760 | // the change in sample value when pivoting with column a is lexicographically |
761 | // smaller than that when pivoting with column b iff B.col(a) / B(i, a) is |
762 | // lexicographically smaller than B.col(b) / B(i, b). |
763 | // |
764 | // Since B(i, j) > 0, column j remains lexicopositive. |
765 | // |
766 | // For the other columns, suppose C.col(k) is not lexicopositive. |
767 | // This means that for some p, for all t < p, |
768 | // C(t,k) = 0 => B(t,k) = B(t,j) * B(i,k) / B(i,j) and |
769 | // C(t,k) < 0 => B(p,k) < B(t,j) * B(i,k) / B(i,j), |
770 | // which is in contradiction to the fact that B.col(j) / B(i,j) must be |
771 | // lexicographically smaller than B.col(k) / B(i,k), since it lexicographically |
772 | // minimizes the change in sample value. |
773 | LogicalResult LexSimplexBase::moveRowUnknownToColumn(unsigned row) { |
774 | std::optional<unsigned> maybeColumn; |
775 | for (unsigned col = 3 + nSymbol, e = getNumColumns(); col < e; ++col) { |
776 | if (tableau(row, col) <= 0) |
777 | continue; |
778 | maybeColumn = |
779 | !maybeColumn ? col : getLexMinPivotColumn(row, colA: *maybeColumn, colB: col); |
780 | } |
781 | |
782 | if (!maybeColumn) |
783 | return failure(); |
784 | |
785 | pivot(row, col: *maybeColumn); |
786 | return success(); |
787 | } |
788 | |
789 | unsigned LexSimplexBase::getLexMinPivotColumn(unsigned row, unsigned colA, |
790 | unsigned colB) const { |
791 | // First, let's consider the non-symbolic case. |
792 | // A pivot causes the following change. (in the diagram the matrix elements |
793 | // are shown as rationals and there is no common denominator used) |
794 | // |
795 | // pivot col big M col const col |
796 | // pivot row a p b |
797 | // other row c q d |
798 | // | |
799 | // v |
800 | // |
801 | // pivot col big M col const col |
802 | // pivot row 1/a -p/a -b/a |
803 | // other row c/a q - pc/a d - bc/a |
804 | // |
805 | // Let the sample value of the pivot row be s = pM + b before the pivot. Since |
806 | // the pivot row represents a violated constraint we know that s < 0. |
807 | // |
808 | // If the variable is a non-pivot column, its sample value is zero before and |
809 | // after the pivot. |
810 | // |
811 | // If the variable is the pivot column, then its sample value goes from 0 to |
812 | // (-p/a)M + (-b/a), i.e. 0 to -(pM + b)/a. Thus the change in the sample |
813 | // value is -s/a. |
814 | // |
815 | // If the variable is the pivot row, its sample value goes from s to 0, for a |
816 | // change of -s. |
817 | // |
818 | // If the variable is a non-pivot row, its sample value changes from |
819 | // qM + d to qM + d + (-pc/a)M + (-bc/a). Thus the change in sample value |
820 | // is -(pM + b)(c/a) = -sc/a. |
821 | // |
822 | // Thus the change in sample value is either 0, -s/a, -s, or -sc/a. Here -s is |
823 | // fixed for all calls to this function since the row and tableau are fixed. |
824 | // The callee just wants to compare the return values with the return value of |
825 | // other invocations of the same function. So the -s is common for all |
826 | // comparisons involved and can be ignored, since -s is strictly positive. |
827 | // |
828 | // Thus we take away this common factor and just return 0, 1/a, 1, or c/a as |
829 | // appropriate. This allows us to run the entire algorithm treating M |
830 | // symbolically, as the pivot to be performed does not depend on the value |
831 | // of M, so long as the sample value s is negative. Note that this is not |
832 | // because of any special feature of M; by the same argument, we ignore the |
833 | // symbols too. The caller ensure that the sample value s is negative for |
834 | // all possible values of the symbols. |
835 | auto getSampleChangeCoeffForVar = [this, row](unsigned col, |
836 | const Unknown &u) -> Fraction { |
837 | MPInt a = tableau(row, col); |
838 | if (u.orientation == Orientation::Column) { |
839 | // Pivot column case. |
840 | if (u.pos == col) |
841 | return {1, a}; |
842 | |
843 | // Non-pivot column case. |
844 | return {0, 1}; |
845 | } |
846 | |
847 | // Pivot row case. |
848 | if (u.pos == row) |
849 | return {1, 1}; |
850 | |
851 | // Non-pivot row case. |
852 | MPInt c = tableau(u.pos, col); |
853 | return {c, a}; |
854 | }; |
855 | |
856 | for (const Unknown &u : var) { |
857 | Fraction changeA = getSampleChangeCoeffForVar(colA, u); |
858 | Fraction changeB = getSampleChangeCoeffForVar(colB, u); |
859 | if (changeA < changeB) |
860 | return colA; |
861 | if (changeA > changeB) |
862 | return colB; |
863 | } |
864 | |
865 | // If we reached here, both result in exactly the same changes, so it |
866 | // doesn't matter which we return. |
867 | return colA; |
868 | } |
869 | |
870 | /// Find a pivot to change the sample value of the row in the specified |
871 | /// direction. The returned pivot row will involve `row` if and only if the |
872 | /// unknown is unbounded in the specified direction. |
873 | /// |
874 | /// To increase (resp. decrease) the value of a row, we need to find a live |
875 | /// column with a non-zero coefficient. If the coefficient is positive, we need |
876 | /// to increase (decrease) the value of the column, and if the coefficient is |
877 | /// negative, we need to decrease (increase) the value of the column. Also, |
878 | /// we cannot decrease the sample value of restricted columns. |
879 | /// |
880 | /// If multiple columns are valid, we break ties by considering a lexicographic |
881 | /// ordering where we prefer unknowns with lower index. |
882 | std::optional<SimplexBase::Pivot> |
883 | Simplex::findPivot(int row, Direction direction) const { |
884 | std::optional<unsigned> col; |
885 | for (unsigned j = 2, e = getNumColumns(); j < e; ++j) { |
886 | MPInt elem = tableau(row, j); |
887 | if (elem == 0) |
888 | continue; |
889 | |
890 | if (unknownFromColumn(col: j).restricted && |
891 | !signMatchesDirection(elem, direction)) |
892 | continue; |
893 | if (!col || colUnknown[j] < colUnknown[*col]) |
894 | col = j; |
895 | } |
896 | |
897 | if (!col) |
898 | return {}; |
899 | |
900 | Direction newDirection = |
901 | tableau(row, *col) < 0 ? flippedDirection(direction) : direction; |
902 | std::optional<unsigned> maybePivotRow = findPivotRow(skipRow: row, direction: newDirection, col: *col); |
903 | return Pivot{.row: maybePivotRow.value_or(u&: row), .column: *col}; |
904 | } |
905 | |
906 | /// Swap the associated unknowns for the row and the column. |
907 | /// |
908 | /// First we swap the index associated with the row and column. Then we update |
909 | /// the unknowns to reflect their new position and orientation. |
910 | void SimplexBase::swapRowWithCol(unsigned row, unsigned col) { |
911 | std::swap(a&: rowUnknown[row], b&: colUnknown[col]); |
912 | Unknown &uCol = unknownFromColumn(col); |
913 | Unknown &uRow = unknownFromRow(row); |
914 | uCol.orientation = Orientation::Column; |
915 | uRow.orientation = Orientation::Row; |
916 | uCol.pos = col; |
917 | uRow.pos = row; |
918 | } |
919 | |
920 | void SimplexBase::pivot(Pivot pair) { pivot(row: pair.row, col: pair.column); } |
921 | |
922 | /// Pivot pivotRow and pivotCol. |
923 | /// |
924 | /// Let R be the pivot row unknown and let C be the pivot col unknown. |
925 | /// Since initially R = a*C + sum b_i * X_i |
926 | /// (where the sum is over the other column's unknowns, x_i) |
927 | /// C = (R - (sum b_i * X_i))/a |
928 | /// |
929 | /// Let u be some other row unknown. |
930 | /// u = c*C + sum d_i * X_i |
931 | /// So u = c*(R - sum b_i * X_i)/a + sum d_i * X_i |
932 | /// |
933 | /// This results in the following transform: |
934 | /// pivot col other col pivot col other col |
935 | /// pivot row a b -> pivot row 1/a -b/a |
936 | /// other row c d other row c/a d - bc/a |
937 | /// |
938 | /// Taking into account the common denominators p and q: |
939 | /// |
940 | /// pivot col other col pivot col other col |
941 | /// pivot row a/p b/p -> pivot row p/a -b/a |
942 | /// other row c/q d/q other row cp/aq (da - bc)/aq |
943 | /// |
944 | /// The pivot row transform is accomplished be swapping a with the pivot row's |
945 | /// common denominator and negating the pivot row except for the pivot column |
946 | /// element. |
947 | void SimplexBase::pivot(unsigned pivotRow, unsigned pivotCol) { |
948 | assert(pivotCol >= getNumFixedCols() && "Refusing to pivot invalid column" ); |
949 | assert(!unknownFromColumn(pivotCol).isSymbol); |
950 | |
951 | swapRowWithCol(row: pivotRow, col: pivotCol); |
952 | std::swap(a&: tableau(pivotRow, 0), b&: tableau(pivotRow, pivotCol)); |
953 | // We need to negate the whole pivot row except for the pivot column. |
954 | if (tableau(pivotRow, 0) < 0) { |
955 | // If the denominator is negative, we negate the row by simply negating the |
956 | // denominator. |
957 | tableau(pivotRow, 0) = -tableau(pivotRow, 0); |
958 | tableau(pivotRow, pivotCol) = -tableau(pivotRow, pivotCol); |
959 | } else { |
960 | for (unsigned col = 1, e = getNumColumns(); col < e; ++col) { |
961 | if (col == pivotCol) |
962 | continue; |
963 | tableau(pivotRow, col) = -tableau(pivotRow, col); |
964 | } |
965 | } |
966 | tableau.normalizeRow(row: pivotRow); |
967 | |
968 | for (unsigned row = 0, numRows = getNumRows(); row < numRows; ++row) { |
969 | if (row == pivotRow) |
970 | continue; |
971 | if (tableau(row, pivotCol) == 0) // Nothing to do. |
972 | continue; |
973 | tableau(row, 0) *= tableau(pivotRow, 0); |
974 | for (unsigned col = 1, numCols = getNumColumns(); col < numCols; ++col) { |
975 | if (col == pivotCol) |
976 | continue; |
977 | // Add rather than subtract because the pivot row has been negated. |
978 | tableau(row, col) = tableau(row, col) * tableau(pivotRow, 0) + |
979 | tableau(row, pivotCol) * tableau(pivotRow, col); |
980 | } |
981 | tableau(row, pivotCol) *= tableau(pivotRow, pivotCol); |
982 | tableau.normalizeRow(row); |
983 | } |
984 | } |
985 | |
986 | /// Perform pivots until the unknown has a non-negative sample value or until |
987 | /// no more upward pivots can be performed. Return success if we were able to |
988 | /// bring the row to a non-negative sample value, and failure otherwise. |
989 | LogicalResult Simplex::restoreRow(Unknown &u) { |
990 | assert(u.orientation == Orientation::Row && |
991 | "unknown should be in row position" ); |
992 | |
993 | while (tableau(u.pos, 1) < 0) { |
994 | std::optional<Pivot> maybePivot = findPivot(row: u.pos, direction: Direction::Up); |
995 | if (!maybePivot) |
996 | break; |
997 | |
998 | pivot(pair: *maybePivot); |
999 | if (u.orientation == Orientation::Column) |
1000 | return success(); // the unknown is unbounded above. |
1001 | } |
1002 | return success(isSuccess: tableau(u.pos, 1) >= 0); |
1003 | } |
1004 | |
1005 | /// Find a row that can be used to pivot the column in the specified direction. |
1006 | /// This returns an empty optional if and only if the column is unbounded in the |
1007 | /// specified direction (ignoring skipRow, if skipRow is set). |
1008 | /// |
1009 | /// If skipRow is set, this row is not considered, and (if it is restricted) its |
1010 | /// restriction may be violated by the returned pivot. Usually, skipRow is set |
1011 | /// because we don't want to move it to column position unless it is unbounded, |
1012 | /// and we are either trying to increase the value of skipRow or explicitly |
1013 | /// trying to make skipRow negative, so we are not concerned about this. |
1014 | /// |
1015 | /// If the direction is up (resp. down) and a restricted row has a negative |
1016 | /// (positive) coefficient for the column, then this row imposes a bound on how |
1017 | /// much the sample value of the column can change. Such a row with constant |
1018 | /// term c and coefficient f for the column imposes a bound of c/|f| on the |
1019 | /// change in sample value (in the specified direction). (note that c is |
1020 | /// non-negative here since the row is restricted and the tableau is consistent) |
1021 | /// |
1022 | /// We iterate through the rows and pick the row which imposes the most |
1023 | /// stringent bound, since pivoting with a row changes the row's sample value to |
1024 | /// 0 and hence saturates the bound it imposes. We break ties between rows that |
1025 | /// impose the same bound by considering a lexicographic ordering where we |
1026 | /// prefer unknowns with lower index value. |
1027 | std::optional<unsigned> Simplex::findPivotRow(std::optional<unsigned> skipRow, |
1028 | Direction direction, |
1029 | unsigned col) const { |
1030 | std::optional<unsigned> retRow; |
1031 | // Initialize these to zero in order to silence a warning about retElem and |
1032 | // retConst being used uninitialized in the initialization of `diff` below. In |
1033 | // reality, these are always initialized when that line is reached since these |
1034 | // are set whenever retRow is set. |
1035 | MPInt retElem, retConst; |
1036 | for (unsigned row = nRedundant, e = getNumRows(); row < e; ++row) { |
1037 | if (skipRow && row == *skipRow) |
1038 | continue; |
1039 | MPInt elem = tableau(row, col); |
1040 | if (elem == 0) |
1041 | continue; |
1042 | if (!unknownFromRow(row).restricted) |
1043 | continue; |
1044 | if (signMatchesDirection(elem, direction)) |
1045 | continue; |
1046 | MPInt constTerm = tableau(row, 1); |
1047 | |
1048 | if (!retRow) { |
1049 | retRow = row; |
1050 | retElem = elem; |
1051 | retConst = constTerm; |
1052 | continue; |
1053 | } |
1054 | |
1055 | MPInt diff = retConst * elem - constTerm * retElem; |
1056 | if ((diff == 0 && rowUnknown[row] < rowUnknown[*retRow]) || |
1057 | (diff != 0 && !signMatchesDirection(elem: diff, direction))) { |
1058 | retRow = row; |
1059 | retElem = elem; |
1060 | retConst = constTerm; |
1061 | } |
1062 | } |
1063 | return retRow; |
1064 | } |
1065 | |
1066 | bool SimplexBase::isEmpty() const { return empty; } |
1067 | |
1068 | void SimplexBase::swapRows(unsigned i, unsigned j) { |
1069 | if (i == j) |
1070 | return; |
1071 | tableau.swapRows(row: i, otherRow: j); |
1072 | std::swap(a&: rowUnknown[i], b&: rowUnknown[j]); |
1073 | unknownFromRow(row: i).pos = i; |
1074 | unknownFromRow(row: j).pos = j; |
1075 | } |
1076 | |
1077 | void SimplexBase::swapColumns(unsigned i, unsigned j) { |
1078 | assert(i < getNumColumns() && j < getNumColumns() && |
1079 | "Invalid columns provided!" ); |
1080 | if (i == j) |
1081 | return; |
1082 | tableau.swapColumns(column: i, otherColumn: j); |
1083 | std::swap(a&: colUnknown[i], b&: colUnknown[j]); |
1084 | unknownFromColumn(col: i).pos = i; |
1085 | unknownFromColumn(col: j).pos = j; |
1086 | } |
1087 | |
1088 | /// Mark this tableau empty and push an entry to the undo stack. |
1089 | void SimplexBase::markEmpty() { |
1090 | // If the set is already empty, then we shouldn't add another UnmarkEmpty log |
1091 | // entry, since in that case the Simplex will be erroneously marked as |
1092 | // non-empty when rolling back past this point. |
1093 | if (empty) |
1094 | return; |
1095 | undoLog.push_back(Elt: UndoLogEntry::UnmarkEmpty); |
1096 | empty = true; |
1097 | } |
1098 | |
1099 | /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n |
1100 | /// is the current number of variables, then the corresponding inequality is |
1101 | /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. |
1102 | /// |
1103 | /// We add the inequality and mark it as restricted. We then try to make its |
1104 | /// sample value non-negative. If this is not possible, the tableau has become |
1105 | /// empty and we mark it as such. |
1106 | void Simplex::addInequality(ArrayRef<MPInt> coeffs) { |
1107 | unsigned conIndex = addRow(coeffs, /*makeRestricted=*/true); |
1108 | LogicalResult result = restoreRow(u&: con[conIndex]); |
1109 | if (failed(result)) |
1110 | markEmpty(); |
1111 | } |
1112 | |
1113 | /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n |
1114 | /// is the current number of variables, then the corresponding equality is |
1115 | /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0. |
1116 | /// |
1117 | /// We simply add two opposing inequalities, which force the expression to |
1118 | /// be zero. |
1119 | void SimplexBase::addEquality(ArrayRef<MPInt> coeffs) { |
1120 | addInequality(coeffs); |
1121 | SmallVector<MPInt, 8> negatedCoeffs; |
1122 | for (const MPInt &coeff : coeffs) |
1123 | negatedCoeffs.emplace_back(Args: -coeff); |
1124 | addInequality(coeffs: negatedCoeffs); |
1125 | } |
1126 | |
1127 | unsigned SimplexBase::getNumVariables() const { return var.size(); } |
1128 | unsigned SimplexBase::getNumConstraints() const { return con.size(); } |
1129 | |
1130 | /// Return a snapshot of the current state. This is just the current size of the |
1131 | /// undo log. |
1132 | unsigned SimplexBase::getSnapshot() const { return undoLog.size(); } |
1133 | |
1134 | unsigned SimplexBase::getSnapshotBasis() { |
1135 | SmallVector<int, 8> basis; |
1136 | for (int index : colUnknown) { |
1137 | if (index != nullIndex) |
1138 | basis.push_back(Elt: index); |
1139 | } |
1140 | savedBases.push_back(Elt: std::move(basis)); |
1141 | |
1142 | undoLog.emplace_back(Args: UndoLogEntry::RestoreBasis); |
1143 | return undoLog.size() - 1; |
1144 | } |
1145 | |
1146 | void SimplexBase::removeLastConstraintRowOrientation() { |
1147 | assert(con.back().orientation == Orientation::Row); |
1148 | |
1149 | // Move this unknown to the last row and remove the last row from the |
1150 | // tableau. |
1151 | swapRows(i: con.back().pos, j: getNumRows() - 1); |
1152 | // It is not strictly necessary to shrink the tableau, but for now we |
1153 | // maintain the invariant that the tableau has exactly getNumRows() |
1154 | // rows. |
1155 | tableau.resizeVertically(newNRows: getNumRows() - 1); |
1156 | rowUnknown.pop_back(); |
1157 | con.pop_back(); |
1158 | } |
1159 | |
1160 | // This doesn't find a pivot row only if the column has zero |
1161 | // coefficients for every row. |
1162 | // |
1163 | // If the unknown is a constraint, this can't happen, since it was added |
1164 | // initially as a row. Such a row could never have been pivoted to a column. So |
1165 | // a pivot row will always be found if we have a constraint. |
1166 | // |
1167 | // If we have a variable, then the column has zero coefficients for every row |
1168 | // iff no constraints have been added with a non-zero coefficient for this row. |
1169 | std::optional<unsigned> SimplexBase::findAnyPivotRow(unsigned col) { |
1170 | for (unsigned row = nRedundant, e = getNumRows(); row < e; ++row) |
1171 | if (tableau(row, col) != 0) |
1172 | return row; |
1173 | return {}; |
1174 | } |
1175 | |
1176 | // It's not valid to remove the constraint by deleting the column since this |
1177 | // would result in an invalid basis. |
1178 | void Simplex::undoLastConstraint() { |
1179 | if (con.back().orientation == Orientation::Column) { |
1180 | // We try to find any pivot row for this column that preserves tableau |
1181 | // consistency (except possibly the column itself, which is going to be |
1182 | // deallocated anyway). |
1183 | // |
1184 | // If no pivot row is found in either direction, then the unknown is |
1185 | // unbounded in both directions and we are free to perform any pivot at |
1186 | // all. To do this, we just need to find any row with a non-zero |
1187 | // coefficient for the column. findAnyPivotRow will always be able to |
1188 | // find such a row for a constraint. |
1189 | unsigned column = con.back().pos; |
1190 | if (std::optional<unsigned> maybeRow = |
1191 | findPivotRow(skipRow: {}, direction: Direction::Up, col: column)) { |
1192 | pivot(pivotRow: *maybeRow, pivotCol: column); |
1193 | } else if (std::optional<unsigned> maybeRow = |
1194 | findPivotRow(skipRow: {}, direction: Direction::Down, col: column)) { |
1195 | pivot(pivotRow: *maybeRow, pivotCol: column); |
1196 | } else { |
1197 | std::optional<unsigned> row = findAnyPivotRow(col: column); |
1198 | assert(row && "Pivot should always exist for a constraint!" ); |
1199 | pivot(pivotRow: *row, pivotCol: column); |
1200 | } |
1201 | } |
1202 | removeLastConstraintRowOrientation(); |
1203 | } |
1204 | |
1205 | // It's not valid to remove the constraint by deleting the column since this |
1206 | // would result in an invalid basis. |
1207 | void LexSimplexBase::undoLastConstraint() { |
1208 | if (con.back().orientation == Orientation::Column) { |
1209 | // When removing the last constraint during a rollback, we just need to find |
1210 | // any pivot at all, i.e., any row with non-zero coefficient for the |
1211 | // column, because when rolling back a lexicographic simplex, we always |
1212 | // end by restoring the exact basis that was present at the time of the |
1213 | // snapshot, so what pivots we perform while undoing doesn't matter as |
1214 | // long as we get the unknown to row orientation and remove it. |
1215 | unsigned column = con.back().pos; |
1216 | std::optional<unsigned> row = findAnyPivotRow(col: column); |
1217 | assert(row && "Pivot should always exist for a constraint!" ); |
1218 | pivot(pivotRow: *row, pivotCol: column); |
1219 | } |
1220 | removeLastConstraintRowOrientation(); |
1221 | } |
1222 | |
1223 | void SimplexBase::undo(UndoLogEntry entry) { |
1224 | if (entry == UndoLogEntry::RemoveLastConstraint) { |
1225 | // Simplex and LexSimplex handle this differently, so we call out to a |
1226 | // virtual function to handle this. |
1227 | undoLastConstraint(); |
1228 | } else if (entry == UndoLogEntry::RemoveLastVariable) { |
1229 | // Whenever we are rolling back the addition of a variable, it is guaranteed |
1230 | // that the variable will be in column position. |
1231 | // |
1232 | // We can see this as follows: any constraint that depends on this variable |
1233 | // was added after this variable was added, so the addition of such |
1234 | // constraints should already have been rolled back by the time we get to |
1235 | // rolling back the addition of the variable. Therefore, no constraint |
1236 | // currently has a component along the variable, so the variable itself must |
1237 | // be part of the basis. |
1238 | assert(var.back().orientation == Orientation::Column && |
1239 | "Variable to be removed must be in column orientation!" ); |
1240 | |
1241 | if (var.back().isSymbol) |
1242 | nSymbol--; |
1243 | |
1244 | // Move this variable to the last column and remove the column from the |
1245 | // tableau. |
1246 | swapColumns(i: var.back().pos, j: getNumColumns() - 1); |
1247 | tableau.resizeHorizontally(newNColumns: getNumColumns() - 1); |
1248 | var.pop_back(); |
1249 | colUnknown.pop_back(); |
1250 | } else if (entry == UndoLogEntry::UnmarkEmpty) { |
1251 | empty = false; |
1252 | } else if (entry == UndoLogEntry::UnmarkLastRedundant) { |
1253 | nRedundant--; |
1254 | } else if (entry == UndoLogEntry::RestoreBasis) { |
1255 | assert(!savedBases.empty() && "No bases saved!" ); |
1256 | |
1257 | SmallVector<int, 8> basis = std::move(savedBases.back()); |
1258 | savedBases.pop_back(); |
1259 | |
1260 | for (int index : basis) { |
1261 | Unknown &u = unknownFromIndex(index); |
1262 | if (u.orientation == Orientation::Column) |
1263 | continue; |
1264 | for (unsigned col = getNumFixedCols(), e = getNumColumns(); col < e; |
1265 | col++) { |
1266 | assert(colUnknown[col] != nullIndex && |
1267 | "Column should not be a fixed column!" ); |
1268 | if (llvm::is_contained(Range&: basis, Element: colUnknown[col])) |
1269 | continue; |
1270 | if (tableau(u.pos, col) == 0) |
1271 | continue; |
1272 | pivot(pivotRow: u.pos, pivotCol: col); |
1273 | break; |
1274 | } |
1275 | |
1276 | assert(u.orientation == Orientation::Column && "No pivot found!" ); |
1277 | } |
1278 | } |
1279 | } |
1280 | |
1281 | /// Rollback to the specified snapshot. |
1282 | /// |
1283 | /// We undo all the log entries until the log size when the snapshot was taken |
1284 | /// is reached. |
1285 | void SimplexBase::rollback(unsigned snapshot) { |
1286 | while (undoLog.size() > snapshot) { |
1287 | undo(entry: undoLog.back()); |
1288 | undoLog.pop_back(); |
1289 | } |
1290 | } |
1291 | |
1292 | /// We add the usual floor division constraints: |
1293 | /// `0 <= coeffs - denom*q <= denom - 1`, where `q` is the new division |
1294 | /// variable. |
1295 | /// |
1296 | /// This constrains the remainder `coeffs - denom*q` to be in the |
1297 | /// range `[0, denom - 1]`, which fixes the integer value of the quotient `q`. |
1298 | void SimplexBase::addDivisionVariable(ArrayRef<MPInt> coeffs, |
1299 | const MPInt &denom) { |
1300 | assert(denom > 0 && "Denominator must be positive!" ); |
1301 | appendVariable(); |
1302 | |
1303 | SmallVector<MPInt, 8> ineq(coeffs.begin(), coeffs.end()); |
1304 | MPInt constTerm = ineq.back(); |
1305 | ineq.back() = -denom; |
1306 | ineq.push_back(Elt: constTerm); |
1307 | addInequality(coeffs: ineq); |
1308 | |
1309 | for (MPInt &coeff : ineq) |
1310 | coeff = -coeff; |
1311 | ineq.back() += denom - 1; |
1312 | addInequality(coeffs: ineq); |
1313 | } |
1314 | |
1315 | void SimplexBase::appendVariable(unsigned count) { |
1316 | if (count == 0) |
1317 | return; |
1318 | var.reserve(N: var.size() + count); |
1319 | colUnknown.reserve(N: colUnknown.size() + count); |
1320 | for (unsigned i = 0; i < count; ++i) { |
1321 | var.emplace_back(Args: Orientation::Column, /*restricted=*/Args: false, |
1322 | /*pos=*/Args: getNumColumns() + i); |
1323 | colUnknown.push_back(Elt: var.size() - 1); |
1324 | } |
1325 | tableau.resizeHorizontally(newNColumns: getNumColumns() + count); |
1326 | undoLog.insert(I: undoLog.end(), NumToInsert: count, Elt: UndoLogEntry::RemoveLastVariable); |
1327 | } |
1328 | |
1329 | /// Add all the constraints from the given IntegerRelation. |
1330 | void SimplexBase::intersectIntegerRelation(const IntegerRelation &rel) { |
1331 | assert(rel.getNumVars() == getNumVariables() && |
1332 | "IntegerRelation must have same dimensionality as simplex" ); |
1333 | for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) |
1334 | addInequality(coeffs: rel.getInequality(idx: i)); |
1335 | for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) |
1336 | addEquality(coeffs: rel.getEquality(idx: i)); |
1337 | } |
1338 | |
1339 | MaybeOptimum<Fraction> Simplex::computeRowOptimum(Direction direction, |
1340 | unsigned row) { |
1341 | // Keep trying to find a pivot for the row in the specified direction. |
1342 | while (std::optional<Pivot> maybePivot = findPivot(row, direction)) { |
1343 | // If findPivot returns a pivot involving the row itself, then the optimum |
1344 | // is unbounded, so we return std::nullopt. |
1345 | if (maybePivot->row == row) |
1346 | return OptimumKind::Unbounded; |
1347 | pivot(pair: *maybePivot); |
1348 | } |
1349 | |
1350 | // The row has reached its optimal sample value, which we return. |
1351 | // The sample value is the entry in the constant column divided by the common |
1352 | // denominator for this row. |
1353 | return Fraction(tableau(row, 1), tableau(row, 0)); |
1354 | } |
1355 | |
1356 | /// Compute the optimum of the specified expression in the specified direction, |
1357 | /// or std::nullopt if it is unbounded. |
1358 | MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, |
1359 | ArrayRef<MPInt> coeffs) { |
1360 | if (empty) |
1361 | return OptimumKind::Empty; |
1362 | |
1363 | SimplexRollbackScopeExit scopeExit(*this); |
1364 | unsigned conIndex = addRow(coeffs); |
1365 | unsigned row = con[conIndex].pos; |
1366 | return computeRowOptimum(direction, row); |
1367 | } |
1368 | |
1369 | MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, |
1370 | Unknown &u) { |
1371 | if (empty) |
1372 | return OptimumKind::Empty; |
1373 | if (u.orientation == Orientation::Column) { |
1374 | unsigned column = u.pos; |
1375 | std::optional<unsigned> pivotRow = findPivotRow(skipRow: {}, direction, col: column); |
1376 | // If no pivot is returned, the constraint is unbounded in the specified |
1377 | // direction. |
1378 | if (!pivotRow) |
1379 | return OptimumKind::Unbounded; |
1380 | pivot(pivotRow: *pivotRow, pivotCol: column); |
1381 | } |
1382 | |
1383 | unsigned row = u.pos; |
1384 | MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); |
1385 | if (u.restricted && direction == Direction::Down && |
1386 | (optimum.isUnbounded() || *optimum < Fraction(0, 1))) { |
1387 | if (failed(result: restoreRow(u))) |
1388 | llvm_unreachable("Could not restore row!" ); |
1389 | } |
1390 | return optimum; |
1391 | } |
1392 | |
1393 | bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) { |
1394 | assert(!empty && "It is not meaningful to ask whether a direction is bounded " |
1395 | "in an empty set." ); |
1396 | // The constraint's perpendicular is already bounded below, since it is a |
1397 | // constraint. If it is also bounded above, we can return true. |
1398 | return computeOptimum(direction: Direction::Up, u&: con[constraintIndex]).isBounded(); |
1399 | } |
1400 | |
1401 | /// Redundant constraints are those that are in row orientation and lie in |
1402 | /// rows 0 to nRedundant - 1. |
1403 | bool Simplex::isMarkedRedundant(unsigned constraintIndex) const { |
1404 | const Unknown &u = con[constraintIndex]; |
1405 | return u.orientation == Orientation::Row && u.pos < nRedundant; |
1406 | } |
1407 | |
1408 | /// Mark the specified row redundant. |
1409 | /// |
1410 | /// This is done by moving the unknown to the end of the block of redundant |
1411 | /// rows (namely, to row nRedundant) and incrementing nRedundant to |
1412 | /// accomodate the new redundant row. |
1413 | void Simplex::markRowRedundant(Unknown &u) { |
1414 | assert(u.orientation == Orientation::Row && |
1415 | "Unknown should be in row position!" ); |
1416 | assert(u.pos >= nRedundant && "Unknown is already marked redundant!" ); |
1417 | swapRows(i: u.pos, j: nRedundant); |
1418 | ++nRedundant; |
1419 | undoLog.emplace_back(Args: UndoLogEntry::UnmarkLastRedundant); |
1420 | } |
1421 | |
1422 | /// Find a subset of constraints that is redundant and mark them redundant. |
1423 | void Simplex::detectRedundant(unsigned offset, unsigned count) { |
1424 | assert(offset + count <= con.size() && "invalid range!" ); |
1425 | // It is not meaningful to talk about redundancy for empty sets. |
1426 | if (empty) |
1427 | return; |
1428 | |
1429 | // Iterate through the constraints and check for each one if it can attain |
1430 | // negative sample values. If it can, it's not redundant. Otherwise, it is. |
1431 | // We mark redundant constraints redundant. |
1432 | // |
1433 | // Constraints that get marked redundant in one iteration are not respected |
1434 | // when checking constraints in later iterations. This prevents, for example, |
1435 | // two identical constraints both being marked redundant since each is |
1436 | // redundant given the other one. In this example, only the first of the |
1437 | // constraints that is processed will get marked redundant, as it should be. |
1438 | for (unsigned i = 0; i < count; ++i) { |
1439 | Unknown &u = con[offset + i]; |
1440 | if (u.orientation == Orientation::Column) { |
1441 | unsigned column = u.pos; |
1442 | std::optional<unsigned> pivotRow = |
1443 | findPivotRow(skipRow: {}, direction: Direction::Down, col: column); |
1444 | // If no downward pivot is returned, the constraint is unbounded below |
1445 | // and hence not redundant. |
1446 | if (!pivotRow) |
1447 | continue; |
1448 | pivot(pivotRow: *pivotRow, pivotCol: column); |
1449 | } |
1450 | |
1451 | unsigned row = u.pos; |
1452 | MaybeOptimum<Fraction> minimum = computeRowOptimum(direction: Direction::Down, row); |
1453 | if (minimum.isUnbounded() || *minimum < Fraction(0, 1)) { |
1454 | // Constraint is unbounded below or can attain negative sample values and |
1455 | // hence is not redundant. |
1456 | if (failed(result: restoreRow(u))) |
1457 | llvm_unreachable("Could not restore non-redundant row!" ); |
1458 | continue; |
1459 | } |
1460 | |
1461 | markRowRedundant(u); |
1462 | } |
1463 | } |
1464 | |
1465 | bool Simplex::isUnbounded() { |
1466 | if (empty) |
1467 | return false; |
1468 | |
1469 | SmallVector<MPInt, 8> dir(var.size() + 1); |
1470 | for (unsigned i = 0; i < var.size(); ++i) { |
1471 | dir[i] = 1; |
1472 | |
1473 | if (computeOptimum(direction: Direction::Up, coeffs: dir).isUnbounded()) |
1474 | return true; |
1475 | |
1476 | if (computeOptimum(direction: Direction::Down, coeffs: dir).isUnbounded()) |
1477 | return true; |
1478 | |
1479 | dir[i] = 0; |
1480 | } |
1481 | return false; |
1482 | } |
1483 | |
1484 | /// Make a tableau to represent a pair of points in the original tableau. |
1485 | /// |
1486 | /// The product constraints and variables are stored as: first A's, then B's. |
1487 | /// |
1488 | /// The product tableau has row layout: |
1489 | /// A's redundant rows, B's redundant rows, A's other rows, B's other rows. |
1490 | /// |
1491 | /// It has column layout: |
1492 | /// denominator, constant, A's columns, B's columns. |
1493 | Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) { |
1494 | unsigned numVar = a.getNumVariables() + b.getNumVariables(); |
1495 | unsigned numCon = a.getNumConstraints() + b.getNumConstraints(); |
1496 | Simplex result(numVar); |
1497 | |
1498 | result.tableau.reserveRows(rows: numCon); |
1499 | result.empty = a.empty || b.empty; |
1500 | |
1501 | auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) { |
1502 | SmallVector<Unknown, 8> result; |
1503 | result.reserve(N: v.size() + w.size()); |
1504 | result.insert(I: result.end(), From: v.begin(), To: v.end()); |
1505 | result.insert(I: result.end(), From: w.begin(), To: w.end()); |
1506 | return result; |
1507 | }; |
1508 | result.con = concat(a.con, b.con); |
1509 | result.var = concat(a.var, b.var); |
1510 | |
1511 | auto indexFromBIndex = [&](int index) { |
1512 | return index >= 0 ? a.getNumVariables() + index |
1513 | : ~(a.getNumConstraints() + ~index); |
1514 | }; |
1515 | |
1516 | result.colUnknown.assign(NumElts: 2, Elt: nullIndex); |
1517 | for (unsigned i = 2, e = a.getNumColumns(); i < e; ++i) { |
1518 | result.colUnknown.push_back(Elt: a.colUnknown[i]); |
1519 | result.unknownFromIndex(index: result.colUnknown.back()).pos = |
1520 | result.colUnknown.size() - 1; |
1521 | } |
1522 | for (unsigned i = 2, e = b.getNumColumns(); i < e; ++i) { |
1523 | result.colUnknown.push_back(Elt: indexFromBIndex(b.colUnknown[i])); |
1524 | result.unknownFromIndex(index: result.colUnknown.back()).pos = |
1525 | result.colUnknown.size() - 1; |
1526 | } |
1527 | |
1528 | auto appendRowFromA = [&](unsigned row) { |
1529 | unsigned resultRow = result.tableau.appendExtraRow(); |
1530 | for (unsigned col = 0, e = a.getNumColumns(); col < e; ++col) |
1531 | result.tableau(resultRow, col) = a.tableau(row, col); |
1532 | result.rowUnknown.push_back(Elt: a.rowUnknown[row]); |
1533 | result.unknownFromIndex(index: result.rowUnknown.back()).pos = |
1534 | result.rowUnknown.size() - 1; |
1535 | }; |
1536 | |
1537 | // Also fixes the corresponding entry in rowUnknown and var/con (as the case |
1538 | // may be). |
1539 | auto appendRowFromB = [&](unsigned row) { |
1540 | unsigned resultRow = result.tableau.appendExtraRow(); |
1541 | result.tableau(resultRow, 0) = b.tableau(row, 0); |
1542 | result.tableau(resultRow, 1) = b.tableau(row, 1); |
1543 | |
1544 | unsigned offset = a.getNumColumns() - 2; |
1545 | for (unsigned col = 2, e = b.getNumColumns(); col < e; ++col) |
1546 | result.tableau(resultRow, offset + col) = b.tableau(row, col); |
1547 | result.rowUnknown.push_back(Elt: indexFromBIndex(b.rowUnknown[row])); |
1548 | result.unknownFromIndex(index: result.rowUnknown.back()).pos = |
1549 | result.rowUnknown.size() - 1; |
1550 | }; |
1551 | |
1552 | result.nRedundant = a.nRedundant + b.nRedundant; |
1553 | for (unsigned row = 0; row < a.nRedundant; ++row) |
1554 | appendRowFromA(row); |
1555 | for (unsigned row = 0; row < b.nRedundant; ++row) |
1556 | appendRowFromB(row); |
1557 | for (unsigned row = a.nRedundant, e = a.getNumRows(); row < e; ++row) |
1558 | appendRowFromA(row); |
1559 | for (unsigned row = b.nRedundant, e = b.getNumRows(); row < e; ++row) |
1560 | appendRowFromB(row); |
1561 | |
1562 | return result; |
1563 | } |
1564 | |
1565 | std::optional<SmallVector<Fraction, 8>> Simplex::getRationalSample() const { |
1566 | if (empty) |
1567 | return {}; |
1568 | |
1569 | SmallVector<Fraction, 8> sample; |
1570 | sample.reserve(N: var.size()); |
1571 | // Push the sample value for each variable into the vector. |
1572 | for (const Unknown &u : var) { |
1573 | if (u.orientation == Orientation::Column) { |
1574 | // If the variable is in column position, its sample value is zero. |
1575 | sample.emplace_back(Args: 0, Args: 1); |
1576 | } else { |
1577 | // If the variable is in row position, its sample value is the |
1578 | // entry in the constant column divided by the denominator. |
1579 | MPInt denom = tableau(u.pos, 0); |
1580 | sample.emplace_back(Args: tableau(u.pos, 1), Args&: denom); |
1581 | } |
1582 | } |
1583 | return sample; |
1584 | } |
1585 | |
1586 | void LexSimplexBase::addInequality(ArrayRef<MPInt> coeffs) { |
1587 | addRow(coeffs, /*makeRestricted=*/true); |
1588 | } |
1589 | |
1590 | MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::getRationalSample() const { |
1591 | if (empty) |
1592 | return OptimumKind::Empty; |
1593 | |
1594 | SmallVector<Fraction, 8> sample; |
1595 | sample.reserve(N: var.size()); |
1596 | // Push the sample value for each variable into the vector. |
1597 | for (const Unknown &u : var) { |
1598 | // When the big M parameter is being used, each variable x is represented |
1599 | // as M + x, so its sample value is finite if and only if it is of the |
1600 | // form 1*M + c. If the coefficient of M is not one then the sample value |
1601 | // is infinite, and we return an empty optional. |
1602 | |
1603 | if (u.orientation == Orientation::Column) { |
1604 | // If the variable is in column position, the sample value of M + x is |
1605 | // zero, so x = -M which is unbounded. |
1606 | return OptimumKind::Unbounded; |
1607 | } |
1608 | |
1609 | // If the variable is in row position, its sample value is the |
1610 | // entry in the constant column divided by the denominator. |
1611 | MPInt denom = tableau(u.pos, 0); |
1612 | if (usingBigM) |
1613 | if (tableau(u.pos, 2) != denom) |
1614 | return OptimumKind::Unbounded; |
1615 | sample.emplace_back(Args: tableau(u.pos, 1), Args&: denom); |
1616 | } |
1617 | return sample; |
1618 | } |
1619 | |
1620 | std::optional<SmallVector<MPInt, 8>> Simplex::getSamplePointIfIntegral() const { |
1621 | // If the tableau is empty, no sample point exists. |
1622 | if (empty) |
1623 | return {}; |
1624 | |
1625 | // The value will always exist since the Simplex is non-empty. |
1626 | SmallVector<Fraction, 8> rationalSample = *getRationalSample(); |
1627 | SmallVector<MPInt, 8> integerSample; |
1628 | integerSample.reserve(N: var.size()); |
1629 | for (const Fraction &coord : rationalSample) { |
1630 | // If the sample is non-integral, return std::nullopt. |
1631 | if (coord.num % coord.den != 0) |
1632 | return {}; |
1633 | integerSample.push_back(Elt: coord.num / coord.den); |
1634 | } |
1635 | return integerSample; |
1636 | } |
1637 | |
1638 | /// Given a simplex for a polytope, construct a new simplex whose variables are |
1639 | /// identified with a pair of points (x, y) in the original polytope. Supports |
1640 | /// some operations needed for generalized basis reduction. In what follows, |
1641 | /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the |
1642 | /// dimension of the original polytope. |
1643 | /// |
1644 | /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It |
1645 | /// also supports rolling back this addition, by maintaining a snapshot stack |
1646 | /// that contains a snapshot of the Simplex's state for each equality, just |
1647 | /// before that equality was added. |
1648 | class presburger::GBRSimplex { |
1649 | using Orientation = Simplex::Orientation; |
1650 | |
1651 | public: |
1652 | GBRSimplex(const Simplex &originalSimplex) |
1653 | : simplex(Simplex::makeProduct(a: originalSimplex, b: originalSimplex)), |
1654 | simplexConstraintOffset(simplex.getNumConstraints()) {} |
1655 | |
1656 | /// Add an equality dotProduct(dir, x - y) == 0. |
1657 | /// First pushes a snapshot for the current simplex state to the stack so |
1658 | /// that this can be rolled back later. |
1659 | void addEqualityForDirection(ArrayRef<MPInt> dir) { |
1660 | assert(llvm::any_of(dir, [](const MPInt &x) { return x != 0; }) && |
1661 | "Direction passed is the zero vector!" ); |
1662 | snapshotStack.push_back(Elt: simplex.getSnapshot()); |
1663 | simplex.addEquality(coeffs: getCoeffsForDirection(dir)); |
1664 | } |
1665 | /// Compute max(dotProduct(dir, x - y)). |
1666 | Fraction computeWidth(ArrayRef<MPInt> dir) { |
1667 | MaybeOptimum<Fraction> maybeWidth = |
1668 | simplex.computeOptimum(direction: Direction::Up, coeffs: getCoeffsForDirection(dir)); |
1669 | assert(maybeWidth.isBounded() && "Width should be bounded!" ); |
1670 | return *maybeWidth; |
1671 | } |
1672 | |
1673 | /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only |
1674 | /// the direction equalities to `dual`. |
1675 | Fraction computeWidthAndDuals(ArrayRef<MPInt> dir, |
1676 | SmallVectorImpl<MPInt> &dual, |
1677 | MPInt &dualDenom) { |
1678 | // We can't just call into computeWidth or computeOptimum since we need to |
1679 | // access the state of the tableau after computing the optimum, and these |
1680 | // functions rollback the insertion of the objective function into the |
1681 | // tableau before returning. We instead add a row for the objective function |
1682 | // ourselves, call into computeOptimum, compute the duals from the tableau |
1683 | // state, and finally rollback the addition of the row before returning. |
1684 | SimplexRollbackScopeExit scopeExit(simplex); |
1685 | unsigned conIndex = simplex.addRow(coeffs: getCoeffsForDirection(dir)); |
1686 | unsigned row = simplex.con[conIndex].pos; |
1687 | MaybeOptimum<Fraction> maybeWidth = |
1688 | simplex.computeRowOptimum(direction: Simplex::Direction::Up, row); |
1689 | assert(maybeWidth.isBounded() && "Width should be bounded!" ); |
1690 | dualDenom = simplex.tableau(row, 0); |
1691 | dual.clear(); |
1692 | |
1693 | // The increment is i += 2 because equalities are added as two inequalities, |
1694 | // one positive and one negative. Each iteration processes one equality. |
1695 | for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) { |
1696 | // The dual variable for an inequality in column orientation is the |
1697 | // negative of its coefficient at the objective row. If the inequality is |
1698 | // in row orientation, the corresponding dual variable is zero. |
1699 | // |
1700 | // We want the dual for the original equality, which corresponds to two |
1701 | // inequalities: a positive inequality, which has the same coefficients as |
1702 | // the equality, and a negative equality, which has negated coefficients. |
1703 | // |
1704 | // Note that at most one of these inequalities can be in column |
1705 | // orientation because the column unknowns should form a basis and hence |
1706 | // must be linearly independent. If the positive inequality is in column |
1707 | // position, its dual is the dual corresponding to the equality. If the |
1708 | // negative inequality is in column position, the negation of its dual is |
1709 | // the dual corresponding to the equality. If neither is in column |
1710 | // position, then that means that this equality is redundant, and its dual |
1711 | // is zero. |
1712 | // |
1713 | // Note that it is NOT valid to perform pivots during the computation of |
1714 | // the duals. This entire dual computation must be performed on the same |
1715 | // tableau configuration. |
1716 | assert(!(simplex.con[i].orientation == Orientation::Column && |
1717 | simplex.con[i + 1].orientation == Orientation::Column) && |
1718 | "Both inequalities for the equality cannot be in column " |
1719 | "orientation!" ); |
1720 | if (simplex.con[i].orientation == Orientation::Column) |
1721 | dual.push_back(Elt: -simplex.tableau(row, simplex.con[i].pos)); |
1722 | else if (simplex.con[i + 1].orientation == Orientation::Column) |
1723 | dual.push_back(Elt: simplex.tableau(row, simplex.con[i + 1].pos)); |
1724 | else |
1725 | dual.emplace_back(Args: 0); |
1726 | } |
1727 | return *maybeWidth; |
1728 | } |
1729 | |
1730 | /// Remove the last equality that was added through addEqualityForDirection. |
1731 | /// |
1732 | /// We do this by rolling back to the snapshot at the top of the stack, which |
1733 | /// should be a snapshot taken just before the last equality was added. |
1734 | void removeLastEquality() { |
1735 | assert(!snapshotStack.empty() && "Snapshot stack is empty!" ); |
1736 | simplex.rollback(snapshot: snapshotStack.back()); |
1737 | snapshotStack.pop_back(); |
1738 | } |
1739 | |
1740 | private: |
1741 | /// Returns coefficients of the expression 'dot_product(dir, x - y)', |
1742 | /// i.e., dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n |
1743 | /// - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n, |
1744 | /// where n is the dimension of the original polytope. |
1745 | SmallVector<MPInt, 8> getCoeffsForDirection(ArrayRef<MPInt> dir) { |
1746 | assert(2 * dir.size() == simplex.getNumVariables() && |
1747 | "Direction vector has wrong dimensionality" ); |
1748 | SmallVector<MPInt, 8> coeffs(dir.begin(), dir.end()); |
1749 | coeffs.reserve(N: 2 * dir.size()); |
1750 | for (const MPInt &coeff : dir) |
1751 | coeffs.push_back(Elt: -coeff); |
1752 | coeffs.emplace_back(Args: 0); // constant term |
1753 | return coeffs; |
1754 | } |
1755 | |
1756 | Simplex simplex; |
1757 | /// The first index of the equality constraints, the index immediately after |
1758 | /// the last constraint in the initial product simplex. |
1759 | unsigned simplexConstraintOffset; |
1760 | /// A stack of snapshots, used for rolling back. |
1761 | SmallVector<unsigned, 8> snapshotStack; |
1762 | }; |
1763 | |
1764 | /// Reduce the basis to try and find a direction in which the polytope is |
1765 | /// "thin". This only works for bounded polytopes. |
1766 | /// |
1767 | /// This is an implementation of the algorithm described in the paper |
1768 | /// "An Implementation of Generalized Basis Reduction for Integer Programming" |
1769 | /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross. |
1770 | /// |
1771 | /// Let b_{level}, b_{level + 1}, ... b_n be the current basis. |
1772 | /// Let width_i(v) = max <v, x - y> where x and y are points in the original |
1773 | /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i. |
1774 | /// |
1775 | /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u |
1776 | /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i |
1777 | /// be the dual variable associated with the constraint <b_i, x - y> = 0 when |
1778 | /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the |
1779 | /// minimizing value of u, if it were allowed to be fractional. Due to |
1780 | /// convexity, the minimizing integer value is either floor(dual_i) or |
1781 | /// ceil(dual_i), so we just need to check which of these gives a lower |
1782 | /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i. |
1783 | /// |
1784 | /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new) |
1785 | /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the |
1786 | /// same i). Otherwise, we increment i. |
1787 | /// |
1788 | /// We keep f values and duals cached and invalidate them when necessary. |
1789 | /// Whenever possible, we use them instead of recomputing them. We implement the |
1790 | /// algorithm as follows. |
1791 | /// |
1792 | /// In an iteration at i we need to compute: |
1793 | /// a) width_i(b_{i + 1}) |
1794 | /// b) width_i(b_i) |
1795 | /// c) the integer u that minimizes width_i(b_{i + 1} + u*b_i) |
1796 | /// |
1797 | /// If width_i(b_i) is not already cached, we compute it. |
1798 | /// |
1799 | /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and |
1800 | /// store the duals from this computation. |
1801 | /// |
1802 | /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value |
1803 | /// of u as explained before, caches the duals from this computation, sets |
1804 | /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}). |
1805 | /// |
1806 | /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and |
1807 | /// decrement i, resulting in the basis |
1808 | /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ... |
1809 | /// with corresponding f values |
1810 | /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ... |
1811 | /// The values up to i - 1 remain unchanged. We have just gotten the middle |
1812 | /// value from updateBasisWithUAndGetFCandidate, so we can update that in the |
1813 | /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from |
1814 | /// the cache. The iteration after decrementing needs exactly the duals from the |
1815 | /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache. |
1816 | /// |
1817 | /// When incrementing i, no cached f values get invalidated. However, the cached |
1818 | /// duals do get invalidated as the duals for the higher levels are different. |
1819 | void Simplex::reduceBasis(IntMatrix &basis, unsigned level) { |
1820 | const Fraction epsilon(3, 4); |
1821 | |
1822 | if (level == basis.getNumRows() - 1) |
1823 | return; |
1824 | |
1825 | GBRSimplex gbrSimplex(*this); |
1826 | SmallVector<Fraction, 8> width; |
1827 | SmallVector<MPInt, 8> dual; |
1828 | MPInt dualDenom; |
1829 | |
1830 | // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the |
1831 | // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns |
1832 | // the new value of width_i(b_{i+1}). |
1833 | // |
1834 | // If dual_i is not an integer, the minimizing value must be either |
1835 | // floor(dual_i) or ceil(dual_i). We compute the expression for both and |
1836 | // choose the minimizing value. |
1837 | // |
1838 | // If dual_i is an integer, we don't need to perform these computations. We |
1839 | // know that in this case, |
1840 | // a) u = dual_i. |
1841 | // b) one can show that dual_j for j < i are the same duals we would have |
1842 | // gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals |
1843 | // are the ones already in the cache. |
1844 | // c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i), |
1845 | // which |
1846 | // one can show is equal to width_{i+1}(b_{i+1}). The latter value must |
1847 | // be in the cache, so we get it from there and return it. |
1848 | auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction { |
1849 | assert(i < level + dual.size() && "dual_i is not known!" ); |
1850 | |
1851 | MPInt u = floorDiv(lhs: dual[i - level], rhs: dualDenom); |
1852 | basis.addToRow(sourceRow: i, targetRow: i + 1, scale: u); |
1853 | if (dual[i - level] % dualDenom != 0) { |
1854 | SmallVector<MPInt, 8> candidateDual[2]; |
1855 | MPInt candidateDualDenom[2]; |
1856 | Fraction widthI[2]; |
1857 | |
1858 | // Initially u is floor(dual) and basis reflects this. |
1859 | widthI[0] = gbrSimplex.computeWidthAndDuals( |
1860 | dir: basis.getRow(row: i + 1), dual&: candidateDual[0], dualDenom&: candidateDualDenom[0]); |
1861 | |
1862 | // Now try ceil(dual), i.e. floor(dual) + 1. |
1863 | ++u; |
1864 | basis.addToRow(sourceRow: i, targetRow: i + 1, scale: 1); |
1865 | widthI[1] = gbrSimplex.computeWidthAndDuals( |
1866 | dir: basis.getRow(row: i + 1), dual&: candidateDual[1], dualDenom&: candidateDualDenom[1]); |
1867 | |
1868 | unsigned j = widthI[0] < widthI[1] ? 0 : 1; |
1869 | if (j == 0) |
1870 | // Subtract 1 to go from u = ceil(dual) back to floor(dual). |
1871 | basis.addToRow(sourceRow: i, targetRow: i + 1, scale: -1); |
1872 | |
1873 | // width_i(b{i+1} + u*b_i) should be minimized at our value of u. |
1874 | // We assert that this holds by checking that the values of width_i at |
1875 | // u - 1 and u + 1 are greater than or equal to the value at u. If the |
1876 | // width is lesser at either of the adjacent values, then our computed |
1877 | // value of u is clearly not the minimizer. Otherwise by convexity the |
1878 | // computed value of u is really the minimizer. |
1879 | |
1880 | // Check the value at u - 1. |
1881 | assert(gbrSimplex.computeWidth(scaleAndAddForAssert( |
1882 | basis.getRow(i + 1), MPInt(-1), basis.getRow(i))) >= |
1883 | widthI[j] && |
1884 | "Computed u value does not minimize the width!" ); |
1885 | // Check the value at u + 1. |
1886 | assert(gbrSimplex.computeWidth(scaleAndAddForAssert( |
1887 | basis.getRow(i + 1), MPInt(+1), basis.getRow(i))) >= |
1888 | widthI[j] && |
1889 | "Computed u value does not minimize the width!" ); |
1890 | |
1891 | dual = std::move(candidateDual[j]); |
1892 | dualDenom = candidateDualDenom[j]; |
1893 | return widthI[j]; |
1894 | } |
1895 | |
1896 | assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved" ); |
1897 | // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the |
1898 | // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in |
1899 | // the above expression is equal to basis.getRow(i+1) below.) |
1900 | assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) == |
1901 | width[i + 1 - level]); |
1902 | return width[i + 1 - level]; |
1903 | }; |
1904 | |
1905 | // In the ith iteration of the loop, gbrSimplex has constraints for directions |
1906 | // from `level` to i - 1. |
1907 | unsigned i = level; |
1908 | while (i < basis.getNumRows() - 1) { |
1909 | if (i >= level + width.size()) { |
1910 | // We don't even know the value of f_i(b_i), so let's find that first. |
1911 | // We have to do this first since later we assume that width already |
1912 | // contains values up to and including i. |
1913 | |
1914 | assert((i == 0 || i - 1 < level + width.size()) && |
1915 | "We are at level i but we don't know the value of width_{i-1}" ); |
1916 | |
1917 | // We don't actually use these duals at all, but it doesn't matter |
1918 | // because this case should only occur when i is level, and there are no |
1919 | // duals in that case anyway. |
1920 | assert(i == level && "This case should only occur when i == level" ); |
1921 | width.push_back( |
1922 | Elt: gbrSimplex.computeWidthAndDuals(dir: basis.getRow(row: i), dual, dualDenom)); |
1923 | } |
1924 | |
1925 | if (i >= level + dual.size()) { |
1926 | assert(i + 1 >= level + width.size() && |
1927 | "We don't know dual_i but we know width_{i+1}" ); |
1928 | // We don't know dual for our level, so let's find it. |
1929 | gbrSimplex.addEqualityForDirection(dir: basis.getRow(row: i)); |
1930 | width.push_back(Elt: gbrSimplex.computeWidthAndDuals(dir: basis.getRow(row: i + 1), dual, |
1931 | dualDenom)); |
1932 | gbrSimplex.removeLastEquality(); |
1933 | } |
1934 | |
1935 | // This variable stores width_i(b_{i+1} + u*b_i). |
1936 | Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i); |
1937 | if (widthICandidate < epsilon * width[i - level]) { |
1938 | basis.swapRows(row: i, otherRow: i + 1); |
1939 | width[i - level] = widthICandidate; |
1940 | // The values of width_{i+1}(b_{i+1}) and higher may change after the |
1941 | // swap, so we remove the cached values here. |
1942 | width.resize(N: i - level + 1); |
1943 | if (i == level) { |
1944 | dual.clear(); |
1945 | continue; |
1946 | } |
1947 | |
1948 | gbrSimplex.removeLastEquality(); |
1949 | i--; |
1950 | continue; |
1951 | } |
1952 | |
1953 | // Invalidate duals since the higher level needs to recompute its own duals. |
1954 | dual.clear(); |
1955 | gbrSimplex.addEqualityForDirection(dir: basis.getRow(row: i)); |
1956 | i++; |
1957 | } |
1958 | } |
1959 | |
1960 | /// Search for an integer sample point using a branch and bound algorithm. |
1961 | /// |
1962 | /// Each row in the basis matrix is a vector, and the set of basis vectors |
1963 | /// should span the space. Initially this is the identity matrix, |
1964 | /// i.e., the basis vectors are just the variables. |
1965 | /// |
1966 | /// In every level, a value is assigned to the level-th basis vector, as |
1967 | /// follows. Compute the minimum and maximum rational values of this direction. |
1968 | /// If only one integer point lies in this range, constrain the variable to |
1969 | /// have this value and recurse to the next variable. |
1970 | /// |
1971 | /// If the range has multiple values, perform generalized basis reduction via |
1972 | /// reduceBasis and then compute the bounds again. Now we try constraining |
1973 | /// this direction in the first value in this range and "recurse" to the next |
1974 | /// level. If we fail to find a sample, we try assigning the direction the next |
1975 | /// value in this range, and so on. |
1976 | /// |
1977 | /// If no integer sample is found from any of the assignments, or if the range |
1978 | /// contains no integer value, then of course the polytope is empty for the |
1979 | /// current assignment of the values in previous levels, so we return to |
1980 | /// the previous level. |
1981 | /// |
1982 | /// If we reach the last level where all the variables have been assigned values |
1983 | /// already, then we simply return the current sample point if it is integral, |
1984 | /// and go back to the previous level otherwise. |
1985 | /// |
1986 | /// To avoid potentially arbitrarily large recursion depths leading to stack |
1987 | /// overflows, this algorithm is implemented iteratively. |
1988 | std::optional<SmallVector<MPInt, 8>> Simplex::findIntegerSample() { |
1989 | if (empty) |
1990 | return {}; |
1991 | |
1992 | unsigned nDims = var.size(); |
1993 | IntMatrix basis = IntMatrix::identity(dimension: nDims); |
1994 | |
1995 | unsigned level = 0; |
1996 | // The snapshot just before constraining a direction to a value at each level. |
1997 | SmallVector<unsigned, 8> snapshotStack; |
1998 | // The maximum value in the range of the direction for each level. |
1999 | SmallVector<MPInt, 8> upperBoundStack; |
2000 | // The next value to try constraining the basis vector to at each level. |
2001 | SmallVector<MPInt, 8> nextValueStack; |
2002 | |
2003 | snapshotStack.reserve(N: basis.getNumRows()); |
2004 | upperBoundStack.reserve(N: basis.getNumRows()); |
2005 | nextValueStack.reserve(N: basis.getNumRows()); |
2006 | while (level != -1u) { |
2007 | if (level == basis.getNumRows()) { |
2008 | // We've assigned values to all variables. Return if we have a sample, |
2009 | // or go back up to the previous level otherwise. |
2010 | if (auto maybeSample = getSamplePointIfIntegral()) |
2011 | return maybeSample; |
2012 | level--; |
2013 | continue; |
2014 | } |
2015 | |
2016 | if (level >= upperBoundStack.size()) { |
2017 | // We haven't populated the stack values for this level yet, so we have |
2018 | // just come down a level ("recursed"). Find the lower and upper bounds. |
2019 | // If there is more than one integer point in the range, perform |
2020 | // generalized basis reduction. |
2021 | SmallVector<MPInt, 8> basisCoeffs = |
2022 | llvm::to_vector<8>(Range: basis.getRow(row: level)); |
2023 | basisCoeffs.emplace_back(Args: 0); |
2024 | |
2025 | auto [minRoundedUp, maxRoundedDown] = computeIntegerBounds(coeffs: basisCoeffs); |
2026 | |
2027 | // We don't have any integer values in the range. |
2028 | // Pop the stack and return up a level. |
2029 | if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) { |
2030 | assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) && |
2031 | "If one bound is empty, both should be." ); |
2032 | snapshotStack.pop_back(); |
2033 | nextValueStack.pop_back(); |
2034 | upperBoundStack.pop_back(); |
2035 | level--; |
2036 | continue; |
2037 | } |
2038 | |
2039 | // We already checked the empty case above. |
2040 | assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) && |
2041 | "Polyhedron should be bounded!" ); |
2042 | |
2043 | // Heuristic: if the sample point is integral at this point, just return |
2044 | // it. |
2045 | if (auto maybeSample = getSamplePointIfIntegral()) |
2046 | return *maybeSample; |
2047 | |
2048 | if (*minRoundedUp < *maxRoundedDown) { |
2049 | reduceBasis(basis, level); |
2050 | basisCoeffs = llvm::to_vector<8>(Range: basis.getRow(row: level)); |
2051 | basisCoeffs.emplace_back(Args: 0); |
2052 | std::tie(args&: minRoundedUp, args&: maxRoundedDown) = |
2053 | computeIntegerBounds(coeffs: basisCoeffs); |
2054 | } |
2055 | |
2056 | snapshotStack.push_back(Elt: getSnapshot()); |
2057 | // The smallest value in the range is the next value to try. |
2058 | // The values in the optionals are guaranteed to exist since we know the |
2059 | // polytope is bounded. |
2060 | nextValueStack.push_back(Elt: *minRoundedUp); |
2061 | upperBoundStack.push_back(Elt: *maxRoundedDown); |
2062 | } |
2063 | |
2064 | assert((snapshotStack.size() - 1 == level && |
2065 | nextValueStack.size() - 1 == level && |
2066 | upperBoundStack.size() - 1 == level) && |
2067 | "Mismatched variable stack sizes!" ); |
2068 | |
2069 | // Whether we "recursed" or "returned" from a lower level, we rollback |
2070 | // to the snapshot of the starting state at this level. (in the "recursed" |
2071 | // case this has no effect) |
2072 | rollback(snapshot: snapshotStack.back()); |
2073 | MPInt nextValue = nextValueStack.back(); |
2074 | ++nextValueStack.back(); |
2075 | if (nextValue > upperBoundStack.back()) { |
2076 | // We have exhausted the range and found no solution. Pop the stack and |
2077 | // return up a level. |
2078 | snapshotStack.pop_back(); |
2079 | nextValueStack.pop_back(); |
2080 | upperBoundStack.pop_back(); |
2081 | level--; |
2082 | continue; |
2083 | } |
2084 | |
2085 | // Try the next value in the range and "recurse" into the next level. |
2086 | SmallVector<MPInt, 8> basisCoeffs(basis.getRow(row: level).begin(), |
2087 | basis.getRow(row: level).end()); |
2088 | basisCoeffs.push_back(Elt: -nextValue); |
2089 | addEquality(coeffs: basisCoeffs); |
2090 | level++; |
2091 | } |
2092 | |
2093 | return {}; |
2094 | } |
2095 | |
2096 | /// Compute the minimum and maximum integer values the expression can take. We |
2097 | /// compute each separately. |
2098 | std::pair<MaybeOptimum<MPInt>, MaybeOptimum<MPInt>> |
2099 | Simplex::computeIntegerBounds(ArrayRef<MPInt> coeffs) { |
2100 | MaybeOptimum<MPInt> minRoundedUp( |
2101 | computeOptimum(direction: Simplex::Direction::Down, coeffs).map(f&: ceil)); |
2102 | MaybeOptimum<MPInt> maxRoundedDown( |
2103 | computeOptimum(direction: Simplex::Direction::Up, coeffs).map(f&: floor)); |
2104 | return {minRoundedUp, maxRoundedDown}; |
2105 | } |
2106 | |
2107 | bool Simplex::isFlatAlong(ArrayRef<MPInt> coeffs) { |
2108 | assert(!isEmpty() && "cannot check for flatness of empty simplex!" ); |
2109 | auto upOpt = computeOptimum(direction: Simplex::Direction::Up, coeffs); |
2110 | auto downOpt = computeOptimum(direction: Simplex::Direction::Down, coeffs); |
2111 | |
2112 | if (!upOpt.isBounded()) |
2113 | return false; |
2114 | if (!downOpt.isBounded()) |
2115 | return false; |
2116 | |
2117 | return *upOpt == *downOpt; |
2118 | } |
2119 | |
2120 | void SimplexBase::print(raw_ostream &os) const { |
2121 | os << "rows = " << getNumRows() << ", columns = " << getNumColumns() << "\n" ; |
2122 | if (empty) |
2123 | os << "Simplex marked empty!\n" ; |
2124 | os << "var: " ; |
2125 | for (unsigned i = 0; i < var.size(); ++i) { |
2126 | if (i > 0) |
2127 | os << ", " ; |
2128 | var[i].print(os); |
2129 | } |
2130 | os << "\ncon: " ; |
2131 | for (unsigned i = 0; i < con.size(); ++i) { |
2132 | if (i > 0) |
2133 | os << ", " ; |
2134 | con[i].print(os); |
2135 | } |
2136 | os << '\n'; |
2137 | for (unsigned row = 0, e = getNumRows(); row < e; ++row) { |
2138 | if (row > 0) |
2139 | os << ", " ; |
2140 | os << "r" << row << ": " << rowUnknown[row]; |
2141 | } |
2142 | os << '\n'; |
2143 | os << "c0: denom, c1: const" ; |
2144 | for (unsigned col = 2, e = getNumColumns(); col < e; ++col) |
2145 | os << ", c" << col << ": " << colUnknown[col]; |
2146 | os << '\n'; |
2147 | for (unsigned row = 0, numRows = getNumRows(); row < numRows; ++row) { |
2148 | for (unsigned col = 0, numCols = getNumColumns(); col < numCols; ++col) |
2149 | os << tableau(row, col) << '\t'; |
2150 | os << '\n'; |
2151 | } |
2152 | os << '\n'; |
2153 | } |
2154 | |
2155 | void SimplexBase::dump() const { print(os&: llvm::errs()); } |
2156 | |
2157 | bool Simplex::isRationalSubsetOf(const IntegerRelation &rel) { |
2158 | if (isEmpty()) |
2159 | return true; |
2160 | |
2161 | for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) |
2162 | if (findIneqType(coeffs: rel.getInequality(idx: i)) != IneqType::Redundant) |
2163 | return false; |
2164 | |
2165 | for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) |
2166 | if (!isRedundantEquality(coeffs: rel.getEquality(idx: i))) |
2167 | return false; |
2168 | |
2169 | return true; |
2170 | } |
2171 | |
2172 | /// Returns the type of the inequality with coefficients `coeffs`. |
2173 | /// Possible types are: |
2174 | /// Redundant The inequality is satisfied by all points in the polytope |
2175 | /// Cut The inequality is satisfied by some points, but not by others |
2176 | /// Separate The inequality is not satisfied by any point |
2177 | /// |
2178 | /// Internally, this computes the minimum and the maximum the inequality with |
2179 | /// coefficients `coeffs` can take. If the minimum is >= 0, the inequality holds |
2180 | /// for all points in the polytope, so it is redundant. If the minimum is <= 0 |
2181 | /// and the maximum is >= 0, the points in between the minimum and the |
2182 | /// inequality do not satisfy it, the points in between the inequality and the |
2183 | /// maximum satisfy it. Hence, it is a cut inequality. If both are < 0, no |
2184 | /// points of the polytope satisfy the inequality, which means it is a separate |
2185 | /// inequality. |
2186 | Simplex::IneqType Simplex::findIneqType(ArrayRef<MPInt> coeffs) { |
2187 | MaybeOptimum<Fraction> minimum = computeOptimum(direction: Direction::Down, coeffs); |
2188 | if (minimum.isBounded() && *minimum >= Fraction(0, 1)) { |
2189 | return IneqType::Redundant; |
2190 | } |
2191 | MaybeOptimum<Fraction> maximum = computeOptimum(direction: Direction::Up, coeffs); |
2192 | if ((!minimum.isBounded() || *minimum <= Fraction(0, 1)) && |
2193 | (!maximum.isBounded() || *maximum >= Fraction(0, 1))) { |
2194 | return IneqType::Cut; |
2195 | } |
2196 | return IneqType::Separate; |
2197 | } |
2198 | |
2199 | /// Checks whether the type of the inequality with coefficients `coeffs` |
2200 | /// is Redundant. |
2201 | bool Simplex::isRedundantInequality(ArrayRef<MPInt> coeffs) { |
2202 | assert(!empty && |
2203 | "It is not meaningful to ask about redundancy in an empty set!" ); |
2204 | return findIneqType(coeffs) == IneqType::Redundant; |
2205 | } |
2206 | |
2207 | /// Check whether the equality given by `coeffs == 0` is redundant given |
2208 | /// the existing constraints. This is redundant when `coeffs` is already |
2209 | /// always zero under the existing constraints. `coeffs` is always zero |
2210 | /// when the minimum and maximum value that `coeffs` can take are both zero. |
2211 | bool Simplex::isRedundantEquality(ArrayRef<MPInt> coeffs) { |
2212 | assert(!empty && |
2213 | "It is not meaningful to ask about redundancy in an empty set!" ); |
2214 | MaybeOptimum<Fraction> minimum = computeOptimum(direction: Direction::Down, coeffs); |
2215 | MaybeOptimum<Fraction> maximum = computeOptimum(direction: Direction::Up, coeffs); |
2216 | assert((!minimum.isEmpty() && !maximum.isEmpty()) && |
2217 | "Optima should be non-empty for a non-empty set" ); |
2218 | return minimum.isBounded() && maximum.isBounded() && |
2219 | *maximum == Fraction(0, 1) && *minimum == Fraction(0, 1); |
2220 | } |
2221 | |