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/Matrix.h" 11 #include "mlir/Support/MathExtras.h" 12 #include "llvm/ADT/Optional.h" 13 14 using namespace mlir; 15 using namespace presburger; 16 17 using Direction = Simplex::Direction; 18 19 const int nullIndex = std::numeric_limits<int>::max(); 20 21 SimplexBase::SimplexBase(unsigned nVar, bool mustUseBigM) 22 : usingBigM(mustUseBigM), nRow(0), nCol(getNumFixedCols() + nVar), 23 nRedundant(0), tableau(0, nCol), empty(false) { 24 colUnknown.insert(colUnknown.begin(), getNumFixedCols(), nullIndex); 25 for (unsigned i = 0; i < nVar; ++i) { 26 var.emplace_back(Orientation::Column, /*restricted=*/false, 27 /*pos=*/getNumFixedCols() + i); 28 colUnknown.push_back(i); 29 } 30 } 31 32 const Simplex::Unknown &SimplexBase::unknownFromIndex(int index) const { 33 assert(index != nullIndex && "nullIndex passed to unknownFromIndex"); 34 return index >= 0 ? var[index] : con[~index]; 35 } 36 37 const Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) const { 38 assert(col < nCol && "Invalid column"); 39 return unknownFromIndex(colUnknown[col]); 40 } 41 42 const Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) const { 43 assert(row < nRow && "Invalid row"); 44 return unknownFromIndex(rowUnknown[row]); 45 } 46 47 Simplex::Unknown &SimplexBase::unknownFromIndex(int index) { 48 assert(index != nullIndex && "nullIndex passed to unknownFromIndex"); 49 return index >= 0 ? var[index] : con[~index]; 50 } 51 52 Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) { 53 assert(col < nCol && "Invalid column"); 54 return unknownFromIndex(colUnknown[col]); 55 } 56 57 Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) { 58 assert(row < nRow && "Invalid row"); 59 return unknownFromIndex(rowUnknown[row]); 60 } 61 62 unsigned SimplexBase::addZeroRow(bool makeRestricted) { 63 ++nRow; 64 // If the tableau is not big enough to accomodate the extra row, we extend it. 65 if (nRow >= tableau.getNumRows()) 66 tableau.resizeVertically(nRow); 67 rowUnknown.push_back(~con.size()); 68 con.emplace_back(Orientation::Row, makeRestricted, nRow - 1); 69 70 // Zero out the new row. 71 tableau.fillRow(nRow - 1, 0); 72 73 tableau(nRow - 1, 0) = 1; 74 return con.size() - 1; 75 } 76 77 /// Add a new row to the tableau corresponding to the given constant term and 78 /// list of coefficients. The coefficients are specified as a vector of 79 /// (variable index, coefficient) pairs. 80 unsigned SimplexBase::addRow(ArrayRef<int64_t> coeffs, bool makeRestricted) { 81 assert(coeffs.size() == var.size() + 1 && 82 "Incorrect number of coefficients!"); 83 84 addZeroRow(makeRestricted); 85 tableau(nRow - 1, 1) = coeffs.back(); 86 if (usingBigM) { 87 // When the lexicographic pivot rule is used, instead of the variables 88 // 89 // x, y, z ... 90 // 91 // we internally use the variables 92 // 93 // M, M + x, M + y, M + z, ... 94 // 95 // where M is the big M parameter. As such, when the user tries to add 96 // a row ax + by + cz + d, we express it in terms of our internal variables 97 // as -(a + b + c)M + a(M + x) + b(M + y) + c(M + z) + d. 98 int64_t bigMCoeff = 0; 99 for (unsigned i = 0; i < coeffs.size() - 1; ++i) 100 bigMCoeff -= coeffs[i]; 101 // The coefficient to the big M parameter is stored in column 2. 102 tableau(nRow - 1, 2) = bigMCoeff; 103 } 104 105 // Process each given variable coefficient. 106 for (unsigned i = 0; i < var.size(); ++i) { 107 unsigned pos = var[i].pos; 108 if (coeffs[i] == 0) 109 continue; 110 111 if (var[i].orientation == Orientation::Column) { 112 // If a variable is in column position at column col, then we just add the 113 // coefficient for that variable (scaled by the common row denominator) to 114 // the corresponding entry in the new row. 115 tableau(nRow - 1, pos) += coeffs[i] * tableau(nRow - 1, 0); 116 continue; 117 } 118 119 // If the variable is in row position, we need to add that row to the new 120 // row, scaled by the coefficient for the variable, accounting for the two 121 // rows potentially having different denominators. The new denominator is 122 // the lcm of the two. 123 int64_t lcm = mlir::lcm(tableau(nRow - 1, 0), tableau(pos, 0)); 124 int64_t nRowCoeff = lcm / tableau(nRow - 1, 0); 125 int64_t idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0)); 126 tableau(nRow - 1, 0) = lcm; 127 for (unsigned col = 1; col < nCol; ++col) 128 tableau(nRow - 1, col) = 129 nRowCoeff * tableau(nRow - 1, col) + idxRowCoeff * tableau(pos, col); 130 } 131 132 normalizeRow(nRow - 1); 133 // Push to undo log along with the index of the new constraint. 134 undoLog.push_back(UndoLogEntry::RemoveLastConstraint); 135 return con.size() - 1; 136 } 137 138 /// Normalize the row by removing factors that are common between the 139 /// denominator and all the numerator coefficients. 140 void SimplexBase::normalizeRow(unsigned row) { 141 int64_t gcd = 0; 142 for (unsigned col = 0; col < nCol; ++col) { 143 gcd = llvm::greatestCommonDivisor(gcd, std::abs(tableau(row, col))); 144 // If the gcd becomes 1 then the row is already normalized. 145 if (gcd == 1) 146 return; 147 } 148 149 // Note that the gcd can never become zero since the first element of the row, 150 // the denominator, is non-zero. 151 assert(gcd != 0); 152 for (unsigned col = 0; col < nCol; ++col) 153 tableau(row, col) /= gcd; 154 } 155 156 namespace { 157 bool signMatchesDirection(int64_t elem, Direction direction) { 158 assert(elem != 0 && "elem should not be 0"); 159 return direction == Direction::Up ? elem > 0 : elem < 0; 160 } 161 162 Direction flippedDirection(Direction direction) { 163 return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up; 164 } 165 } // namespace 166 167 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::findRationalLexMin() { 168 restoreRationalConsistency(); 169 return getRationalSample(); 170 } 171 172 LogicalResult LexSimplex::addCut(unsigned row) { 173 int64_t denom = tableau(row, 0); 174 addZeroRow(/*makeRestricted=*/true); 175 tableau(nRow - 1, 0) = denom; 176 tableau(nRow - 1, 1) = -mod(-tableau(row, 1), denom); 177 tableau(nRow - 1, 2) = 0; // M has all factors in it. 178 for (unsigned col = 3; col < nCol; ++col) 179 tableau(nRow - 1, col) = mod(tableau(row, col), denom); 180 return moveRowUnknownToColumn(nRow - 1); 181 } 182 183 Optional<unsigned> LexSimplex::maybeGetNonIntegeralVarRow() const { 184 for (const Unknown &u : var) { 185 if (u.orientation == Orientation::Column) 186 continue; 187 // If the sample value is of the form (a/d)M + b/d, we need b to be 188 // divisible by d. We assume M is very large and contains all possible 189 // factors and is divisible by everything. 190 unsigned row = u.pos; 191 if (tableau(row, 1) % tableau(row, 0) != 0) 192 return row; 193 } 194 return {}; 195 } 196 197 MaybeOptimum<SmallVector<int64_t, 8>> LexSimplex::findIntegerLexMin() { 198 while (!empty) { 199 restoreRationalConsistency(); 200 if (empty) 201 return OptimumKind::Empty; 202 203 if (Optional<unsigned> maybeRow = maybeGetNonIntegeralVarRow()) { 204 // Failure occurs when the polytope is integer empty. 205 if (failed(addCut(*maybeRow))) 206 return OptimumKind::Empty; 207 continue; 208 } 209 210 MaybeOptimum<SmallVector<Fraction, 8>> sample = getRationalSample(); 211 assert(!sample.isEmpty() && "If we reached here the sample should exist!"); 212 if (sample.isUnbounded()) 213 return OptimumKind::Unbounded; 214 return llvm::to_vector<8>(llvm::map_range( 215 *sample, [](const Fraction &f) { return f.getAsInteger(); })); 216 } 217 218 // Polytope is integer empty. 219 return OptimumKind::Empty; 220 } 221 222 bool LexSimplex::rowIsViolated(unsigned row) const { 223 if (tableau(row, 2) < 0) 224 return true; 225 if (tableau(row, 2) == 0 && tableau(row, 1) < 0) 226 return true; 227 return false; 228 } 229 230 Optional<unsigned> LexSimplex::maybeGetViolatedRow() const { 231 for (unsigned row = 0; row < nRow; ++row) 232 if (rowIsViolated(row)) 233 return row; 234 return {}; 235 } 236 237 // We simply look for violated rows and keep trying to move them to column 238 // orientation, which always succeeds unless the constraints have no solution 239 // in which case we just give up and return. 240 void LexSimplex::restoreRationalConsistency() { 241 while (Optional<unsigned> maybeViolatedRow = maybeGetViolatedRow()) { 242 LogicalResult status = moveRowUnknownToColumn(*maybeViolatedRow); 243 if (failed(status)) 244 return; 245 } 246 } 247 248 // Move the row unknown to column orientation while preserving lexicopositivity 249 // of the basis transform. 250 // 251 // We only consider pivots where the pivot element is positive. Suppose no such 252 // pivot exists, i.e., some violated row has no positive coefficient for any 253 // basis unknown. The row can be represented as (s + c_1*u_1 + ... + c_n*u_n)/d, 254 // where d is the denominator, s is the sample value and the c_i are the basis 255 // coefficients. Since any feasible assignment of the basis satisfies u_i >= 0 256 // for all i, and we have s < 0 as well as c_i < 0 for all i, any feasible 257 // assignment would violate this row and therefore the constraints have no 258 // solution. 259 // 260 // We can preserve lexicopositivity by picking the pivot column with positive 261 // pivot element that makes the lexicographically smallest change to the sample 262 // point. 263 // 264 // Proof. Let 265 // x = (x_1, ... x_n) be the variables, 266 // z = (z_1, ... z_m) be the constraints, 267 // y = (y_1, ... y_n) be the current basis, and 268 // define w = (x_1, ... x_n, z_1, ... z_m) = B*y + s. 269 // B is basically the simplex tableau of our implementation except that instead 270 // of only describing the transform to get back the non-basis unknowns, it 271 // defines the values of all the unknowns in terms of the basis unknowns. 272 // Similarly, s is the column for the sample value. 273 // 274 // Our goal is to show that each column in B, restricted to the first n 275 // rows, is lexicopositive after the pivot if it is so before. This is 276 // equivalent to saying the columns in the whole matrix are lexicopositive; 277 // there must be some non-zero element in every column in the first n rows since 278 // the n variables cannot be spanned without using all the n basis unknowns. 279 // 280 // Consider a pivot where z_i replaces y_j in the basis. Recall the pivot 281 // transform for the tableau derived for SimplexBase::pivot: 282 // 283 // pivot col other col pivot col other col 284 // pivot row a b -> pivot row 1/a -b/a 285 // other row c d other row c/a d - bc/a 286 // 287 // Similarly, a pivot results in B changing to B' and c to c'; the difference 288 // between the tableau and these matrices B and B' is that there is no special 289 // case for the pivot row, since it continues to represent the same unknown. The 290 // same formula applies for all rows: 291 // 292 // B'.col(j) = B.col(j) / B(i,j) 293 // B'.col(k) = B.col(k) - B(i,k) * B.col(j) / B(i,j) for k != j 294 // and similarly, s' = s - s_i * B.col(j) / B(i,j). 295 // 296 // Since the row is violated, we have s_i < 0, so the change in sample value 297 // when pivoting with column a is lexicographically smaller than that when 298 // pivoting with column b iff B.col(a) / B(i, a) is lexicographically smaller 299 // than B.col(b) / B(i, b). 300 // 301 // Since B(i, j) > 0, column j remains lexicopositive. 302 // 303 // For the other columns, suppose C.col(k) is not lexicopositive. 304 // This means that for some p, for all t < p, 305 // C(t,k) = 0 => B(t,k) = B(t,j) * B(i,k) / B(i,j) and 306 // C(t,k) < 0 => B(p,k) < B(t,j) * B(i,k) / B(i,j), 307 // which is in contradiction to the fact that B.col(j) / B(i,j) must be 308 // lexicographically smaller than B.col(k) / B(i,k), since it lexicographically 309 // minimizes the change in sample value. 310 LogicalResult LexSimplex::moveRowUnknownToColumn(unsigned row) { 311 Optional<unsigned> maybeColumn; 312 for (unsigned col = 3; col < nCol; ++col) { 313 if (tableau(row, col) <= 0) 314 continue; 315 maybeColumn = 316 !maybeColumn ? col : getLexMinPivotColumn(row, *maybeColumn, col); 317 } 318 319 if (!maybeColumn) { 320 markEmpty(); 321 return failure(); 322 } 323 324 pivot(row, *maybeColumn); 325 return success(); 326 } 327 328 unsigned LexSimplex::getLexMinPivotColumn(unsigned row, unsigned colA, 329 unsigned colB) const { 330 // A pivot causes the following change. (in the diagram the matrix elements 331 // are shown as rationals and there is no common denominator used) 332 // 333 // pivot col big M col const col 334 // pivot row a p b 335 // other row c q d 336 // | 337 // v 338 // 339 // pivot col big M col const col 340 // pivot row 1/a -p/a -b/a 341 // other row c/a q - pc/a d - bc/a 342 // 343 // Let the sample value of the pivot row be s = pM + b before the pivot. Since 344 // the pivot row represents a violated constraint we know that s < 0. 345 // 346 // If the variable is a non-pivot column, its sample value is zero before and 347 // after the pivot. 348 // 349 // If the variable is the pivot column, then its sample value goes from 0 to 350 // (-p/a)M + (-b/a), i.e. 0 to -(pM + b)/a. Thus the change in the sample 351 // value is -s/a. 352 // 353 // If the variable is the pivot row, it sampel value goes from s to 0, for a 354 // change of -s. 355 // 356 // If the variable is a non-pivot row, its sample value changes from 357 // qM + d to qM + d + (-pc/a)M + (-bc/a). Thus the change in sample value 358 // is -(pM + b)(c/a) = -sc/a. 359 // 360 // Thus the change in sample value is either 0, -s/a, -s, or -sc/a. Here -s is 361 // fixed for all calls to this function since the row and tableau are fixed. 362 // The callee just wants to compare the return values with the return value of 363 // other invocations of the same function. So the -s is common for all 364 // comparisons involved and can be ignored, since -s is strictly positive. 365 // 366 // Thus we take away this common factor and just return 0, 1/a, 1, or c/a as 367 // appropriate. This allows us to run the entire algorithm without ever having 368 // to fix a value of M. 369 auto getSampleChangeCoeffForVar = [this, row](unsigned col, 370 const Unknown &u) -> Fraction { 371 int64_t a = tableau(row, col); 372 if (u.orientation == Orientation::Column) { 373 // Pivot column case. 374 if (u.pos == col) 375 return {1, a}; 376 377 // Non-pivot column case. 378 return {0, 1}; 379 } 380 381 // Pivot row case. 382 if (u.pos == row) 383 return {1, 1}; 384 385 // Non-pivot row case. 386 int64_t c = tableau(u.pos, col); 387 return {c, a}; 388 }; 389 390 for (const Unknown &u : var) { 391 Fraction changeA = getSampleChangeCoeffForVar(colA, u); 392 Fraction changeB = getSampleChangeCoeffForVar(colB, u); 393 if (changeA < changeB) 394 return colA; 395 if (changeA > changeB) 396 return colB; 397 } 398 399 // If we reached here, both result in exactly the same changes, so it 400 // doesn't matter which we return. 401 return colA; 402 } 403 404 /// Find a pivot to change the sample value of the row in the specified 405 /// direction. The returned pivot row will involve `row` if and only if the 406 /// unknown is unbounded in the specified direction. 407 /// 408 /// To increase (resp. decrease) the value of a row, we need to find a live 409 /// column with a non-zero coefficient. If the coefficient is positive, we need 410 /// to increase (decrease) the value of the column, and if the coefficient is 411 /// negative, we need to decrease (increase) the value of the column. Also, 412 /// we cannot decrease the sample value of restricted columns. 413 /// 414 /// If multiple columns are valid, we break ties by considering a lexicographic 415 /// ordering where we prefer unknowns with lower index. 416 Optional<SimplexBase::Pivot> Simplex::findPivot(int row, 417 Direction direction) const { 418 Optional<unsigned> col; 419 for (unsigned j = 2; j < nCol; ++j) { 420 int64_t elem = tableau(row, j); 421 if (elem == 0) 422 continue; 423 424 if (unknownFromColumn(j).restricted && 425 !signMatchesDirection(elem, direction)) 426 continue; 427 if (!col || colUnknown[j] < colUnknown[*col]) 428 col = j; 429 } 430 431 if (!col) 432 return {}; 433 434 Direction newDirection = 435 tableau(row, *col) < 0 ? flippedDirection(direction) : direction; 436 Optional<unsigned> maybePivotRow = findPivotRow(row, newDirection, *col); 437 return Pivot{maybePivotRow.getValueOr(row), *col}; 438 } 439 440 /// Swap the associated unknowns for the row and the column. 441 /// 442 /// First we swap the index associated with the row and column. Then we update 443 /// the unknowns to reflect their new position and orientation. 444 void SimplexBase::swapRowWithCol(unsigned row, unsigned col) { 445 std::swap(rowUnknown[row], colUnknown[col]); 446 Unknown &uCol = unknownFromColumn(col); 447 Unknown &uRow = unknownFromRow(row); 448 uCol.orientation = Orientation::Column; 449 uRow.orientation = Orientation::Row; 450 uCol.pos = col; 451 uRow.pos = row; 452 } 453 454 void SimplexBase::pivot(Pivot pair) { pivot(pair.row, pair.column); } 455 456 /// Pivot pivotRow and pivotCol. 457 /// 458 /// Let R be the pivot row unknown and let C be the pivot col unknown. 459 /// Since initially R = a*C + sum b_i * X_i 460 /// (where the sum is over the other column's unknowns, x_i) 461 /// C = (R - (sum b_i * X_i))/a 462 /// 463 /// Let u be some other row unknown. 464 /// u = c*C + sum d_i * X_i 465 /// So u = c*(R - sum b_i * X_i)/a + sum d_i * X_i 466 /// 467 /// This results in the following transform: 468 /// pivot col other col pivot col other col 469 /// pivot row a b -> pivot row 1/a -b/a 470 /// other row c d other row c/a d - bc/a 471 /// 472 /// Taking into account the common denominators p and q: 473 /// 474 /// pivot col other col pivot col other col 475 /// pivot row a/p b/p -> pivot row p/a -b/a 476 /// other row c/q d/q other row cp/aq (da - bc)/aq 477 /// 478 /// The pivot row transform is accomplished be swapping a with the pivot row's 479 /// common denominator and negating the pivot row except for the pivot column 480 /// element. 481 void SimplexBase::pivot(unsigned pivotRow, unsigned pivotCol) { 482 assert(pivotCol >= getNumFixedCols() && "Refusing to pivot invalid column"); 483 484 swapRowWithCol(pivotRow, pivotCol); 485 std::swap(tableau(pivotRow, 0), tableau(pivotRow, pivotCol)); 486 // We need to negate the whole pivot row except for the pivot column. 487 if (tableau(pivotRow, 0) < 0) { 488 // If the denominator is negative, we negate the row by simply negating the 489 // denominator. 490 tableau(pivotRow, 0) = -tableau(pivotRow, 0); 491 tableau(pivotRow, pivotCol) = -tableau(pivotRow, pivotCol); 492 } else { 493 for (unsigned col = 1; col < nCol; ++col) { 494 if (col == pivotCol) 495 continue; 496 tableau(pivotRow, col) = -tableau(pivotRow, col); 497 } 498 } 499 normalizeRow(pivotRow); 500 501 for (unsigned row = 0; row < nRow; ++row) { 502 if (row == pivotRow) 503 continue; 504 if (tableau(row, pivotCol) == 0) // Nothing to do. 505 continue; 506 tableau(row, 0) *= tableau(pivotRow, 0); 507 for (unsigned j = 1; j < nCol; ++j) { 508 if (j == pivotCol) 509 continue; 510 // Add rather than subtract because the pivot row has been negated. 511 tableau(row, j) = tableau(row, j) * tableau(pivotRow, 0) + 512 tableau(row, pivotCol) * tableau(pivotRow, j); 513 } 514 tableau(row, pivotCol) *= tableau(pivotRow, pivotCol); 515 normalizeRow(row); 516 } 517 } 518 519 /// Perform pivots until the unknown has a non-negative sample value or until 520 /// no more upward pivots can be performed. Return success if we were able to 521 /// bring the row to a non-negative sample value, and failure otherwise. 522 LogicalResult Simplex::restoreRow(Unknown &u) { 523 assert(u.orientation == Orientation::Row && 524 "unknown should be in row position"); 525 526 while (tableau(u.pos, 1) < 0) { 527 Optional<Pivot> maybePivot = findPivot(u.pos, Direction::Up); 528 if (!maybePivot) 529 break; 530 531 pivot(*maybePivot); 532 if (u.orientation == Orientation::Column) 533 return success(); // the unknown is unbounded above. 534 } 535 return success(tableau(u.pos, 1) >= 0); 536 } 537 538 /// Find a row that can be used to pivot the column in the specified direction. 539 /// This returns an empty optional if and only if the column is unbounded in the 540 /// specified direction (ignoring skipRow, if skipRow is set). 541 /// 542 /// If skipRow is set, this row is not considered, and (if it is restricted) its 543 /// restriction may be violated by the returned pivot. Usually, skipRow is set 544 /// because we don't want to move it to column position unless it is unbounded, 545 /// and we are either trying to increase the value of skipRow or explicitly 546 /// trying to make skipRow negative, so we are not concerned about this. 547 /// 548 /// If the direction is up (resp. down) and a restricted row has a negative 549 /// (positive) coefficient for the column, then this row imposes a bound on how 550 /// much the sample value of the column can change. Such a row with constant 551 /// term c and coefficient f for the column imposes a bound of c/|f| on the 552 /// change in sample value (in the specified direction). (note that c is 553 /// non-negative here since the row is restricted and the tableau is consistent) 554 /// 555 /// We iterate through the rows and pick the row which imposes the most 556 /// stringent bound, since pivoting with a row changes the row's sample value to 557 /// 0 and hence saturates the bound it imposes. We break ties between rows that 558 /// impose the same bound by considering a lexicographic ordering where we 559 /// prefer unknowns with lower index value. 560 Optional<unsigned> Simplex::findPivotRow(Optional<unsigned> skipRow, 561 Direction direction, 562 unsigned col) const { 563 Optional<unsigned> retRow; 564 // Initialize these to zero in order to silence a warning about retElem and 565 // retConst being used uninitialized in the initialization of `diff` below. In 566 // reality, these are always initialized when that line is reached since these 567 // are set whenever retRow is set. 568 int64_t retElem = 0, retConst = 0; 569 for (unsigned row = nRedundant; row < nRow; ++row) { 570 if (skipRow && row == *skipRow) 571 continue; 572 int64_t elem = tableau(row, col); 573 if (elem == 0) 574 continue; 575 if (!unknownFromRow(row).restricted) 576 continue; 577 if (signMatchesDirection(elem, direction)) 578 continue; 579 int64_t constTerm = tableau(row, 1); 580 581 if (!retRow) { 582 retRow = row; 583 retElem = elem; 584 retConst = constTerm; 585 continue; 586 } 587 588 int64_t diff = retConst * elem - constTerm * retElem; 589 if ((diff == 0 && rowUnknown[row] < rowUnknown[*retRow]) || 590 (diff != 0 && !signMatchesDirection(diff, direction))) { 591 retRow = row; 592 retElem = elem; 593 retConst = constTerm; 594 } 595 } 596 return retRow; 597 } 598 599 bool SimplexBase::isEmpty() const { return empty; } 600 601 void SimplexBase::swapRows(unsigned i, unsigned j) { 602 if (i == j) 603 return; 604 tableau.swapRows(i, j); 605 std::swap(rowUnknown[i], rowUnknown[j]); 606 unknownFromRow(i).pos = i; 607 unknownFromRow(j).pos = j; 608 } 609 610 void SimplexBase::swapColumns(unsigned i, unsigned j) { 611 assert(i < nCol && j < nCol && "Invalid columns provided!"); 612 if (i == j) 613 return; 614 tableau.swapColumns(i, j); 615 std::swap(colUnknown[i], colUnknown[j]); 616 unknownFromColumn(i).pos = i; 617 unknownFromColumn(j).pos = j; 618 } 619 620 /// Mark this tableau empty and push an entry to the undo stack. 621 void SimplexBase::markEmpty() { 622 // If the set is already empty, then we shouldn't add another UnmarkEmpty log 623 // entry, since in that case the Simplex will be erroneously marked as 624 // non-empty when rolling back past this point. 625 if (empty) 626 return; 627 undoLog.push_back(UndoLogEntry::UnmarkEmpty); 628 empty = true; 629 } 630 631 /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n 632 /// is the current number of variables, then the corresponding inequality is 633 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. 634 /// 635 /// We add the inequality and mark it as restricted. We then try to make its 636 /// sample value non-negative. If this is not possible, the tableau has become 637 /// empty and we mark it as such. 638 void Simplex::addInequality(ArrayRef<int64_t> coeffs) { 639 unsigned conIndex = addRow(coeffs, /*makeRestricted=*/true); 640 LogicalResult result = restoreRow(con[conIndex]); 641 if (failed(result)) 642 markEmpty(); 643 } 644 645 /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n 646 /// is the current number of variables, then the corresponding equality is 647 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0. 648 /// 649 /// We simply add two opposing inequalities, which force the expression to 650 /// be zero. 651 void SimplexBase::addEquality(ArrayRef<int64_t> coeffs) { 652 addInequality(coeffs); 653 SmallVector<int64_t, 8> negatedCoeffs; 654 for (int64_t coeff : coeffs) 655 negatedCoeffs.emplace_back(-coeff); 656 addInequality(negatedCoeffs); 657 } 658 659 unsigned SimplexBase::getNumVariables() const { return var.size(); } 660 unsigned SimplexBase::getNumConstraints() const { return con.size(); } 661 662 /// Return a snapshot of the current state. This is just the current size of the 663 /// undo log. 664 unsigned SimplexBase::getSnapshot() const { return undoLog.size(); } 665 666 unsigned SimplexBase::getSnapshotBasis() { 667 SmallVector<int, 8> basis; 668 for (int index : colUnknown) { 669 if (index != nullIndex) 670 basis.push_back(index); 671 } 672 savedBases.push_back(std::move(basis)); 673 674 undoLog.emplace_back(UndoLogEntry::RestoreBasis); 675 return undoLog.size() - 1; 676 } 677 678 void SimplexBase::removeLastConstraintRowOrientation() { 679 assert(con.back().orientation == Orientation::Row); 680 681 // Move this unknown to the last row and remove the last row from the 682 // tableau. 683 swapRows(con.back().pos, nRow - 1); 684 // It is not strictly necessary to shrink the tableau, but for now we 685 // maintain the invariant that the tableau has exactly nRow rows. 686 tableau.resizeVertically(nRow - 1); 687 nRow--; 688 rowUnknown.pop_back(); 689 con.pop_back(); 690 } 691 692 // This doesn't find a pivot row only if the column has zero 693 // coefficients for every row. 694 // 695 // If the unknown is a constraint, this can't happen, since it was added 696 // initially as a row. Such a row could never have been pivoted to a column. So 697 // a pivot row will always be found if we have a constraint. 698 // 699 // If we have a variable, then the column has zero coefficients for every row 700 // iff no constraints have been added with a non-zero coefficient for this row. 701 Optional<unsigned> SimplexBase::findAnyPivotRow(unsigned col) { 702 for (unsigned row = nRedundant; row < nRow; ++row) 703 if (tableau(row, col) != 0) 704 return row; 705 return {}; 706 } 707 708 // It's not valid to remove the constraint by deleting the column since this 709 // would result in an invalid basis. 710 void Simplex::undoLastConstraint() { 711 if (con.back().orientation == Orientation::Column) { 712 // We try to find any pivot row for this column that preserves tableau 713 // consistency (except possibly the column itself, which is going to be 714 // deallocated anyway). 715 // 716 // If no pivot row is found in either direction, then the unknown is 717 // unbounded in both directions and we are free to perform any pivot at 718 // all. To do this, we just need to find any row with a non-zero 719 // coefficient for the column. findAnyPivotRow will always be able to 720 // find such a row for a constraint. 721 unsigned column = con.back().pos; 722 if (Optional<unsigned> maybeRow = findPivotRow({}, Direction::Up, column)) { 723 pivot(*maybeRow, column); 724 } else if (Optional<unsigned> maybeRow = 725 findPivotRow({}, Direction::Down, column)) { 726 pivot(*maybeRow, column); 727 } else { 728 Optional<unsigned> row = findAnyPivotRow(column); 729 assert(row.hasValue() && "Pivot should always exist for a constraint!"); 730 pivot(*row, column); 731 } 732 } 733 removeLastConstraintRowOrientation(); 734 } 735 736 // It's not valid to remove the constraint by deleting the column since this 737 // would result in an invalid basis. 738 void LexSimplex::undoLastConstraint() { 739 if (con.back().orientation == Orientation::Column) { 740 // When removing the last constraint during a rollback, we just need to find 741 // any pivot at all, i.e., any row with non-zero coefficient for the 742 // column, because when rolling back a lexicographic simplex, we always 743 // end by restoring the exact basis that was present at the time of the 744 // snapshot, so what pivots we perform while undoing doesn't matter as 745 // long as we get the unknown to row orientation and remove it. 746 unsigned column = con.back().pos; 747 Optional<unsigned> row = findAnyPivotRow(column); 748 assert(row.hasValue() && "Pivot should always exist for a constraint!"); 749 pivot(*row, column); 750 } 751 removeLastConstraintRowOrientation(); 752 } 753 754 void SimplexBase::undo(UndoLogEntry entry) { 755 if (entry == UndoLogEntry::RemoveLastConstraint) { 756 // Simplex and LexSimplex handle this differently, so we call out to a 757 // virtual function to handle this. 758 undoLastConstraint(); 759 } else if (entry == UndoLogEntry::RemoveLastVariable) { 760 // Whenever we are rolling back the addition of a variable, it is guaranteed 761 // that the variable will be in column position. 762 // 763 // We can see this as follows: any constraint that depends on this variable 764 // was added after this variable was added, so the addition of such 765 // constraints should already have been rolled back by the time we get to 766 // rolling back the addition of the variable. Therefore, no constraint 767 // currently has a component along the variable, so the variable itself must 768 // be part of the basis. 769 assert(var.back().orientation == Orientation::Column && 770 "Variable to be removed must be in column orientation!"); 771 772 // Move this variable to the last column and remove the column from the 773 // tableau. 774 swapColumns(var.back().pos, nCol - 1); 775 tableau.resizeHorizontally(nCol - 1); 776 var.pop_back(); 777 colUnknown.pop_back(); 778 nCol--; 779 } else if (entry == UndoLogEntry::UnmarkEmpty) { 780 empty = false; 781 } else if (entry == UndoLogEntry::UnmarkLastRedundant) { 782 nRedundant--; 783 } else if (entry == UndoLogEntry::RestoreBasis) { 784 assert(!savedBases.empty() && "No bases saved!"); 785 786 SmallVector<int, 8> basis = std::move(savedBases.back()); 787 savedBases.pop_back(); 788 789 for (int index : basis) { 790 Unknown &u = unknownFromIndex(index); 791 if (u.orientation == Orientation::Column) 792 continue; 793 for (unsigned col = getNumFixedCols(); col < nCol; col++) { 794 assert(colUnknown[col] != nullIndex && 795 "Column should not be a fixed column!"); 796 if (std::find(basis.begin(), basis.end(), colUnknown[col]) != 797 basis.end()) 798 continue; 799 if (tableau(u.pos, col) == 0) 800 continue; 801 pivot(u.pos, col); 802 break; 803 } 804 805 assert(u.orientation == Orientation::Column && "No pivot found!"); 806 } 807 } 808 } 809 810 /// Rollback to the specified snapshot. 811 /// 812 /// We undo all the log entries until the log size when the snapshot was taken 813 /// is reached. 814 void SimplexBase::rollback(unsigned snapshot) { 815 while (undoLog.size() > snapshot) { 816 undo(undoLog.back()); 817 undoLog.pop_back(); 818 } 819 } 820 821 void SimplexBase::appendVariable(unsigned count) { 822 if (count == 0) 823 return; 824 var.reserve(var.size() + count); 825 colUnknown.reserve(colUnknown.size() + count); 826 for (unsigned i = 0; i < count; ++i) { 827 nCol++; 828 var.emplace_back(Orientation::Column, /*restricted=*/false, 829 /*pos=*/nCol - 1); 830 colUnknown.push_back(var.size() - 1); 831 } 832 tableau.resizeHorizontally(nCol); 833 undoLog.insert(undoLog.end(), count, UndoLogEntry::RemoveLastVariable); 834 } 835 836 /// Add all the constraints from the given IntegerPolyhedron. 837 void SimplexBase::intersectIntegerPolyhedron(const IntegerPolyhedron &poly) { 838 assert(poly.getNumIds() == getNumVariables() && 839 "IntegerPolyhedron must have same dimensionality as simplex"); 840 for (unsigned i = 0, e = poly.getNumInequalities(); i < e; ++i) 841 addInequality(poly.getInequality(i)); 842 for (unsigned i = 0, e = poly.getNumEqualities(); i < e; ++i) 843 addEquality(poly.getEquality(i)); 844 } 845 846 MaybeOptimum<Fraction> Simplex::computeRowOptimum(Direction direction, 847 unsigned row) { 848 // Keep trying to find a pivot for the row in the specified direction. 849 while (Optional<Pivot> maybePivot = findPivot(row, direction)) { 850 // If findPivot returns a pivot involving the row itself, then the optimum 851 // is unbounded, so we return None. 852 if (maybePivot->row == row) 853 return OptimumKind::Unbounded; 854 pivot(*maybePivot); 855 } 856 857 // The row has reached its optimal sample value, which we return. 858 // The sample value is the entry in the constant column divided by the common 859 // denominator for this row. 860 return Fraction(tableau(row, 1), tableau(row, 0)); 861 } 862 863 /// Compute the optimum of the specified expression in the specified direction, 864 /// or None if it is unbounded. 865 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 866 ArrayRef<int64_t> coeffs) { 867 if (empty) 868 return OptimumKind::Empty; 869 unsigned snapshot = getSnapshot(); 870 unsigned conIndex = addRow(coeffs); 871 unsigned row = con[conIndex].pos; 872 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 873 rollback(snapshot); 874 return optimum; 875 } 876 877 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 878 Unknown &u) { 879 if (empty) 880 return OptimumKind::Empty; 881 if (u.orientation == Orientation::Column) { 882 unsigned column = u.pos; 883 Optional<unsigned> pivotRow = findPivotRow({}, direction, column); 884 // If no pivot is returned, the constraint is unbounded in the specified 885 // direction. 886 if (!pivotRow) 887 return OptimumKind::Unbounded; 888 pivot(*pivotRow, column); 889 } 890 891 unsigned row = u.pos; 892 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 893 if (u.restricted && direction == Direction::Down && 894 (optimum.isUnbounded() || *optimum < Fraction(0, 1))) { 895 if (failed(restoreRow(u))) 896 llvm_unreachable("Could not restore row!"); 897 } 898 return optimum; 899 } 900 901 bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) { 902 assert(!empty && "It is not meaningful to ask whether a direction is bounded " 903 "in an empty set."); 904 // The constraint's perpendicular is already bounded below, since it is a 905 // constraint. If it is also bounded above, we can return true. 906 return computeOptimum(Direction::Up, con[constraintIndex]).isBounded(); 907 } 908 909 /// Redundant constraints are those that are in row orientation and lie in 910 /// rows 0 to nRedundant - 1. 911 bool Simplex::isMarkedRedundant(unsigned constraintIndex) const { 912 const Unknown &u = con[constraintIndex]; 913 return u.orientation == Orientation::Row && u.pos < nRedundant; 914 } 915 916 /// Mark the specified row redundant. 917 /// 918 /// This is done by moving the unknown to the end of the block of redundant 919 /// rows (namely, to row nRedundant) and incrementing nRedundant to 920 /// accomodate the new redundant row. 921 void Simplex::markRowRedundant(Unknown &u) { 922 assert(u.orientation == Orientation::Row && 923 "Unknown should be in row position!"); 924 assert(u.pos >= nRedundant && "Unknown is already marked redundant!"); 925 swapRows(u.pos, nRedundant); 926 ++nRedundant; 927 undoLog.emplace_back(UndoLogEntry::UnmarkLastRedundant); 928 } 929 930 /// Find a subset of constraints that is redundant and mark them redundant. 931 void Simplex::detectRedundant() { 932 // It is not meaningful to talk about redundancy for empty sets. 933 if (empty) 934 return; 935 936 // Iterate through the constraints and check for each one if it can attain 937 // negative sample values. If it can, it's not redundant. Otherwise, it is. 938 // We mark redundant constraints redundant. 939 // 940 // Constraints that get marked redundant in one iteration are not respected 941 // when checking constraints in later iterations. This prevents, for example, 942 // two identical constraints both being marked redundant since each is 943 // redundant given the other one. In this example, only the first of the 944 // constraints that is processed will get marked redundant, as it should be. 945 for (Unknown &u : con) { 946 if (u.orientation == Orientation::Column) { 947 unsigned column = u.pos; 948 Optional<unsigned> pivotRow = findPivotRow({}, Direction::Down, column); 949 // If no downward pivot is returned, the constraint is unbounded below 950 // and hence not redundant. 951 if (!pivotRow) 952 continue; 953 pivot(*pivotRow, column); 954 } 955 956 unsigned row = u.pos; 957 MaybeOptimum<Fraction> minimum = computeRowOptimum(Direction::Down, row); 958 if (minimum.isUnbounded() || *minimum < Fraction(0, 1)) { 959 // Constraint is unbounded below or can attain negative sample values and 960 // hence is not redundant. 961 if (failed(restoreRow(u))) 962 llvm_unreachable("Could not restore non-redundant row!"); 963 continue; 964 } 965 966 markRowRedundant(u); 967 } 968 } 969 970 bool Simplex::isUnbounded() { 971 if (empty) 972 return false; 973 974 SmallVector<int64_t, 8> dir(var.size() + 1); 975 for (unsigned i = 0; i < var.size(); ++i) { 976 dir[i] = 1; 977 978 if (computeOptimum(Direction::Up, dir).isUnbounded()) 979 return true; 980 981 if (computeOptimum(Direction::Down, dir).isUnbounded()) 982 return true; 983 984 dir[i] = 0; 985 } 986 return false; 987 } 988 989 /// Make a tableau to represent a pair of points in the original tableau. 990 /// 991 /// The product constraints and variables are stored as: first A's, then B's. 992 /// 993 /// The product tableau has row layout: 994 /// A's redundant rows, B's redundant rows, A's other rows, B's other rows. 995 /// 996 /// It has column layout: 997 /// denominator, constant, A's columns, B's columns. 998 Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) { 999 unsigned numVar = a.getNumVariables() + b.getNumVariables(); 1000 unsigned numCon = a.getNumConstraints() + b.getNumConstraints(); 1001 Simplex result(numVar); 1002 1003 result.tableau.resizeVertically(numCon); 1004 result.empty = a.empty || b.empty; 1005 1006 auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) { 1007 SmallVector<Unknown, 8> result; 1008 result.reserve(v.size() + w.size()); 1009 result.insert(result.end(), v.begin(), v.end()); 1010 result.insert(result.end(), w.begin(), w.end()); 1011 return result; 1012 }; 1013 result.con = concat(a.con, b.con); 1014 result.var = concat(a.var, b.var); 1015 1016 auto indexFromBIndex = [&](int index) { 1017 return index >= 0 ? a.getNumVariables() + index 1018 : ~(a.getNumConstraints() + ~index); 1019 }; 1020 1021 result.colUnknown.assign(2, nullIndex); 1022 for (unsigned i = 2; i < a.nCol; ++i) { 1023 result.colUnknown.push_back(a.colUnknown[i]); 1024 result.unknownFromIndex(result.colUnknown.back()).pos = 1025 result.colUnknown.size() - 1; 1026 } 1027 for (unsigned i = 2; i < b.nCol; ++i) { 1028 result.colUnknown.push_back(indexFromBIndex(b.colUnknown[i])); 1029 result.unknownFromIndex(result.colUnknown.back()).pos = 1030 result.colUnknown.size() - 1; 1031 } 1032 1033 auto appendRowFromA = [&](unsigned row) { 1034 for (unsigned col = 0; col < a.nCol; ++col) 1035 result.tableau(result.nRow, col) = a.tableau(row, col); 1036 result.rowUnknown.push_back(a.rowUnknown[row]); 1037 result.unknownFromIndex(result.rowUnknown.back()).pos = 1038 result.rowUnknown.size() - 1; 1039 result.nRow++; 1040 }; 1041 1042 // Also fixes the corresponding entry in rowUnknown and var/con (as the case 1043 // may be). 1044 auto appendRowFromB = [&](unsigned row) { 1045 result.tableau(result.nRow, 0) = b.tableau(row, 0); 1046 result.tableau(result.nRow, 1) = b.tableau(row, 1); 1047 1048 unsigned offset = a.nCol - 2; 1049 for (unsigned col = 2; col < b.nCol; ++col) 1050 result.tableau(result.nRow, offset + col) = b.tableau(row, col); 1051 result.rowUnknown.push_back(indexFromBIndex(b.rowUnknown[row])); 1052 result.unknownFromIndex(result.rowUnknown.back()).pos = 1053 result.rowUnknown.size() - 1; 1054 result.nRow++; 1055 }; 1056 1057 result.nRedundant = a.nRedundant + b.nRedundant; 1058 for (unsigned row = 0; row < a.nRedundant; ++row) 1059 appendRowFromA(row); 1060 for (unsigned row = 0; row < b.nRedundant; ++row) 1061 appendRowFromB(row); 1062 for (unsigned row = a.nRedundant; row < a.nRow; ++row) 1063 appendRowFromA(row); 1064 for (unsigned row = b.nRedundant; row < b.nRow; ++row) 1065 appendRowFromB(row); 1066 1067 return result; 1068 } 1069 1070 Optional<SmallVector<Fraction, 8>> Simplex::getRationalSample() const { 1071 if (empty) 1072 return {}; 1073 1074 SmallVector<Fraction, 8> sample; 1075 sample.reserve(var.size()); 1076 // Push the sample value for each variable into the vector. 1077 for (const Unknown &u : var) { 1078 if (u.orientation == Orientation::Column) { 1079 // If the variable is in column position, its sample value is zero. 1080 sample.emplace_back(0, 1); 1081 } else { 1082 // If the variable is in row position, its sample value is the 1083 // entry in the constant column divided by the denominator. 1084 int64_t denom = tableau(u.pos, 0); 1085 sample.emplace_back(tableau(u.pos, 1), denom); 1086 } 1087 } 1088 return sample; 1089 } 1090 1091 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::getRationalSample() const { 1092 if (empty) 1093 return OptimumKind::Empty; 1094 1095 SmallVector<Fraction, 8> sample; 1096 sample.reserve(var.size()); 1097 // Push the sample value for each variable into the vector. 1098 for (const Unknown &u : var) { 1099 // When the big M parameter is being used, each variable x is represented 1100 // as M + x, so its sample value is finite if and only if it is of the 1101 // form 1*M + c. If the coefficient of M is not one then the sample value 1102 // is infinite, and we return an empty optional. 1103 1104 if (u.orientation == Orientation::Column) { 1105 // If the variable is in column position, the sample value of M + x is 1106 // zero, so x = -M which is unbounded. 1107 return OptimumKind::Unbounded; 1108 } 1109 1110 // If the variable is in row position, its sample value is the 1111 // entry in the constant column divided by the denominator. 1112 int64_t denom = tableau(u.pos, 0); 1113 if (usingBigM) 1114 if (tableau(u.pos, 2) != denom) 1115 return OptimumKind::Unbounded; 1116 sample.emplace_back(tableau(u.pos, 1), denom); 1117 } 1118 return sample; 1119 } 1120 1121 Optional<SmallVector<int64_t, 8>> Simplex::getSamplePointIfIntegral() const { 1122 // If the tableau is empty, no sample point exists. 1123 if (empty) 1124 return {}; 1125 1126 // The value will always exist since the Simplex is non-empty. 1127 SmallVector<Fraction, 8> rationalSample = *getRationalSample(); 1128 SmallVector<int64_t, 8> integerSample; 1129 integerSample.reserve(var.size()); 1130 for (const Fraction &coord : rationalSample) { 1131 // If the sample is non-integral, return None. 1132 if (coord.num % coord.den != 0) 1133 return {}; 1134 integerSample.push_back(coord.num / coord.den); 1135 } 1136 return integerSample; 1137 } 1138 1139 /// Given a simplex for a polytope, construct a new simplex whose variables are 1140 /// identified with a pair of points (x, y) in the original polytope. Supports 1141 /// some operations needed for generalized basis reduction. In what follows, 1142 /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the 1143 /// dimension of the original polytope. 1144 /// 1145 /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It 1146 /// also supports rolling back this addition, by maintaining a snapshot stack 1147 /// that contains a snapshot of the Simplex's state for each equality, just 1148 /// before that equality was added. 1149 class presburger::GBRSimplex { 1150 using Orientation = Simplex::Orientation; 1151 1152 public: 1153 GBRSimplex(const Simplex &originalSimplex) 1154 : simplex(Simplex::makeProduct(originalSimplex, originalSimplex)), 1155 simplexConstraintOffset(simplex.getNumConstraints()) {} 1156 1157 /// Add an equality dotProduct(dir, x - y) == 0. 1158 /// First pushes a snapshot for the current simplex state to the stack so 1159 /// that this can be rolled back later. 1160 void addEqualityForDirection(ArrayRef<int64_t> dir) { 1161 assert( 1162 std::any_of(dir.begin(), dir.end(), [](int64_t x) { return x != 0; }) && 1163 "Direction passed is the zero vector!"); 1164 snapshotStack.push_back(simplex.getSnapshot()); 1165 simplex.addEquality(getCoeffsForDirection(dir)); 1166 } 1167 /// Compute max(dotProduct(dir, x - y)). 1168 Fraction computeWidth(ArrayRef<int64_t> dir) { 1169 MaybeOptimum<Fraction> maybeWidth = 1170 simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir)); 1171 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1172 return *maybeWidth; 1173 } 1174 1175 /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only 1176 /// the direction equalities to `dual`. 1177 Fraction computeWidthAndDuals(ArrayRef<int64_t> dir, 1178 SmallVectorImpl<int64_t> &dual, 1179 int64_t &dualDenom) { 1180 // We can't just call into computeWidth or computeOptimum since we need to 1181 // access the state of the tableau after computing the optimum, and these 1182 // functions rollback the insertion of the objective function into the 1183 // tableau before returning. We instead add a row for the objective function 1184 // ourselves, call into computeOptimum, compute the duals from the tableau 1185 // state, and finally rollback the addition of the row before returning. 1186 unsigned snap = simplex.getSnapshot(); 1187 unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir)); 1188 unsigned row = simplex.con[conIndex].pos; 1189 MaybeOptimum<Fraction> maybeWidth = 1190 simplex.computeRowOptimum(Simplex::Direction::Up, row); 1191 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1192 dualDenom = simplex.tableau(row, 0); 1193 dual.clear(); 1194 1195 // The increment is i += 2 because equalities are added as two inequalities, 1196 // one positive and one negative. Each iteration processes one equality. 1197 for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) { 1198 // The dual variable for an inequality in column orientation is the 1199 // negative of its coefficient at the objective row. If the inequality is 1200 // in row orientation, the corresponding dual variable is zero. 1201 // 1202 // We want the dual for the original equality, which corresponds to two 1203 // inequalities: a positive inequality, which has the same coefficients as 1204 // the equality, and a negative equality, which has negated coefficients. 1205 // 1206 // Note that at most one of these inequalities can be in column 1207 // orientation because the column unknowns should form a basis and hence 1208 // must be linearly independent. If the positive inequality is in column 1209 // position, its dual is the dual corresponding to the equality. If the 1210 // negative inequality is in column position, the negation of its dual is 1211 // the dual corresponding to the equality. If neither is in column 1212 // position, then that means that this equality is redundant, and its dual 1213 // is zero. 1214 // 1215 // Note that it is NOT valid to perform pivots during the computation of 1216 // the duals. This entire dual computation must be performed on the same 1217 // tableau configuration. 1218 assert(!(simplex.con[i].orientation == Orientation::Column && 1219 simplex.con[i + 1].orientation == Orientation::Column) && 1220 "Both inequalities for the equality cannot be in column " 1221 "orientation!"); 1222 if (simplex.con[i].orientation == Orientation::Column) 1223 dual.push_back(-simplex.tableau(row, simplex.con[i].pos)); 1224 else if (simplex.con[i + 1].orientation == Orientation::Column) 1225 dual.push_back(simplex.tableau(row, simplex.con[i + 1].pos)); 1226 else 1227 dual.push_back(0); 1228 } 1229 simplex.rollback(snap); 1230 return *maybeWidth; 1231 } 1232 1233 /// Remove the last equality that was added through addEqualityForDirection. 1234 /// 1235 /// We do this by rolling back to the snapshot at the top of the stack, which 1236 /// should be a snapshot taken just before the last equality was added. 1237 void removeLastEquality() { 1238 assert(!snapshotStack.empty() && "Snapshot stack is empty!"); 1239 simplex.rollback(snapshotStack.back()); 1240 snapshotStack.pop_back(); 1241 } 1242 1243 private: 1244 /// Returns coefficients of the expression 'dot_product(dir, x - y)', 1245 /// i.e., dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n 1246 /// - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n, 1247 /// where n is the dimension of the original polytope. 1248 SmallVector<int64_t, 8> getCoeffsForDirection(ArrayRef<int64_t> dir) { 1249 assert(2 * dir.size() == simplex.getNumVariables() && 1250 "Direction vector has wrong dimensionality"); 1251 SmallVector<int64_t, 8> coeffs(dir.begin(), dir.end()); 1252 coeffs.reserve(2 * dir.size()); 1253 for (int64_t coeff : dir) 1254 coeffs.push_back(-coeff); 1255 coeffs.push_back(0); // constant term 1256 return coeffs; 1257 } 1258 1259 Simplex simplex; 1260 /// The first index of the equality constraints, the index immediately after 1261 /// the last constraint in the initial product simplex. 1262 unsigned simplexConstraintOffset; 1263 /// A stack of snapshots, used for rolling back. 1264 SmallVector<unsigned, 8> snapshotStack; 1265 }; 1266 1267 // Return a + scale*b; 1268 static SmallVector<int64_t, 8> scaleAndAdd(ArrayRef<int64_t> a, int64_t scale, 1269 ArrayRef<int64_t> b) { 1270 assert(a.size() == b.size()); 1271 SmallVector<int64_t, 8> res; 1272 res.reserve(a.size()); 1273 for (unsigned i = 0, e = a.size(); i < e; ++i) 1274 res.push_back(a[i] + scale * b[i]); 1275 return res; 1276 } 1277 1278 /// Reduce the basis to try and find a direction in which the polytope is 1279 /// "thin". This only works for bounded polytopes. 1280 /// 1281 /// This is an implementation of the algorithm described in the paper 1282 /// "An Implementation of Generalized Basis Reduction for Integer Programming" 1283 /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross. 1284 /// 1285 /// Let b_{level}, b_{level + 1}, ... b_n be the current basis. 1286 /// Let width_i(v) = max <v, x - y> where x and y are points in the original 1287 /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i. 1288 /// 1289 /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u 1290 /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i 1291 /// be the dual variable associated with the constraint <b_i, x - y> = 0 when 1292 /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the 1293 /// minimizing value of u, if it were allowed to be fractional. Due to 1294 /// convexity, the minimizing integer value is either floor(dual_i) or 1295 /// ceil(dual_i), so we just need to check which of these gives a lower 1296 /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i. 1297 /// 1298 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new) 1299 /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the 1300 /// same i). Otherwise, we increment i. 1301 /// 1302 /// We keep f values and duals cached and invalidate them when necessary. 1303 /// Whenever possible, we use them instead of recomputing them. We implement the 1304 /// algorithm as follows. 1305 /// 1306 /// In an iteration at i we need to compute: 1307 /// a) width_i(b_{i + 1}) 1308 /// b) width_i(b_i) 1309 /// c) the integer u that minimizes width_i(b_{i + 1} + u*b_i) 1310 /// 1311 /// If width_i(b_i) is not already cached, we compute it. 1312 /// 1313 /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and 1314 /// store the duals from this computation. 1315 /// 1316 /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value 1317 /// of u as explained before, caches the duals from this computation, sets 1318 /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}). 1319 /// 1320 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and 1321 /// decrement i, resulting in the basis 1322 /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ... 1323 /// with corresponding f values 1324 /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ... 1325 /// The values up to i - 1 remain unchanged. We have just gotten the middle 1326 /// value from updateBasisWithUAndGetFCandidate, so we can update that in the 1327 /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from 1328 /// the cache. The iteration after decrementing needs exactly the duals from the 1329 /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache. 1330 /// 1331 /// When incrementing i, no cached f values get invalidated. However, the cached 1332 /// duals do get invalidated as the duals for the higher levels are different. 1333 void Simplex::reduceBasis(Matrix &basis, unsigned level) { 1334 const Fraction epsilon(3, 4); 1335 1336 if (level == basis.getNumRows() - 1) 1337 return; 1338 1339 GBRSimplex gbrSimplex(*this); 1340 SmallVector<Fraction, 8> width; 1341 SmallVector<int64_t, 8> dual; 1342 int64_t dualDenom; 1343 1344 // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the 1345 // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns 1346 // the new value of width_i(b_{i+1}). 1347 // 1348 // If dual_i is not an integer, the minimizing value must be either 1349 // floor(dual_i) or ceil(dual_i). We compute the expression for both and 1350 // choose the minimizing value. 1351 // 1352 // If dual_i is an integer, we don't need to perform these computations. We 1353 // know that in this case, 1354 // a) u = dual_i. 1355 // b) one can show that dual_j for j < i are the same duals we would have 1356 // gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals 1357 // are the ones already in the cache. 1358 // c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i), 1359 // which 1360 // one can show is equal to width_{i+1}(b_{i+1}). The latter value must 1361 // be in the cache, so we get it from there and return it. 1362 auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction { 1363 assert(i < level + dual.size() && "dual_i is not known!"); 1364 1365 int64_t u = floorDiv(dual[i - level], dualDenom); 1366 basis.addToRow(i, i + 1, u); 1367 if (dual[i - level] % dualDenom != 0) { 1368 SmallVector<int64_t, 8> candidateDual[2]; 1369 int64_t candidateDualDenom[2]; 1370 Fraction widthI[2]; 1371 1372 // Initially u is floor(dual) and basis reflects this. 1373 widthI[0] = gbrSimplex.computeWidthAndDuals( 1374 basis.getRow(i + 1), candidateDual[0], candidateDualDenom[0]); 1375 1376 // Now try ceil(dual), i.e. floor(dual) + 1. 1377 ++u; 1378 basis.addToRow(i, i + 1, 1); 1379 widthI[1] = gbrSimplex.computeWidthAndDuals( 1380 basis.getRow(i + 1), candidateDual[1], candidateDualDenom[1]); 1381 1382 unsigned j = widthI[0] < widthI[1] ? 0 : 1; 1383 if (j == 0) 1384 // Subtract 1 to go from u = ceil(dual) back to floor(dual). 1385 basis.addToRow(i, i + 1, -1); 1386 1387 // width_i(b{i+1} + u*b_i) should be minimized at our value of u. 1388 // We assert that this holds by checking that the values of width_i at 1389 // u - 1 and u + 1 are greater than or equal to the value at u. If the 1390 // width is lesser at either of the adjacent values, then our computed 1391 // value of u is clearly not the minimizer. Otherwise by convexity the 1392 // computed value of u is really the minimizer. 1393 1394 // Check the value at u - 1. 1395 assert(gbrSimplex.computeWidth(scaleAndAdd( 1396 basis.getRow(i + 1), -1, basis.getRow(i))) >= widthI[j] && 1397 "Computed u value does not minimize the width!"); 1398 // Check the value at u + 1. 1399 assert(gbrSimplex.computeWidth(scaleAndAdd( 1400 basis.getRow(i + 1), +1, basis.getRow(i))) >= widthI[j] && 1401 "Computed u value does not minimize the width!"); 1402 1403 dual = std::move(candidateDual[j]); 1404 dualDenom = candidateDualDenom[j]; 1405 return widthI[j]; 1406 } 1407 1408 assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved"); 1409 // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the 1410 // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in 1411 // the above expression is equal to basis.getRow(i+1) below.) 1412 assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) == 1413 width[i + 1 - level]); 1414 return width[i + 1 - level]; 1415 }; 1416 1417 // In the ith iteration of the loop, gbrSimplex has constraints for directions 1418 // from `level` to i - 1. 1419 unsigned i = level; 1420 while (i < basis.getNumRows() - 1) { 1421 if (i >= level + width.size()) { 1422 // We don't even know the value of f_i(b_i), so let's find that first. 1423 // We have to do this first since later we assume that width already 1424 // contains values up to and including i. 1425 1426 assert((i == 0 || i - 1 < level + width.size()) && 1427 "We are at level i but we don't know the value of width_{i-1}"); 1428 1429 // We don't actually use these duals at all, but it doesn't matter 1430 // because this case should only occur when i is level, and there are no 1431 // duals in that case anyway. 1432 assert(i == level && "This case should only occur when i == level"); 1433 width.push_back( 1434 gbrSimplex.computeWidthAndDuals(basis.getRow(i), dual, dualDenom)); 1435 } 1436 1437 if (i >= level + dual.size()) { 1438 assert(i + 1 >= level + width.size() && 1439 "We don't know dual_i but we know width_{i+1}"); 1440 // We don't know dual for our level, so let's find it. 1441 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1442 width.push_back(gbrSimplex.computeWidthAndDuals(basis.getRow(i + 1), dual, 1443 dualDenom)); 1444 gbrSimplex.removeLastEquality(); 1445 } 1446 1447 // This variable stores width_i(b_{i+1} + u*b_i). 1448 Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i); 1449 if (widthICandidate < epsilon * width[i - level]) { 1450 basis.swapRows(i, i + 1); 1451 width[i - level] = widthICandidate; 1452 // The values of width_{i+1}(b_{i+1}) and higher may change after the 1453 // swap, so we remove the cached values here. 1454 width.resize(i - level + 1); 1455 if (i == level) { 1456 dual.clear(); 1457 continue; 1458 } 1459 1460 gbrSimplex.removeLastEquality(); 1461 i--; 1462 continue; 1463 } 1464 1465 // Invalidate duals since the higher level needs to recompute its own duals. 1466 dual.clear(); 1467 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1468 i++; 1469 } 1470 } 1471 1472 /// Search for an integer sample point using a branch and bound algorithm. 1473 /// 1474 /// Each row in the basis matrix is a vector, and the set of basis vectors 1475 /// should span the space. Initially this is the identity matrix, 1476 /// i.e., the basis vectors are just the variables. 1477 /// 1478 /// In every level, a value is assigned to the level-th basis vector, as 1479 /// follows. Compute the minimum and maximum rational values of this direction. 1480 /// If only one integer point lies in this range, constrain the variable to 1481 /// have this value and recurse to the next variable. 1482 /// 1483 /// If the range has multiple values, perform generalized basis reduction via 1484 /// reduceBasis and then compute the bounds again. Now we try constraining 1485 /// this direction in the first value in this range and "recurse" to the next 1486 /// level. If we fail to find a sample, we try assigning the direction the next 1487 /// value in this range, and so on. 1488 /// 1489 /// If no integer sample is found from any of the assignments, or if the range 1490 /// contains no integer value, then of course the polytope is empty for the 1491 /// current assignment of the values in previous levels, so we return to 1492 /// the previous level. 1493 /// 1494 /// If we reach the last level where all the variables have been assigned values 1495 /// already, then we simply return the current sample point if it is integral, 1496 /// and go back to the previous level otherwise. 1497 /// 1498 /// To avoid potentially arbitrarily large recursion depths leading to stack 1499 /// overflows, this algorithm is implemented iteratively. 1500 Optional<SmallVector<int64_t, 8>> Simplex::findIntegerSample() { 1501 if (empty) 1502 return {}; 1503 1504 unsigned nDims = var.size(); 1505 Matrix basis = Matrix::identity(nDims); 1506 1507 unsigned level = 0; 1508 // The snapshot just before constraining a direction to a value at each level. 1509 SmallVector<unsigned, 8> snapshotStack; 1510 // The maximum value in the range of the direction for each level. 1511 SmallVector<int64_t, 8> upperBoundStack; 1512 // The next value to try constraining the basis vector to at each level. 1513 SmallVector<int64_t, 8> nextValueStack; 1514 1515 snapshotStack.reserve(basis.getNumRows()); 1516 upperBoundStack.reserve(basis.getNumRows()); 1517 nextValueStack.reserve(basis.getNumRows()); 1518 while (level != -1u) { 1519 if (level == basis.getNumRows()) { 1520 // We've assigned values to all variables. Return if we have a sample, 1521 // or go back up to the previous level otherwise. 1522 if (auto maybeSample = getSamplePointIfIntegral()) 1523 return maybeSample; 1524 level--; 1525 continue; 1526 } 1527 1528 if (level >= upperBoundStack.size()) { 1529 // We haven't populated the stack values for this level yet, so we have 1530 // just come down a level ("recursed"). Find the lower and upper bounds. 1531 // If there is more than one integer point in the range, perform 1532 // generalized basis reduction. 1533 SmallVector<int64_t, 8> basisCoeffs = 1534 llvm::to_vector<8>(basis.getRow(level)); 1535 basisCoeffs.push_back(0); 1536 1537 MaybeOptimum<int64_t> minRoundedUp, maxRoundedDown; 1538 std::tie(minRoundedUp, maxRoundedDown) = 1539 computeIntegerBounds(basisCoeffs); 1540 1541 // We don't have any integer values in the range. 1542 // Pop the stack and return up a level. 1543 if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) { 1544 assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) && 1545 "If one bound is empty, both should be."); 1546 snapshotStack.pop_back(); 1547 nextValueStack.pop_back(); 1548 upperBoundStack.pop_back(); 1549 level--; 1550 continue; 1551 } 1552 1553 // We already checked the empty case above. 1554 assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) && 1555 "Polyhedron should be bounded!"); 1556 1557 // Heuristic: if the sample point is integral at this point, just return 1558 // it. 1559 if (auto maybeSample = getSamplePointIfIntegral()) 1560 return *maybeSample; 1561 1562 if (*minRoundedUp < *maxRoundedDown) { 1563 reduceBasis(basis, level); 1564 basisCoeffs = llvm::to_vector<8>(basis.getRow(level)); 1565 basisCoeffs.push_back(0); 1566 std::tie(minRoundedUp, maxRoundedDown) = 1567 computeIntegerBounds(basisCoeffs); 1568 } 1569 1570 snapshotStack.push_back(getSnapshot()); 1571 // The smallest value in the range is the next value to try. 1572 // The values in the optionals are guaranteed to exist since we know the 1573 // polytope is bounded. 1574 nextValueStack.push_back(*minRoundedUp); 1575 upperBoundStack.push_back(*maxRoundedDown); 1576 } 1577 1578 assert((snapshotStack.size() - 1 == level && 1579 nextValueStack.size() - 1 == level && 1580 upperBoundStack.size() - 1 == level) && 1581 "Mismatched variable stack sizes!"); 1582 1583 // Whether we "recursed" or "returned" from a lower level, we rollback 1584 // to the snapshot of the starting state at this level. (in the "recursed" 1585 // case this has no effect) 1586 rollback(snapshotStack.back()); 1587 int64_t nextValue = nextValueStack.back(); 1588 nextValueStack.back()++; 1589 if (nextValue > upperBoundStack.back()) { 1590 // We have exhausted the range and found no solution. Pop the stack and 1591 // return up a level. 1592 snapshotStack.pop_back(); 1593 nextValueStack.pop_back(); 1594 upperBoundStack.pop_back(); 1595 level--; 1596 continue; 1597 } 1598 1599 // Try the next value in the range and "recurse" into the next level. 1600 SmallVector<int64_t, 8> basisCoeffs(basis.getRow(level).begin(), 1601 basis.getRow(level).end()); 1602 basisCoeffs.push_back(-nextValue); 1603 addEquality(basisCoeffs); 1604 level++; 1605 } 1606 1607 return {}; 1608 } 1609 1610 /// Compute the minimum and maximum integer values the expression can take. We 1611 /// compute each separately. 1612 std::pair<MaybeOptimum<int64_t>, MaybeOptimum<int64_t>> 1613 Simplex::computeIntegerBounds(ArrayRef<int64_t> coeffs) { 1614 MaybeOptimum<int64_t> minRoundedUp( 1615 computeOptimum(Simplex::Direction::Down, coeffs).map(ceil)); 1616 MaybeOptimum<int64_t> maxRoundedDown( 1617 computeOptimum(Simplex::Direction::Up, coeffs).map(floor)); 1618 return {minRoundedUp, maxRoundedDown}; 1619 } 1620 1621 void SimplexBase::print(raw_ostream &os) const { 1622 os << "rows = " << nRow << ", columns = " << nCol << "\n"; 1623 if (empty) 1624 os << "Simplex marked empty!\n"; 1625 os << "var: "; 1626 for (unsigned i = 0; i < var.size(); ++i) { 1627 if (i > 0) 1628 os << ", "; 1629 var[i].print(os); 1630 } 1631 os << "\ncon: "; 1632 for (unsigned i = 0; i < con.size(); ++i) { 1633 if (i > 0) 1634 os << ", "; 1635 con[i].print(os); 1636 } 1637 os << '\n'; 1638 for (unsigned row = 0; row < nRow; ++row) { 1639 if (row > 0) 1640 os << ", "; 1641 os << "r" << row << ": " << rowUnknown[row]; 1642 } 1643 os << '\n'; 1644 os << "c0: denom, c1: const"; 1645 for (unsigned col = 2; col < nCol; ++col) 1646 os << ", c" << col << ": " << colUnknown[col]; 1647 os << '\n'; 1648 for (unsigned row = 0; row < nRow; ++row) { 1649 for (unsigned col = 0; col < nCol; ++col) 1650 os << tableau(row, col) << '\t'; 1651 os << '\n'; 1652 } 1653 os << '\n'; 1654 } 1655 1656 void SimplexBase::dump() const { print(llvm::errs()); } 1657 1658 bool Simplex::isRationalSubsetOf(const IntegerPolyhedron &poly) { 1659 if (isEmpty()) 1660 return true; 1661 1662 for (unsigned i = 0, e = poly.getNumInequalities(); i < e; ++i) 1663 if (findIneqType(poly.getInequality(i)) != IneqType::Redundant) 1664 return false; 1665 1666 for (unsigned i = 0, e = poly.getNumEqualities(); i < e; ++i) 1667 if (!isRedundantEquality(poly.getEquality(i))) 1668 return false; 1669 1670 return true; 1671 } 1672 1673 /// Returns the type of the inequality with coefficients `coeffs`. 1674 /// Possible types are: 1675 /// Redundant The inequality is satisfied by all points in the polytope 1676 /// Cut The inequality is satisfied by some points, but not by others 1677 /// Separate The inequality is not satisfied by any point 1678 /// 1679 /// Internally, this computes the minimum and the maximum the inequality with 1680 /// coefficients `coeffs` can take. If the minimum is >= 0, the inequality holds 1681 /// for all points in the polytope, so it is redundant. If the minimum is <= 0 1682 /// and the maximum is >= 0, the points in between the minimum and the 1683 /// inequality do not satisfy it, the points in between the inequality and the 1684 /// maximum satisfy it. Hence, it is a cut inequality. If both are < 0, no 1685 /// points of the polytope satisfy the inequality, which means it is a separate 1686 /// inequality. 1687 Simplex::IneqType Simplex::findIneqType(ArrayRef<int64_t> coeffs) { 1688 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 1689 if (minimum.isBounded() && *minimum >= Fraction(0, 1)) { 1690 return IneqType::Redundant; 1691 } 1692 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 1693 if ((!minimum.isBounded() || *minimum <= Fraction(0, 1)) && 1694 (!maximum.isBounded() || *maximum >= Fraction(0, 1))) { 1695 return IneqType::Cut; 1696 } 1697 return IneqType::Separate; 1698 } 1699 1700 /// Checks whether the type of the inequality with coefficients `coeffs` 1701 /// is Redundant. 1702 bool Simplex::isRedundantInequality(ArrayRef<int64_t> coeffs) { 1703 assert(!empty && 1704 "It is not meaningful to ask about redundancy in an empty set!"); 1705 return findIneqType(coeffs) == IneqType::Redundant; 1706 } 1707 1708 /// Check whether the equality given by `coeffs == 0` is redundant given 1709 /// the existing constraints. This is redundant when `coeffs` is already 1710 /// always zero under the existing constraints. `coeffs` is always zero 1711 /// when the minimum and maximum value that `coeffs` can take are both zero. 1712 bool Simplex::isRedundantEquality(ArrayRef<int64_t> coeffs) { 1713 assert(!empty && 1714 "It is not meaningful to ask about redundancy in an empty set!"); 1715 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 1716 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 1717 assert((!minimum.isEmpty() && !maximum.isEmpty()) && 1718 "Optima should be non-empty for a non-empty set"); 1719 return minimum.isBounded() && maximum.isBounded() && 1720 *maximum == Fraction(0, 1) && *minimum == Fraction(0, 1); 1721 } 1722