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 undoLog.push_back(UndoLogEntry::RemoveLastConstraint); 70 71 // Zero out the new row. 72 tableau.fillRow(nRow - 1, 0); 73 74 tableau(nRow - 1, 0) = 1; 75 return con.size() - 1; 76 } 77 78 /// Add a new row to the tableau corresponding to the given constant term and 79 /// list of coefficients. The coefficients are specified as a vector of 80 /// (variable index, coefficient) pairs. 81 unsigned SimplexBase::addRow(ArrayRef<int64_t> coeffs, bool makeRestricted) { 82 assert(coeffs.size() == var.size() + 1 && 83 "Incorrect number of coefficients!"); 84 85 addZeroRow(makeRestricted); 86 tableau(nRow - 1, 1) = coeffs.back(); 87 if (usingBigM) { 88 // When the lexicographic pivot rule is used, instead of the variables 89 // 90 // x, y, z ... 91 // 92 // we internally use the variables 93 // 94 // M, M + x, M + y, M + z, ... 95 // 96 // where M is the big M parameter. As such, when the user tries to add 97 // a row ax + by + cz + d, we express it in terms of our internal variables 98 // as -(a + b + c)M + a(M + x) + b(M + y) + c(M + z) + d. 99 int64_t bigMCoeff = 0; 100 for (unsigned i = 0; i < coeffs.size() - 1; ++i) 101 bigMCoeff -= coeffs[i]; 102 // The coefficient to the big M parameter is stored in column 2. 103 tableau(nRow - 1, 2) = bigMCoeff; 104 } 105 106 // Process each given variable coefficient. 107 for (unsigned i = 0; i < var.size(); ++i) { 108 unsigned pos = var[i].pos; 109 if (coeffs[i] == 0) 110 continue; 111 112 if (var[i].orientation == Orientation::Column) { 113 // If a variable is in column position at column col, then we just add the 114 // coefficient for that variable (scaled by the common row denominator) to 115 // the corresponding entry in the new row. 116 tableau(nRow - 1, pos) += coeffs[i] * tableau(nRow - 1, 0); 117 continue; 118 } 119 120 // If the variable is in row position, we need to add that row to the new 121 // row, scaled by the coefficient for the variable, accounting for the two 122 // rows potentially having different denominators. The new denominator is 123 // the lcm of the two. 124 int64_t lcm = mlir::lcm(tableau(nRow - 1, 0), tableau(pos, 0)); 125 int64_t nRowCoeff = lcm / tableau(nRow - 1, 0); 126 int64_t idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0)); 127 tableau(nRow - 1, 0) = lcm; 128 for (unsigned col = 1; col < nCol; ++col) 129 tableau(nRow - 1, col) = 130 nRowCoeff * tableau(nRow - 1, col) + idxRowCoeff * tableau(pos, col); 131 } 132 133 normalizeRow(nRow - 1); 134 // Push to undo log along with the index of the new constraint. 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 LexSimplexBase::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::maybeGetNonIntegralVarRow() 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 = maybeGetNonIntegralVarRow()) { 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>( 215 llvm::map_range(*sample, std::mem_fn(&Fraction::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 LexSimplexBase::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 LexSimplexBase::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 LexSimplexBase::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 /// We add the usual floor division constraints: 822 /// `0 <= coeffs - denom*q <= denom - 1`, where `q` is the new division 823 /// variable. 824 /// 825 /// This constrains the remainder `coeffs - denom*q` to be in the 826 /// range `[0, denom - 1]`, which fixes the integer value of the quotient `q`. 827 void SimplexBase::addDivisionVariable(ArrayRef<int64_t> coeffs, int64_t denom) { 828 assert(denom != 0 && "Cannot divide by zero!\n"); 829 appendVariable(); 830 831 SmallVector<int64_t, 8> ineq(coeffs.begin(), coeffs.end()); 832 int64_t constTerm = ineq.back(); 833 ineq.back() = -denom; 834 ineq.push_back(constTerm); 835 addInequality(ineq); 836 837 for (int64_t &coeff : ineq) 838 coeff = -coeff; 839 ineq.back() += denom - 1; 840 addInequality(ineq); 841 } 842 843 void SimplexBase::appendVariable(unsigned count) { 844 if (count == 0) 845 return; 846 var.reserve(var.size() + count); 847 colUnknown.reserve(colUnknown.size() + count); 848 for (unsigned i = 0; i < count; ++i) { 849 nCol++; 850 var.emplace_back(Orientation::Column, /*restricted=*/false, 851 /*pos=*/nCol - 1); 852 colUnknown.push_back(var.size() - 1); 853 } 854 tableau.resizeHorizontally(nCol); 855 undoLog.insert(undoLog.end(), count, UndoLogEntry::RemoveLastVariable); 856 } 857 858 /// Add all the constraints from the given IntegerRelation. 859 void SimplexBase::intersectIntegerRelation(const IntegerRelation &rel) { 860 assert(rel.getNumIds() == getNumVariables() && 861 "IntegerRelation must have same dimensionality as simplex"); 862 for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) 863 addInequality(rel.getInequality(i)); 864 for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) 865 addEquality(rel.getEquality(i)); 866 } 867 868 MaybeOptimum<Fraction> Simplex::computeRowOptimum(Direction direction, 869 unsigned row) { 870 // Keep trying to find a pivot for the row in the specified direction. 871 while (Optional<Pivot> maybePivot = findPivot(row, direction)) { 872 // If findPivot returns a pivot involving the row itself, then the optimum 873 // is unbounded, so we return None. 874 if (maybePivot->row == row) 875 return OptimumKind::Unbounded; 876 pivot(*maybePivot); 877 } 878 879 // The row has reached its optimal sample value, which we return. 880 // The sample value is the entry in the constant column divided by the common 881 // denominator for this row. 882 return Fraction(tableau(row, 1), tableau(row, 0)); 883 } 884 885 /// Compute the optimum of the specified expression in the specified direction, 886 /// or None if it is unbounded. 887 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 888 ArrayRef<int64_t> coeffs) { 889 if (empty) 890 return OptimumKind::Empty; 891 892 SimplexRollbackScopeExit scopeExit(*this); 893 unsigned conIndex = addRow(coeffs); 894 unsigned row = con[conIndex].pos; 895 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 896 return optimum; 897 } 898 899 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 900 Unknown &u) { 901 if (empty) 902 return OptimumKind::Empty; 903 if (u.orientation == Orientation::Column) { 904 unsigned column = u.pos; 905 Optional<unsigned> pivotRow = findPivotRow({}, direction, column); 906 // If no pivot is returned, the constraint is unbounded in the specified 907 // direction. 908 if (!pivotRow) 909 return OptimumKind::Unbounded; 910 pivot(*pivotRow, column); 911 } 912 913 unsigned row = u.pos; 914 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 915 if (u.restricted && direction == Direction::Down && 916 (optimum.isUnbounded() || *optimum < Fraction(0, 1))) { 917 if (failed(restoreRow(u))) 918 llvm_unreachable("Could not restore row!"); 919 } 920 return optimum; 921 } 922 923 bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) { 924 assert(!empty && "It is not meaningful to ask whether a direction is bounded " 925 "in an empty set."); 926 // The constraint's perpendicular is already bounded below, since it is a 927 // constraint. If it is also bounded above, we can return true. 928 return computeOptimum(Direction::Up, con[constraintIndex]).isBounded(); 929 } 930 931 /// Redundant constraints are those that are in row orientation and lie in 932 /// rows 0 to nRedundant - 1. 933 bool Simplex::isMarkedRedundant(unsigned constraintIndex) const { 934 const Unknown &u = con[constraintIndex]; 935 return u.orientation == Orientation::Row && u.pos < nRedundant; 936 } 937 938 /// Mark the specified row redundant. 939 /// 940 /// This is done by moving the unknown to the end of the block of redundant 941 /// rows (namely, to row nRedundant) and incrementing nRedundant to 942 /// accomodate the new redundant row. 943 void Simplex::markRowRedundant(Unknown &u) { 944 assert(u.orientation == Orientation::Row && 945 "Unknown should be in row position!"); 946 assert(u.pos >= nRedundant && "Unknown is already marked redundant!"); 947 swapRows(u.pos, nRedundant); 948 ++nRedundant; 949 undoLog.emplace_back(UndoLogEntry::UnmarkLastRedundant); 950 } 951 952 /// Find a subset of constraints that is redundant and mark them redundant. 953 void Simplex::detectRedundant() { 954 // It is not meaningful to talk about redundancy for empty sets. 955 if (empty) 956 return; 957 958 // Iterate through the constraints and check for each one if it can attain 959 // negative sample values. If it can, it's not redundant. Otherwise, it is. 960 // We mark redundant constraints redundant. 961 // 962 // Constraints that get marked redundant in one iteration are not respected 963 // when checking constraints in later iterations. This prevents, for example, 964 // two identical constraints both being marked redundant since each is 965 // redundant given the other one. In this example, only the first of the 966 // constraints that is processed will get marked redundant, as it should be. 967 for (Unknown &u : con) { 968 if (u.orientation == Orientation::Column) { 969 unsigned column = u.pos; 970 Optional<unsigned> pivotRow = findPivotRow({}, Direction::Down, column); 971 // If no downward pivot is returned, the constraint is unbounded below 972 // and hence not redundant. 973 if (!pivotRow) 974 continue; 975 pivot(*pivotRow, column); 976 } 977 978 unsigned row = u.pos; 979 MaybeOptimum<Fraction> minimum = computeRowOptimum(Direction::Down, row); 980 if (minimum.isUnbounded() || *minimum < Fraction(0, 1)) { 981 // Constraint is unbounded below or can attain negative sample values and 982 // hence is not redundant. 983 if (failed(restoreRow(u))) 984 llvm_unreachable("Could not restore non-redundant row!"); 985 continue; 986 } 987 988 markRowRedundant(u); 989 } 990 } 991 992 bool Simplex::isUnbounded() { 993 if (empty) 994 return false; 995 996 SmallVector<int64_t, 8> dir(var.size() + 1); 997 for (unsigned i = 0; i < var.size(); ++i) { 998 dir[i] = 1; 999 1000 if (computeOptimum(Direction::Up, dir).isUnbounded()) 1001 return true; 1002 1003 if (computeOptimum(Direction::Down, dir).isUnbounded()) 1004 return true; 1005 1006 dir[i] = 0; 1007 } 1008 return false; 1009 } 1010 1011 /// Make a tableau to represent a pair of points in the original tableau. 1012 /// 1013 /// The product constraints and variables are stored as: first A's, then B's. 1014 /// 1015 /// The product tableau has row layout: 1016 /// A's redundant rows, B's redundant rows, A's other rows, B's other rows. 1017 /// 1018 /// It has column layout: 1019 /// denominator, constant, A's columns, B's columns. 1020 Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) { 1021 unsigned numVar = a.getNumVariables() + b.getNumVariables(); 1022 unsigned numCon = a.getNumConstraints() + b.getNumConstraints(); 1023 Simplex result(numVar); 1024 1025 result.tableau.resizeVertically(numCon); 1026 result.empty = a.empty || b.empty; 1027 1028 auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) { 1029 SmallVector<Unknown, 8> result; 1030 result.reserve(v.size() + w.size()); 1031 result.insert(result.end(), v.begin(), v.end()); 1032 result.insert(result.end(), w.begin(), w.end()); 1033 return result; 1034 }; 1035 result.con = concat(a.con, b.con); 1036 result.var = concat(a.var, b.var); 1037 1038 auto indexFromBIndex = [&](int index) { 1039 return index >= 0 ? a.getNumVariables() + index 1040 : ~(a.getNumConstraints() + ~index); 1041 }; 1042 1043 result.colUnknown.assign(2, nullIndex); 1044 for (unsigned i = 2; i < a.nCol; ++i) { 1045 result.colUnknown.push_back(a.colUnknown[i]); 1046 result.unknownFromIndex(result.colUnknown.back()).pos = 1047 result.colUnknown.size() - 1; 1048 } 1049 for (unsigned i = 2; i < b.nCol; ++i) { 1050 result.colUnknown.push_back(indexFromBIndex(b.colUnknown[i])); 1051 result.unknownFromIndex(result.colUnknown.back()).pos = 1052 result.colUnknown.size() - 1; 1053 } 1054 1055 auto appendRowFromA = [&](unsigned row) { 1056 for (unsigned col = 0; col < a.nCol; ++col) 1057 result.tableau(result.nRow, col) = a.tableau(row, col); 1058 result.rowUnknown.push_back(a.rowUnknown[row]); 1059 result.unknownFromIndex(result.rowUnknown.back()).pos = 1060 result.rowUnknown.size() - 1; 1061 result.nRow++; 1062 }; 1063 1064 // Also fixes the corresponding entry in rowUnknown and var/con (as the case 1065 // may be). 1066 auto appendRowFromB = [&](unsigned row) { 1067 result.tableau(result.nRow, 0) = b.tableau(row, 0); 1068 result.tableau(result.nRow, 1) = b.tableau(row, 1); 1069 1070 unsigned offset = a.nCol - 2; 1071 for (unsigned col = 2; col < b.nCol; ++col) 1072 result.tableau(result.nRow, offset + col) = b.tableau(row, col); 1073 result.rowUnknown.push_back(indexFromBIndex(b.rowUnknown[row])); 1074 result.unknownFromIndex(result.rowUnknown.back()).pos = 1075 result.rowUnknown.size() - 1; 1076 result.nRow++; 1077 }; 1078 1079 result.nRedundant = a.nRedundant + b.nRedundant; 1080 for (unsigned row = 0; row < a.nRedundant; ++row) 1081 appendRowFromA(row); 1082 for (unsigned row = 0; row < b.nRedundant; ++row) 1083 appendRowFromB(row); 1084 for (unsigned row = a.nRedundant; row < a.nRow; ++row) 1085 appendRowFromA(row); 1086 for (unsigned row = b.nRedundant; row < b.nRow; ++row) 1087 appendRowFromB(row); 1088 1089 return result; 1090 } 1091 1092 Optional<SmallVector<Fraction, 8>> Simplex::getRationalSample() const { 1093 if (empty) 1094 return {}; 1095 1096 SmallVector<Fraction, 8> sample; 1097 sample.reserve(var.size()); 1098 // Push the sample value for each variable into the vector. 1099 for (const Unknown &u : var) { 1100 if (u.orientation == Orientation::Column) { 1101 // If the variable is in column position, its sample value is zero. 1102 sample.emplace_back(0, 1); 1103 } else { 1104 // If the variable is in row position, its sample value is the 1105 // entry in the constant column divided by the denominator. 1106 int64_t denom = tableau(u.pos, 0); 1107 sample.emplace_back(tableau(u.pos, 1), denom); 1108 } 1109 } 1110 return sample; 1111 } 1112 1113 void LexSimplexBase::addInequality(ArrayRef<int64_t> coeffs) { 1114 addRow(coeffs, /*makeRestricted=*/true); 1115 } 1116 1117 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::getRationalSample() const { 1118 if (empty) 1119 return OptimumKind::Empty; 1120 1121 SmallVector<Fraction, 8> sample; 1122 sample.reserve(var.size()); 1123 // Push the sample value for each variable into the vector. 1124 for (const Unknown &u : var) { 1125 // When the big M parameter is being used, each variable x is represented 1126 // as M + x, so its sample value is finite if and only if it is of the 1127 // form 1*M + c. If the coefficient of M is not one then the sample value 1128 // is infinite, and we return an empty optional. 1129 1130 if (u.orientation == Orientation::Column) { 1131 // If the variable is in column position, the sample value of M + x is 1132 // zero, so x = -M which is unbounded. 1133 return OptimumKind::Unbounded; 1134 } 1135 1136 // If the variable is in row position, its sample value is the 1137 // entry in the constant column divided by the denominator. 1138 int64_t denom = tableau(u.pos, 0); 1139 if (usingBigM) 1140 if (tableau(u.pos, 2) != denom) 1141 return OptimumKind::Unbounded; 1142 sample.emplace_back(tableau(u.pos, 1), denom); 1143 } 1144 return sample; 1145 } 1146 1147 Optional<SmallVector<int64_t, 8>> Simplex::getSamplePointIfIntegral() const { 1148 // If the tableau is empty, no sample point exists. 1149 if (empty) 1150 return {}; 1151 1152 // The value will always exist since the Simplex is non-empty. 1153 SmallVector<Fraction, 8> rationalSample = *getRationalSample(); 1154 SmallVector<int64_t, 8> integerSample; 1155 integerSample.reserve(var.size()); 1156 for (const Fraction &coord : rationalSample) { 1157 // If the sample is non-integral, return None. 1158 if (coord.num % coord.den != 0) 1159 return {}; 1160 integerSample.push_back(coord.num / coord.den); 1161 } 1162 return integerSample; 1163 } 1164 1165 /// Given a simplex for a polytope, construct a new simplex whose variables are 1166 /// identified with a pair of points (x, y) in the original polytope. Supports 1167 /// some operations needed for generalized basis reduction. In what follows, 1168 /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the 1169 /// dimension of the original polytope. 1170 /// 1171 /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It 1172 /// also supports rolling back this addition, by maintaining a snapshot stack 1173 /// that contains a snapshot of the Simplex's state for each equality, just 1174 /// before that equality was added. 1175 class presburger::GBRSimplex { 1176 using Orientation = Simplex::Orientation; 1177 1178 public: 1179 GBRSimplex(const Simplex &originalSimplex) 1180 : simplex(Simplex::makeProduct(originalSimplex, originalSimplex)), 1181 simplexConstraintOffset(simplex.getNumConstraints()) {} 1182 1183 /// Add an equality dotProduct(dir, x - y) == 0. 1184 /// First pushes a snapshot for the current simplex state to the stack so 1185 /// that this can be rolled back later. 1186 void addEqualityForDirection(ArrayRef<int64_t> dir) { 1187 assert(llvm::any_of(dir, [](int64_t x) { return x != 0; }) && 1188 "Direction passed is the zero vector!"); 1189 snapshotStack.push_back(simplex.getSnapshot()); 1190 simplex.addEquality(getCoeffsForDirection(dir)); 1191 } 1192 /// Compute max(dotProduct(dir, x - y)). 1193 Fraction computeWidth(ArrayRef<int64_t> dir) { 1194 MaybeOptimum<Fraction> maybeWidth = 1195 simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir)); 1196 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1197 return *maybeWidth; 1198 } 1199 1200 /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only 1201 /// the direction equalities to `dual`. 1202 Fraction computeWidthAndDuals(ArrayRef<int64_t> dir, 1203 SmallVectorImpl<int64_t> &dual, 1204 int64_t &dualDenom) { 1205 // We can't just call into computeWidth or computeOptimum since we need to 1206 // access the state of the tableau after computing the optimum, and these 1207 // functions rollback the insertion of the objective function into the 1208 // tableau before returning. We instead add a row for the objective function 1209 // ourselves, call into computeOptimum, compute the duals from the tableau 1210 // state, and finally rollback the addition of the row before returning. 1211 SimplexRollbackScopeExit scopeExit(simplex); 1212 unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir)); 1213 unsigned row = simplex.con[conIndex].pos; 1214 MaybeOptimum<Fraction> maybeWidth = 1215 simplex.computeRowOptimum(Simplex::Direction::Up, row); 1216 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1217 dualDenom = simplex.tableau(row, 0); 1218 dual.clear(); 1219 1220 // The increment is i += 2 because equalities are added as two inequalities, 1221 // one positive and one negative. Each iteration processes one equality. 1222 for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) { 1223 // The dual variable for an inequality in column orientation is the 1224 // negative of its coefficient at the objective row. If the inequality is 1225 // in row orientation, the corresponding dual variable is zero. 1226 // 1227 // We want the dual for the original equality, which corresponds to two 1228 // inequalities: a positive inequality, which has the same coefficients as 1229 // the equality, and a negative equality, which has negated coefficients. 1230 // 1231 // Note that at most one of these inequalities can be in column 1232 // orientation because the column unknowns should form a basis and hence 1233 // must be linearly independent. If the positive inequality is in column 1234 // position, its dual is the dual corresponding to the equality. If the 1235 // negative inequality is in column position, the negation of its dual is 1236 // the dual corresponding to the equality. If neither is in column 1237 // position, then that means that this equality is redundant, and its dual 1238 // is zero. 1239 // 1240 // Note that it is NOT valid to perform pivots during the computation of 1241 // the duals. This entire dual computation must be performed on the same 1242 // tableau configuration. 1243 assert(!(simplex.con[i].orientation == Orientation::Column && 1244 simplex.con[i + 1].orientation == Orientation::Column) && 1245 "Both inequalities for the equality cannot be in column " 1246 "orientation!"); 1247 if (simplex.con[i].orientation == Orientation::Column) 1248 dual.push_back(-simplex.tableau(row, simplex.con[i].pos)); 1249 else if (simplex.con[i + 1].orientation == Orientation::Column) 1250 dual.push_back(simplex.tableau(row, simplex.con[i + 1].pos)); 1251 else 1252 dual.push_back(0); 1253 } 1254 return *maybeWidth; 1255 } 1256 1257 /// Remove the last equality that was added through addEqualityForDirection. 1258 /// 1259 /// We do this by rolling back to the snapshot at the top of the stack, which 1260 /// should be a snapshot taken just before the last equality was added. 1261 void removeLastEquality() { 1262 assert(!snapshotStack.empty() && "Snapshot stack is empty!"); 1263 simplex.rollback(snapshotStack.back()); 1264 snapshotStack.pop_back(); 1265 } 1266 1267 private: 1268 /// Returns coefficients of the expression 'dot_product(dir, x - y)', 1269 /// i.e., dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n 1270 /// - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n, 1271 /// where n is the dimension of the original polytope. 1272 SmallVector<int64_t, 8> getCoeffsForDirection(ArrayRef<int64_t> dir) { 1273 assert(2 * dir.size() == simplex.getNumVariables() && 1274 "Direction vector has wrong dimensionality"); 1275 SmallVector<int64_t, 8> coeffs(dir.begin(), dir.end()); 1276 coeffs.reserve(2 * dir.size()); 1277 for (int64_t coeff : dir) 1278 coeffs.push_back(-coeff); 1279 coeffs.push_back(0); // constant term 1280 return coeffs; 1281 } 1282 1283 Simplex simplex; 1284 /// The first index of the equality constraints, the index immediately after 1285 /// the last constraint in the initial product simplex. 1286 unsigned simplexConstraintOffset; 1287 /// A stack of snapshots, used for rolling back. 1288 SmallVector<unsigned, 8> snapshotStack; 1289 }; 1290 1291 // Return a + scale*b; 1292 static SmallVector<int64_t, 8> scaleAndAdd(ArrayRef<int64_t> a, int64_t scale, 1293 ArrayRef<int64_t> b) { 1294 assert(a.size() == b.size()); 1295 SmallVector<int64_t, 8> res; 1296 res.reserve(a.size()); 1297 for (unsigned i = 0, e = a.size(); i < e; ++i) 1298 res.push_back(a[i] + scale * b[i]); 1299 return res; 1300 } 1301 1302 /// Reduce the basis to try and find a direction in which the polytope is 1303 /// "thin". This only works for bounded polytopes. 1304 /// 1305 /// This is an implementation of the algorithm described in the paper 1306 /// "An Implementation of Generalized Basis Reduction for Integer Programming" 1307 /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross. 1308 /// 1309 /// Let b_{level}, b_{level + 1}, ... b_n be the current basis. 1310 /// Let width_i(v) = max <v, x - y> where x and y are points in the original 1311 /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i. 1312 /// 1313 /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u 1314 /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i 1315 /// be the dual variable associated with the constraint <b_i, x - y> = 0 when 1316 /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the 1317 /// minimizing value of u, if it were allowed to be fractional. Due to 1318 /// convexity, the minimizing integer value is either floor(dual_i) or 1319 /// ceil(dual_i), so we just need to check which of these gives a lower 1320 /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i. 1321 /// 1322 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new) 1323 /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the 1324 /// same i). Otherwise, we increment i. 1325 /// 1326 /// We keep f values and duals cached and invalidate them when necessary. 1327 /// Whenever possible, we use them instead of recomputing them. We implement the 1328 /// algorithm as follows. 1329 /// 1330 /// In an iteration at i we need to compute: 1331 /// a) width_i(b_{i + 1}) 1332 /// b) width_i(b_i) 1333 /// c) the integer u that minimizes width_i(b_{i + 1} + u*b_i) 1334 /// 1335 /// If width_i(b_i) is not already cached, we compute it. 1336 /// 1337 /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and 1338 /// store the duals from this computation. 1339 /// 1340 /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value 1341 /// of u as explained before, caches the duals from this computation, sets 1342 /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}). 1343 /// 1344 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and 1345 /// decrement i, resulting in the basis 1346 /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ... 1347 /// with corresponding f values 1348 /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ... 1349 /// The values up to i - 1 remain unchanged. We have just gotten the middle 1350 /// value from updateBasisWithUAndGetFCandidate, so we can update that in the 1351 /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from 1352 /// the cache. The iteration after decrementing needs exactly the duals from the 1353 /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache. 1354 /// 1355 /// When incrementing i, no cached f values get invalidated. However, the cached 1356 /// duals do get invalidated as the duals for the higher levels are different. 1357 void Simplex::reduceBasis(Matrix &basis, unsigned level) { 1358 const Fraction epsilon(3, 4); 1359 1360 if (level == basis.getNumRows() - 1) 1361 return; 1362 1363 GBRSimplex gbrSimplex(*this); 1364 SmallVector<Fraction, 8> width; 1365 SmallVector<int64_t, 8> dual; 1366 int64_t dualDenom; 1367 1368 // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the 1369 // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns 1370 // the new value of width_i(b_{i+1}). 1371 // 1372 // If dual_i is not an integer, the minimizing value must be either 1373 // floor(dual_i) or ceil(dual_i). We compute the expression for both and 1374 // choose the minimizing value. 1375 // 1376 // If dual_i is an integer, we don't need to perform these computations. We 1377 // know that in this case, 1378 // a) u = dual_i. 1379 // b) one can show that dual_j for j < i are the same duals we would have 1380 // gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals 1381 // are the ones already in the cache. 1382 // c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i), 1383 // which 1384 // one can show is equal to width_{i+1}(b_{i+1}). The latter value must 1385 // be in the cache, so we get it from there and return it. 1386 auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction { 1387 assert(i < level + dual.size() && "dual_i is not known!"); 1388 1389 int64_t u = floorDiv(dual[i - level], dualDenom); 1390 basis.addToRow(i, i + 1, u); 1391 if (dual[i - level] % dualDenom != 0) { 1392 SmallVector<int64_t, 8> candidateDual[2]; 1393 int64_t candidateDualDenom[2]; 1394 Fraction widthI[2]; 1395 1396 // Initially u is floor(dual) and basis reflects this. 1397 widthI[0] = gbrSimplex.computeWidthAndDuals( 1398 basis.getRow(i + 1), candidateDual[0], candidateDualDenom[0]); 1399 1400 // Now try ceil(dual), i.e. floor(dual) + 1. 1401 ++u; 1402 basis.addToRow(i, i + 1, 1); 1403 widthI[1] = gbrSimplex.computeWidthAndDuals( 1404 basis.getRow(i + 1), candidateDual[1], candidateDualDenom[1]); 1405 1406 unsigned j = widthI[0] < widthI[1] ? 0 : 1; 1407 if (j == 0) 1408 // Subtract 1 to go from u = ceil(dual) back to floor(dual). 1409 basis.addToRow(i, i + 1, -1); 1410 1411 // width_i(b{i+1} + u*b_i) should be minimized at our value of u. 1412 // We assert that this holds by checking that the values of width_i at 1413 // u - 1 and u + 1 are greater than or equal to the value at u. If the 1414 // width is lesser at either of the adjacent values, then our computed 1415 // value of u is clearly not the minimizer. Otherwise by convexity the 1416 // computed value of u is really the minimizer. 1417 1418 // Check the value at u - 1. 1419 assert(gbrSimplex.computeWidth(scaleAndAdd( 1420 basis.getRow(i + 1), -1, basis.getRow(i))) >= widthI[j] && 1421 "Computed u value does not minimize the width!"); 1422 // Check the value at u + 1. 1423 assert(gbrSimplex.computeWidth(scaleAndAdd( 1424 basis.getRow(i + 1), +1, basis.getRow(i))) >= widthI[j] && 1425 "Computed u value does not minimize the width!"); 1426 1427 dual = std::move(candidateDual[j]); 1428 dualDenom = candidateDualDenom[j]; 1429 return widthI[j]; 1430 } 1431 1432 assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved"); 1433 // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the 1434 // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in 1435 // the above expression is equal to basis.getRow(i+1) below.) 1436 assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) == 1437 width[i + 1 - level]); 1438 return width[i + 1 - level]; 1439 }; 1440 1441 // In the ith iteration of the loop, gbrSimplex has constraints for directions 1442 // from `level` to i - 1. 1443 unsigned i = level; 1444 while (i < basis.getNumRows() - 1) { 1445 if (i >= level + width.size()) { 1446 // We don't even know the value of f_i(b_i), so let's find that first. 1447 // We have to do this first since later we assume that width already 1448 // contains values up to and including i. 1449 1450 assert((i == 0 || i - 1 < level + width.size()) && 1451 "We are at level i but we don't know the value of width_{i-1}"); 1452 1453 // We don't actually use these duals at all, but it doesn't matter 1454 // because this case should only occur when i is level, and there are no 1455 // duals in that case anyway. 1456 assert(i == level && "This case should only occur when i == level"); 1457 width.push_back( 1458 gbrSimplex.computeWidthAndDuals(basis.getRow(i), dual, dualDenom)); 1459 } 1460 1461 if (i >= level + dual.size()) { 1462 assert(i + 1 >= level + width.size() && 1463 "We don't know dual_i but we know width_{i+1}"); 1464 // We don't know dual for our level, so let's find it. 1465 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1466 width.push_back(gbrSimplex.computeWidthAndDuals(basis.getRow(i + 1), dual, 1467 dualDenom)); 1468 gbrSimplex.removeLastEquality(); 1469 } 1470 1471 // This variable stores width_i(b_{i+1} + u*b_i). 1472 Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i); 1473 if (widthICandidate < epsilon * width[i - level]) { 1474 basis.swapRows(i, i + 1); 1475 width[i - level] = widthICandidate; 1476 // The values of width_{i+1}(b_{i+1}) and higher may change after the 1477 // swap, so we remove the cached values here. 1478 width.resize(i - level + 1); 1479 if (i == level) { 1480 dual.clear(); 1481 continue; 1482 } 1483 1484 gbrSimplex.removeLastEquality(); 1485 i--; 1486 continue; 1487 } 1488 1489 // Invalidate duals since the higher level needs to recompute its own duals. 1490 dual.clear(); 1491 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1492 i++; 1493 } 1494 } 1495 1496 /// Search for an integer sample point using a branch and bound algorithm. 1497 /// 1498 /// Each row in the basis matrix is a vector, and the set of basis vectors 1499 /// should span the space. Initially this is the identity matrix, 1500 /// i.e., the basis vectors are just the variables. 1501 /// 1502 /// In every level, a value is assigned to the level-th basis vector, as 1503 /// follows. Compute the minimum and maximum rational values of this direction. 1504 /// If only one integer point lies in this range, constrain the variable to 1505 /// have this value and recurse to the next variable. 1506 /// 1507 /// If the range has multiple values, perform generalized basis reduction via 1508 /// reduceBasis and then compute the bounds again. Now we try constraining 1509 /// this direction in the first value in this range and "recurse" to the next 1510 /// level. If we fail to find a sample, we try assigning the direction the next 1511 /// value in this range, and so on. 1512 /// 1513 /// If no integer sample is found from any of the assignments, or if the range 1514 /// contains no integer value, then of course the polytope is empty for the 1515 /// current assignment of the values in previous levels, so we return to 1516 /// the previous level. 1517 /// 1518 /// If we reach the last level where all the variables have been assigned values 1519 /// already, then we simply return the current sample point if it is integral, 1520 /// and go back to the previous level otherwise. 1521 /// 1522 /// To avoid potentially arbitrarily large recursion depths leading to stack 1523 /// overflows, this algorithm is implemented iteratively. 1524 Optional<SmallVector<int64_t, 8>> Simplex::findIntegerSample() { 1525 if (empty) 1526 return {}; 1527 1528 unsigned nDims = var.size(); 1529 Matrix basis = Matrix::identity(nDims); 1530 1531 unsigned level = 0; 1532 // The snapshot just before constraining a direction to a value at each level. 1533 SmallVector<unsigned, 8> snapshotStack; 1534 // The maximum value in the range of the direction for each level. 1535 SmallVector<int64_t, 8> upperBoundStack; 1536 // The next value to try constraining the basis vector to at each level. 1537 SmallVector<int64_t, 8> nextValueStack; 1538 1539 snapshotStack.reserve(basis.getNumRows()); 1540 upperBoundStack.reserve(basis.getNumRows()); 1541 nextValueStack.reserve(basis.getNumRows()); 1542 while (level != -1u) { 1543 if (level == basis.getNumRows()) { 1544 // We've assigned values to all variables. Return if we have a sample, 1545 // or go back up to the previous level otherwise. 1546 if (auto maybeSample = getSamplePointIfIntegral()) 1547 return maybeSample; 1548 level--; 1549 continue; 1550 } 1551 1552 if (level >= upperBoundStack.size()) { 1553 // We haven't populated the stack values for this level yet, so we have 1554 // just come down a level ("recursed"). Find the lower and upper bounds. 1555 // If there is more than one integer point in the range, perform 1556 // generalized basis reduction. 1557 SmallVector<int64_t, 8> basisCoeffs = 1558 llvm::to_vector<8>(basis.getRow(level)); 1559 basisCoeffs.push_back(0); 1560 1561 MaybeOptimum<int64_t> minRoundedUp, maxRoundedDown; 1562 std::tie(minRoundedUp, maxRoundedDown) = 1563 computeIntegerBounds(basisCoeffs); 1564 1565 // We don't have any integer values in the range. 1566 // Pop the stack and return up a level. 1567 if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) { 1568 assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) && 1569 "If one bound is empty, both should be."); 1570 snapshotStack.pop_back(); 1571 nextValueStack.pop_back(); 1572 upperBoundStack.pop_back(); 1573 level--; 1574 continue; 1575 } 1576 1577 // We already checked the empty case above. 1578 assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) && 1579 "Polyhedron should be bounded!"); 1580 1581 // Heuristic: if the sample point is integral at this point, just return 1582 // it. 1583 if (auto maybeSample = getSamplePointIfIntegral()) 1584 return *maybeSample; 1585 1586 if (*minRoundedUp < *maxRoundedDown) { 1587 reduceBasis(basis, level); 1588 basisCoeffs = llvm::to_vector<8>(basis.getRow(level)); 1589 basisCoeffs.push_back(0); 1590 std::tie(minRoundedUp, maxRoundedDown) = 1591 computeIntegerBounds(basisCoeffs); 1592 } 1593 1594 snapshotStack.push_back(getSnapshot()); 1595 // The smallest value in the range is the next value to try. 1596 // The values in the optionals are guaranteed to exist since we know the 1597 // polytope is bounded. 1598 nextValueStack.push_back(*minRoundedUp); 1599 upperBoundStack.push_back(*maxRoundedDown); 1600 } 1601 1602 assert((snapshotStack.size() - 1 == level && 1603 nextValueStack.size() - 1 == level && 1604 upperBoundStack.size() - 1 == level) && 1605 "Mismatched variable stack sizes!"); 1606 1607 // Whether we "recursed" or "returned" from a lower level, we rollback 1608 // to the snapshot of the starting state at this level. (in the "recursed" 1609 // case this has no effect) 1610 rollback(snapshotStack.back()); 1611 int64_t nextValue = nextValueStack.back(); 1612 nextValueStack.back()++; 1613 if (nextValue > upperBoundStack.back()) { 1614 // We have exhausted the range and found no solution. Pop the stack and 1615 // return up a level. 1616 snapshotStack.pop_back(); 1617 nextValueStack.pop_back(); 1618 upperBoundStack.pop_back(); 1619 level--; 1620 continue; 1621 } 1622 1623 // Try the next value in the range and "recurse" into the next level. 1624 SmallVector<int64_t, 8> basisCoeffs(basis.getRow(level).begin(), 1625 basis.getRow(level).end()); 1626 basisCoeffs.push_back(-nextValue); 1627 addEquality(basisCoeffs); 1628 level++; 1629 } 1630 1631 return {}; 1632 } 1633 1634 /// Compute the minimum and maximum integer values the expression can take. We 1635 /// compute each separately. 1636 std::pair<MaybeOptimum<int64_t>, MaybeOptimum<int64_t>> 1637 Simplex::computeIntegerBounds(ArrayRef<int64_t> coeffs) { 1638 MaybeOptimum<int64_t> minRoundedUp( 1639 computeOptimum(Simplex::Direction::Down, coeffs).map(ceil)); 1640 MaybeOptimum<int64_t> maxRoundedDown( 1641 computeOptimum(Simplex::Direction::Up, coeffs).map(floor)); 1642 return {minRoundedUp, maxRoundedDown}; 1643 } 1644 1645 void SimplexBase::print(raw_ostream &os) const { 1646 os << "rows = " << nRow << ", columns = " << nCol << "\n"; 1647 if (empty) 1648 os << "Simplex marked empty!\n"; 1649 os << "var: "; 1650 for (unsigned i = 0; i < var.size(); ++i) { 1651 if (i > 0) 1652 os << ", "; 1653 var[i].print(os); 1654 } 1655 os << "\ncon: "; 1656 for (unsigned i = 0; i < con.size(); ++i) { 1657 if (i > 0) 1658 os << ", "; 1659 con[i].print(os); 1660 } 1661 os << '\n'; 1662 for (unsigned row = 0; row < nRow; ++row) { 1663 if (row > 0) 1664 os << ", "; 1665 os << "r" << row << ": " << rowUnknown[row]; 1666 } 1667 os << '\n'; 1668 os << "c0: denom, c1: const"; 1669 for (unsigned col = 2; col < nCol; ++col) 1670 os << ", c" << col << ": " << colUnknown[col]; 1671 os << '\n'; 1672 for (unsigned row = 0; row < nRow; ++row) { 1673 for (unsigned col = 0; col < nCol; ++col) 1674 os << tableau(row, col) << '\t'; 1675 os << '\n'; 1676 } 1677 os << '\n'; 1678 } 1679 1680 void SimplexBase::dump() const { print(llvm::errs()); } 1681 1682 bool Simplex::isRationalSubsetOf(const IntegerRelation &rel) { 1683 if (isEmpty()) 1684 return true; 1685 1686 for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) 1687 if (findIneqType(rel.getInequality(i)) != IneqType::Redundant) 1688 return false; 1689 1690 for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) 1691 if (!isRedundantEquality(rel.getEquality(i))) 1692 return false; 1693 1694 return true; 1695 } 1696 1697 /// Returns the type of the inequality with coefficients `coeffs`. 1698 /// Possible types are: 1699 /// Redundant The inequality is satisfied by all points in the polytope 1700 /// Cut The inequality is satisfied by some points, but not by others 1701 /// Separate The inequality is not satisfied by any point 1702 /// 1703 /// Internally, this computes the minimum and the maximum the inequality with 1704 /// coefficients `coeffs` can take. If the minimum is >= 0, the inequality holds 1705 /// for all points in the polytope, so it is redundant. If the minimum is <= 0 1706 /// and the maximum is >= 0, the points in between the minimum and the 1707 /// inequality do not satisfy it, the points in between the inequality and the 1708 /// maximum satisfy it. Hence, it is a cut inequality. If both are < 0, no 1709 /// points of the polytope satisfy the inequality, which means it is a separate 1710 /// inequality. 1711 Simplex::IneqType Simplex::findIneqType(ArrayRef<int64_t> coeffs) { 1712 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 1713 if (minimum.isBounded() && *minimum >= Fraction(0, 1)) { 1714 return IneqType::Redundant; 1715 } 1716 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 1717 if ((!minimum.isBounded() || *minimum <= Fraction(0, 1)) && 1718 (!maximum.isBounded() || *maximum >= Fraction(0, 1))) { 1719 return IneqType::Cut; 1720 } 1721 return IneqType::Separate; 1722 } 1723 1724 /// Checks whether the type of the inequality with coefficients `coeffs` 1725 /// is Redundant. 1726 bool Simplex::isRedundantInequality(ArrayRef<int64_t> coeffs) { 1727 assert(!empty && 1728 "It is not meaningful to ask about redundancy in an empty set!"); 1729 return findIneqType(coeffs) == IneqType::Redundant; 1730 } 1731 1732 /// Check whether the equality given by `coeffs == 0` is redundant given 1733 /// the existing constraints. This is redundant when `coeffs` is already 1734 /// always zero under the existing constraints. `coeffs` is always zero 1735 /// when the minimum and maximum value that `coeffs` can take are both zero. 1736 bool Simplex::isRedundantEquality(ArrayRef<int64_t> coeffs) { 1737 assert(!empty && 1738 "It is not meaningful to ask about redundancy in an empty set!"); 1739 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 1740 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 1741 assert((!minimum.isEmpty() && !maximum.isEmpty()) && 1742 "Optima should be non-empty for a non-empty set"); 1743 return minimum.isBounded() && maximum.isBounded() && 1744 *maximum == Fraction(0, 1) && *minimum == Fraction(0, 1); 1745 } 1746