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