MLIR 22.0.0git
Matrix.cpp
Go to the documentation of this file.
1//===- Matrix.cpp - MLIR Matrix 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
12#include "llvm/Support/MathExtras.h"
13#include "llvm/Support/raw_ostream.h"
14#include <algorithm>
15#include <cassert>
16#include <utility>
17
18using namespace mlir;
19using namespace presburger;
20
21template <typename T>
22Matrix<T>::Matrix(unsigned rows, unsigned columns, unsigned reservedRows,
23 unsigned reservedColumns)
24 : nRows(rows), nColumns(columns),
25 nReservedColumns(std::max(nColumns, reservedColumns)),
27 data.reserve(std::max(nRows, reservedRows) * nReservedColumns);
28}
29
30/// We cannot use the default implementation of operator== as it compares
31/// fields like `reservedColumns` etc., which are not part of the data.
32template <typename T>
33bool Matrix<T>::operator==(const Matrix<T> &m) const {
34 if (nRows != m.getNumRows())
35 return false;
36 if (nColumns != m.getNumColumns())
37 return false;
38
39 for (unsigned i = 0; i < nRows; i++)
40 if (getRow(i) != m.getRow(i))
41 return false;
42
43 return true;
44}
45
46template <typename T>
47Matrix<T> Matrix<T>::identity(unsigned dimension) {
48 Matrix matrix(dimension, dimension);
49 for (unsigned i = 0; i < dimension; ++i)
50 matrix(i, i) = 1;
51 return matrix;
52}
53
54template <typename T>
56 return data.capacity() / nReservedColumns;
57}
58
59template <typename T>
60void Matrix<T>::reserveRows(unsigned rows) {
61 data.reserve(rows * nReservedColumns);
62}
63
64template <typename T>
67 return nRows - 1;
68}
69
70template <typename T>
72 assert(elems.size() == nColumns && "elems must match row length!");
73 unsigned row = appendExtraRow();
74 for (unsigned col = 0; col < nColumns; ++col)
75 at(row, col) = elems[col];
76 return row;
77}
79template <typename T>
82 for (unsigned row = 0; row < nRows; ++row)
83 for (unsigned col = 0; col < nColumns; ++col)
84 transp(col, row) = at(row, col);
85
86 return transp;
87}
88
89template <typename T>
90void Matrix<T>::resizeHorizontally(unsigned newNColumns) {
91 if (newNColumns < nColumns)
92 removeColumns(newNColumns, nColumns - newNColumns);
93 if (newNColumns > nColumns)
94 insertColumns(nColumns, newNColumns - nColumns);
95}
96
97template <typename T>
98void Matrix<T>::resize(unsigned newNRows, unsigned newNColumns) {
99 resizeHorizontally(newNColumns);
101}
102
103template <typename T>
104void Matrix<T>::resizeVertically(unsigned newNRows) {
105 nRows = newNRows;
106 data.resize(nRows * nReservedColumns);
107}
108
109template <typename T>
110void Matrix<T>::swapRows(unsigned row, unsigned otherRow) {
111 assert((row < getNumRows() && otherRow < getNumRows()) &&
112 "Given row out of bounds");
113 if (row == otherRow)
114 return;
115 for (unsigned col = 0; col < nColumns; col++)
116 std::swap(at(row, col), at(otherRow, col));
119template <typename T>
120void Matrix<T>::swapColumns(unsigned column, unsigned otherColumn) {
121 assert((column < getNumColumns() && otherColumn < getNumColumns()) &&
122 "Given column out of bounds");
123 if (column == otherColumn)
124 return;
125 for (unsigned row = 0; row < nRows; row++)
126 std::swap(at(row, column), at(row, otherColumn));
127}
128
129template <typename T>
131 return {&data[row * nReservedColumns], nColumns};
132}
134template <typename T>
135ArrayRef<T> Matrix<T>::getRow(unsigned row) const {
136 return {&data[row * nReservedColumns], nColumns};
137}
139template <typename T>
140void Matrix<T>::setRow(unsigned row, ArrayRef<T> elems) {
141 assert(elems.size() == getNumColumns() &&
142 "elems size must match row length!");
143 for (unsigned i = 0, e = getNumColumns(); i < e; ++i)
144 at(row, i) = elems[i];
145}
146
147template <typename T>
148void Matrix<T>::insertColumn(unsigned pos) {
149 insertColumns(pos, 1);
151template <typename T>
152void Matrix<T>::insertColumns(unsigned pos, unsigned count) {
153 if (count == 0)
154 return;
155 assert(pos <= nColumns);
156 unsigned oldNReservedColumns = nReservedColumns;
157 if (nColumns + count > nReservedColumns) {
158 nReservedColumns = llvm::NextPowerOf2(nColumns + count);
159 data.resize(nRows * nReservedColumns);
160 }
161 nColumns += count;
162
163 for (int ri = nRows - 1; ri >= 0; --ri) {
164 for (int ci = nReservedColumns - 1; ci >= 0; --ci) {
165 unsigned r = ri;
166 unsigned c = ci;
167 T &dest = data[r * nReservedColumns + c];
168 if (c >= nColumns) { // NOLINT
169 // Out of bounds columns are zero-initialized. NOLINT because clang-tidy
170 // complains about this branch being the same as the c >= pos one.
171 //
172 // TODO: this case can be skipped if the number of reserved columns
173 // didn't change.
174 dest = 0;
175 } else if (c >= pos + count) {
176 // Shift the data occuring after the inserted columns.
177 dest = data[r * oldNReservedColumns + c - count];
178 } else if (c >= pos) {
179 // The inserted columns are also zero-initialized.
180 dest = 0;
181 } else {
182 // The columns before the inserted columns stay at the same (row, col)
183 // but this corresponds to a different location in the linearized array
184 // if the number of reserved columns changed.
185 if (nReservedColumns == oldNReservedColumns)
186 break;
187 dest = data[r * oldNReservedColumns + c];
188 }
190 }
191}
192
193template <typename T>
194void Matrix<T>::removeColumn(unsigned pos) {
196}
197template <typename T>
198void Matrix<T>::removeColumns(unsigned pos, unsigned count) {
199 if (count == 0)
200 return;
201 assert(pos + count - 1 < nColumns);
202 for (unsigned r = 0; r < nRows; ++r) {
203 for (unsigned c = pos; c < nColumns - count; ++c)
204 at(r, c) = at(r, c + count);
205 for (unsigned c = nColumns - count; c < nColumns; ++c)
206 at(r, c) = 0;
207 }
208 nColumns -= count;
209}
210
211template <typename T>
212void Matrix<T>::insertRow(unsigned pos) {
213 insertRows(pos, 1);
214}
215template <typename T>
216void Matrix<T>::insertRows(unsigned pos, unsigned count) {
217 if (count == 0)
218 return;
219
220 assert(pos <= nRows);
221 resizeVertically(nRows + count);
222 for (int r = nRows - 1; r >= int(pos + count); --r)
223 copyRow(r - count, r);
224 for (int r = pos + count - 1; r >= int(pos); --r)
225 for (unsigned c = 0; c < nColumns; ++c)
226 at(r, c) = 0;
227}
228
229template <typename T>
230void Matrix<T>::removeRow(unsigned pos) {
231 removeRows(pos, 1);
232}
233template <typename T>
234void Matrix<T>::removeRows(unsigned pos, unsigned count) {
235 if (count == 0)
236 return;
237 assert(pos + count - 1 <= nRows);
238 for (unsigned r = pos; r + count < nRows; ++r)
239 copyRow(r + count, r);
240 resizeVertically(nRows - count);
241}
242
243template <typename T>
244void Matrix<T>::copyRow(unsigned sourceRow, unsigned targetRow) {
245 if (sourceRow == targetRow)
246 return;
247 for (unsigned c = 0; c < nColumns; ++c)
248 at(targetRow, c) = at(sourceRow, c);
249}
250
251template <typename T>
252void Matrix<T>::fillRow(unsigned row, const T &value) {
253 for (unsigned col = 0; col < nColumns; ++col)
254 at(row, col) = value;
255}
256
257// moveColumns is implemented by moving the columns adjacent to the source range
258// to their final position.
259template <typename T>
260void Matrix<T>::moveColumns(unsigned srcPos, unsigned num, unsigned dstPos) {
261 if (num == 0)
262 return;
263
264 if (dstPos == srcPos)
265 return;
266
267 assert(srcPos + num <= getNumColumns() &&
268 "move source range exceeds matrix columns");
269 assert(dstPos + num <= getNumColumns() &&
270 "move destination range exceeds matrix columns");
271
272 unsigned numRows = getNumRows();
273 // std::rotate(start, middle, end) permutes the elements of [start, end] to
274 // [middle, end) + [start, middle). NOTE: &at(i, srcPos + num) will trigger an
275 // assert.
276 if (dstPos > srcPos) {
277 for (unsigned i = 0; i < numRows; ++i) {
278 std::rotate(&at(i, srcPos), &at(i, srcPos) + num, &at(i, dstPos) + num);
279 }
280 return;
281 }
282 for (unsigned i = 0; i < numRows; ++i) {
283 std::rotate(&at(i, dstPos), &at(i, srcPos), &at(i, srcPos) + num);
284 }
285}
286
287template <typename T>
288void Matrix<T>::addToRow(unsigned sourceRow, unsigned targetRow,
289 const T &scale) {
290 addToRow(targetRow, getRow(sourceRow), scale);
291}
292
293template <typename T>
294void Matrix<T>::addToRow(unsigned row, ArrayRef<T> rowVec, const T &scale) {
295 if (scale == 0)
296 return;
297 for (unsigned col = 0; col < nColumns; ++col)
298 at(row, col) += scale * rowVec[col];
299}
300
301template <typename T>
302void Matrix<T>::scaleRow(unsigned row, const T &scale) {
303 for (unsigned col = 0; col < nColumns; ++col)
304 at(row, col) *= scale;
305}
306
307template <typename T>
308void Matrix<T>::addToColumn(unsigned sourceColumn, unsigned targetColumn,
309 const T &scale) {
310 if (scale == 0)
311 return;
312 for (unsigned row = 0, e = getNumRows(); row < e; ++row)
313 at(row, targetColumn) += scale * at(row, sourceColumn);
314}
315
316template <typename T>
317void Matrix<T>::negateColumn(unsigned column) {
318 for (unsigned row = 0, e = getNumRows(); row < e; ++row)
319 at(row, column) = -at(row, column);
320}
321
322template <typename T>
323void Matrix<T>::negateRow(unsigned row) {
324 for (unsigned column = 0, e = getNumColumns(); column < e; ++column)
325 at(row, column) = -at(row, column);
326}
327
328template <typename T>
330 for (unsigned row = 0; row < nRows; ++row)
331 negateRow(row);
332}
333
334template <typename T>
336 assert(rowVec.size() == getNumRows() && "Invalid row vector dimension!");
337
339 for (unsigned col = 0, e = getNumColumns(); col < e; ++col)
340 for (unsigned i = 0, e = getNumRows(); i < e; ++i)
341 result[col] += rowVec[i] * at(i, col);
342 return result;
343}
344
345template <typename T>
347 assert(getNumColumns() == colVec.size() &&
348 "Invalid column vector dimension!");
349
351 for (unsigned row = 0, e = getNumRows(); row < e; row++)
352 for (unsigned i = 0, e = getNumColumns(); i < e; i++)
353 result[row] += at(row, i) * colVec[i];
354 return result;
355}
356
357/// Set M(row, targetCol) to its remainder on division by M(row, sourceCol)
358/// by subtracting from column targetCol an appropriate integer multiple of
359/// sourceCol. This brings M(row, targetCol) to the range [0, M(row,
360/// sourceCol)). Apply the same column operation to otherMatrix, with the same
361/// integer multiple.
363 unsigned sourceCol, unsigned targetCol,
364 Matrix<DynamicAPInt> &otherMatrix) {
365 assert(m(row, sourceCol) != 0 && "Cannot divide by zero!");
366 assert(m(row, sourceCol) > 0 && "Source must be positive!");
367 DynamicAPInt ratio = -floorDiv(m(row, targetCol), m(row, sourceCol));
368 m.addToColumn(sourceCol, targetCol, ratio);
369 otherMatrix.addToColumn(sourceCol, targetCol, ratio);
370}
371
372template <typename T>
373Matrix<T> Matrix<T>::getSubMatrix(unsigned fromRow, unsigned toRow,
374 unsigned fromColumn,
375 unsigned toColumn) const {
376 assert(fromRow <= toRow && "end of row range must be after beginning!");
377 assert(toRow < nRows && "end of row range out of bounds!");
378 assert(fromColumn <= toColumn &&
379 "end of column range must be after beginning!");
380 assert(toColumn < nColumns && "end of column range out of bounds!");
381 Matrix<T> subMatrix(toRow - fromRow + 1, toColumn - fromColumn + 1);
382 for (unsigned i = fromRow; i <= toRow; ++i)
383 for (unsigned j = fromColumn; j <= toColumn; ++j)
384 subMatrix(i - fromRow, j - fromColumn) = at(i, j);
385 return subMatrix;
386}
387
388template <typename T>
390 PrintTableMetrics ptm = {0, 0, "-"};
391 for (unsigned row = 0; row < nRows; ++row)
392 for (unsigned column = 0; column < nColumns; ++column)
393 updatePrintMetrics<T>(at(row, column), ptm);
394 unsigned minSpacing = 1;
395 for (unsigned row = 0; row < nRows; ++row) {
396 for (unsigned column = 0; column < nColumns; ++column) {
397 printWithPrintMetrics<T>(os, at(row, column), minSpacing, ptm);
398 }
399 os << "\n";
400 }
401}
402
403/// We iterate over the `indicator` bitset, checking each bit. If a bit is 1,
404/// we append it to one matrix, and if it is zero, we append it to the other.
405template <typename T>
406std::pair<Matrix<T>, Matrix<T>>
408 Matrix<T> rowsForOne(0, nColumns), rowsForZero(0, nColumns);
409 for (unsigned i = 0; i < nRows; i++) {
410 if (indicator[i] == 1)
411 rowsForOne.appendExtraRow(getRow(i));
412 else
413 rowsForZero.appendExtraRow(getRow(i));
414 }
415 return {rowsForOne, rowsForZero};
416}
417
418template <typename T>
419void Matrix<T>::dump() const {
420 print(llvm::errs());
421}
422
423template <typename T>
425 if (data.size() != nRows * nReservedColumns)
426 return false;
428 return false;
429#ifdef EXPENSIVE_CHECKS
430 for (unsigned r = 0; r < nRows; ++r)
431 for (unsigned c = nColumns; c < nReservedColumns; ++c)
432 if (data[r * nReservedColumns + c] != 0)
433 return false;
434#endif
435 return true;
436}
437
438namespace mlir {
439namespace presburger {
440template class Matrix<DynamicAPInt>;
441template class Matrix<Fraction>;
442} // namespace presburger
443} // namespace mlir
444
445IntMatrix IntMatrix::identity(unsigned dimension) {
446 IntMatrix matrix(dimension, dimension);
447 for (unsigned i = 0; i < dimension; ++i)
448 matrix(i, i) = 1;
449 return matrix;
450}
451
452std::pair<IntMatrix, IntMatrix> IntMatrix::computeHermiteNormalForm() const {
453 // We start with u as an identity matrix and perform operations on h until h
454 // is in hermite normal form. We apply the same sequence of operations on u to
455 // obtain a transform that takes h to hermite normal form.
456 IntMatrix h = *this;
458
459 unsigned echelonCol = 0;
460 // Invariant: in all rows above row, all columns from echelonCol onwards
461 // are all zero elements. In an iteration, if the curent row has any non-zero
462 // elements echelonCol onwards, we bring one to echelonCol and use it to
463 // make all elements echelonCol + 1 onwards zero.
464 for (unsigned row = 0; row < h.getNumRows(); ++row) {
465 // Search row for a non-empty entry, starting at echelonCol.
466 unsigned nonZeroCol = echelonCol;
467 for (unsigned e = h.getNumColumns(); nonZeroCol < e; ++nonZeroCol) {
468 if (h(row, nonZeroCol) == 0)
469 continue;
470 break;
471 }
472
473 // Continue to the next row with the same echelonCol if this row is all
474 // zeros from echelonCol onwards.
475 if (nonZeroCol == h.getNumColumns())
476 continue;
477
478 // Bring the non-zero column to echelonCol. This doesn't affect rows
479 // above since they are all zero at these columns.
480 if (nonZeroCol != echelonCol) {
481 h.swapColumns(nonZeroCol, echelonCol);
482 u.swapColumns(nonZeroCol, echelonCol);
483 }
484
485 // Make h(row, echelonCol) non-negative.
486 if (h(row, echelonCol) < 0) {
487 h.negateColumn(echelonCol);
488 u.negateColumn(echelonCol);
489 }
490
491 // Make all the entries in row after echelonCol zero.
492 for (unsigned i = echelonCol + 1, e = h.getNumColumns(); i < e; ++i) {
493 // We make h(row, i) non-negative, and then apply the Euclidean GCD
494 // algorithm to (row, i) and (row, echelonCol). At the end, one of them
495 // has value equal to the gcd of the two entries, and the other is zero.
496
497 if (h(row, i) < 0) {
498 h.negateColumn(i);
499 u.negateColumn(i);
500 }
501
502 unsigned targetCol = i, sourceCol = echelonCol;
503 // At every step, we set h(row, targetCol) %= h(row, sourceCol), and
504 // swap the indices sourceCol and targetCol. (not the columns themselves)
505 // This modulo is implemented as a subtraction
506 // h(row, targetCol) -= quotient * h(row, sourceCol),
507 // where quotient = floor(h(row, targetCol) / h(row, sourceCol)),
508 // which brings h(row, targetCol) to the range [0, h(row, sourceCol)).
509 //
510 // We are only allowed column operations; we perform the above
511 // for every row, i.e., the above subtraction is done as a column
512 // operation. This does not affect any rows above us since they are
513 // guaranteed to be zero at these columns.
514 while (h(row, targetCol) != 0 && h(row, sourceCol) != 0) {
515 modEntryColumnOperation(h, row, sourceCol, targetCol, u);
516 std::swap(targetCol, sourceCol);
517 }
518
519 // One of (row, echelonCol) and (row, i) is zero and the other is the gcd.
520 // Make it so that (row, echelonCol) holds the non-zero value.
521 if (h(row, echelonCol) == 0) {
522 h.swapColumns(i, echelonCol);
523 u.swapColumns(i, echelonCol);
524 }
525 }
526
527 // Make all entries before echelonCol non-negative and strictly smaller
528 // than the pivot entry.
529 for (unsigned i = 0; i < echelonCol; ++i)
530 modEntryColumnOperation(h, row, echelonCol, i, u);
531
532 ++echelonCol;
533 }
534
535 return {h, u};
536}
537
538DynamicAPInt IntMatrix::normalizeRow(unsigned row, unsigned cols) {
539 return normalizeRange(getRow(row).slice(0, cols));
540}
541
542DynamicAPInt IntMatrix::normalizeRow(unsigned row) {
543 return normalizeRow(row, getNumColumns());
544}
545
546DynamicAPInt IntMatrix::determinant(IntMatrix *inverse) const {
547 assert(nRows == nColumns &&
548 "determinant can only be calculated for square matrices!");
549
550 FracMatrix m(*this);
551
552 FracMatrix fracInverse(nRows, nColumns);
553 DynamicAPInt detM = m.determinant(&fracInverse).getAsInteger();
554
555 if (detM == 0)
556 return DynamicAPInt(0);
557
558 if (!inverse)
559 return detM;
560
561 *inverse = IntMatrix(nRows, nColumns);
562 for (unsigned i = 0; i < nRows; i++)
563 for (unsigned j = 0; j < nColumns; j++)
564 inverse->at(i, j) = (fracInverse.at(i, j) * detM).getAsInteger();
565
566 return detM;
567}
568
569FracMatrix FracMatrix::identity(unsigned dimension) {
570 return Matrix::identity(dimension);
571}
572
575 for (unsigned i = 0, r = m.getNumRows(); i < r; i++)
576 for (unsigned j = 0, c = m.getNumColumns(); j < c; j++)
577 this->at(i, j) = m.at(i, j);
578}
579
581 assert(nRows == nColumns &&
582 "determinant can only be calculated for square matrices!");
583
584 FracMatrix m(*this);
585 FracMatrix tempInv(nRows, nColumns);
586 if (inverse)
587 tempInv = FracMatrix::identity(nRows);
588
589 Fraction a, b;
590 // Make the matrix into upper triangular form using
591 // gaussian elimination with row operations.
592 // If inverse is required, we apply more operations
593 // to turn the matrix into diagonal form. We apply
594 // the same operations to the inverse matrix,
595 // which is initially identity.
596 // Either way, the product of the diagonal elements
597 // is then the determinant.
598 for (unsigned i = 0; i < nRows; i++) {
599 if (m(i, i) == 0)
600 // First ensure that the diagonal
601 // element is nonzero, by swapping
602 // it with a nonzero row.
603 for (unsigned j = i + 1; j < nRows; j++) {
604 if (m(j, i) != 0) {
605 m.swapRows(j, i);
606 if (inverse)
607 tempInv.swapRows(j, i);
608 break;
609 }
610 }
611
612 b = m.at(i, i);
613 if (b == 0)
614 return 0;
615
616 // Set all elements above the
617 // diagonal to zero.
618 if (inverse) {
619 for (unsigned j = 0; j < i; j++) {
620 if (m.at(j, i) == 0)
621 continue;
622 a = m.at(j, i);
623 // Set element (j, i) to zero
624 // by subtracting the ith row,
625 // appropriately scaled.
626 m.addToRow(i, j, -a / b);
627 tempInv.addToRow(i, j, -a / b);
628 }
629 }
630
631 // Set all elements below the
632 // diagonal to zero.
633 for (unsigned j = i + 1; j < nRows; j++) {
634 if (m.at(j, i) == 0)
635 continue;
636 a = m.at(j, i);
637 // Set element (j, i) to zero
638 // by subtracting the ith row,
639 // appropriately scaled.
640 m.addToRow(i, j, -a / b);
641 if (inverse)
642 tempInv.addToRow(i, j, -a / b);
643 }
644 }
645
646 // Now only diagonal elements of m are nonzero, but they are
647 // not necessarily 1. To get the true inverse, we should
648 // normalize them and apply the same scale to the inverse matrix.
649 // For efficiency we skip scaling m and just scale tempInv appropriately.
650 if (inverse) {
651 for (unsigned i = 0; i < nRows; i++)
652 for (unsigned j = 0; j < nRows; j++)
653 tempInv.at(i, j) = tempInv.at(i, j) / m(i, i);
654
655 *inverse = std::move(tempInv);
656 }
657
659 for (unsigned i = 0; i < nRows; i++)
660 determinant *= m.at(i, i);
661
662 return determinant;
663}
664
666 // Create a copy of the argument to store
667 // the orthogonalised version.
668 FracMatrix orth(*this);
669
670 // For each vector (row) in the matrix, subtract its unit
671 // projection along each of the previous vectors.
672 // This ensures that it has no component in the direction
673 // of any of the previous vectors.
674 for (unsigned i = 1, e = getNumRows(); i < e; i++) {
675 for (unsigned j = 0; j < i; j++) {
676 Fraction jNormSquared = dotProduct(orth.getRow(j), orth.getRow(j));
677 assert(jNormSquared != 0 && "some row became zero! Inputs to this "
678 "function must be linearly independent.");
679 Fraction projectionScale =
680 dotProduct(orth.getRow(i), orth.getRow(j)) / jNormSquared;
681 orth.addToRow(j, i, -projectionScale);
682 }
683 }
684 return orth;
685}
686
687// Convert the matrix, interpreted (row-wise) as a basis
688// to an LLL-reduced basis.
689//
690// This is an implementation of the algorithm described in
691// "Factoring polynomials with rational coefficients" by
692// A. K. Lenstra, H. W. Lenstra Jr., L. Lovasz.
693//
694// Let {b_1, ..., b_n} be the current basis and
695// {b_1*, ..., b_n*} be the Gram-Schmidt orthogonalised
696// basis (unnormalized).
697// Define the Gram-Schmidt coefficients μ_ij as
698// (b_i • b_j*) / (b_j* • b_j*), where (•) represents the inner product.
699//
700// We iterate starting from the second row to the last row.
701//
702// For the kth row, we first check μ_kj for all rows j < k.
703// We subtract b_j (scaled by the integer nearest to μ_kj)
704// from b_k.
705//
706// Now, we update k.
707// If b_k and b_{k-1} satisfy the Lovasz condition
708// |b_k|^2 ≥ (δ - μ_k{k-1}^2) |b_{k-1}|^2,
709// we are done and we increment k.
710// Otherwise, we swap b_k and b_{k-1} and decrement k.
711//
712// We repeat this until k = n and return.
713void FracMatrix::LLL(const Fraction &delta) {
714 DynamicAPInt nearest;
715 Fraction mu;
716
717 // `gsOrth` holds the Gram-Schmidt orthogonalisation
718 // of the matrix at all times. It is recomputed every
719 // time the matrix is modified during the algorithm.
720 // This is naive and can be optimised.
721 FracMatrix gsOrth = gramSchmidt();
722
723 // We start from the second row.
724 unsigned k = 1;
725 while (k < getNumRows()) {
726 for (unsigned j = k - 1; j < k; j--) {
727 // Compute the Gram-Schmidt coefficient μ_jk.
728 mu = dotProduct(getRow(k), gsOrth.getRow(j)) /
729 dotProduct(gsOrth.getRow(j), gsOrth.getRow(j));
730 nearest = round(mu);
731 // Subtract b_j scaled by the integer nearest to μ_jk from b_k.
732 addToRow(k, getRow(j), -Fraction(nearest, 1));
733 gsOrth = gramSchmidt(); // Update orthogonalization.
734 }
735 mu = dotProduct(getRow(k), gsOrth.getRow(k - 1)) /
736 dotProduct(gsOrth.getRow(k - 1), gsOrth.getRow(k - 1));
737 // Check the Lovasz condition for b_k and b_{k-1}.
738 if (dotProduct(gsOrth.getRow(k), gsOrth.getRow(k)) >
739 (delta - mu * mu) *
740 dotProduct(gsOrth.getRow(k - 1), gsOrth.getRow(k - 1))) {
741 // If it is satisfied, proceed to the next k.
742 k += 1;
743 } else {
744 // If it is not satisfied, decrement k (without
745 // going beyond the second row).
746 swapRows(k, k - 1);
747 gsOrth = gramSchmidt(); // Update orthogonalization.
748 k = k > 1 ? k - 1 : 1;
749 }
750 }
751}
752
754 unsigned numRows = getNumRows();
755 unsigned numColumns = getNumColumns();
756 IntMatrix normalized(numRows, numColumns);
757
758 DynamicAPInt lcmDenoms = DynamicAPInt(1);
759 for (unsigned i = 0; i < numRows; i++) {
760 // For a row, first compute the LCM of the denominators.
761 for (unsigned j = 0; j < numColumns; j++)
762 lcmDenoms = lcm(lcmDenoms, at(i, j).den);
763 // Then, multiply by it throughout and convert to integers.
764 for (unsigned j = 0; j < numColumns; j++)
765 normalized(i, j) = (at(i, j) * lcmDenoms).getAsInteger();
766 }
767 return normalized;
768}
for(Operation *op :ops)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static void modEntryColumnOperation(Matrix< DynamicAPInt > &m, unsigned row, unsigned sourceCol, unsigned targetCol, Matrix< DynamicAPInt > &otherMatrix)
Set M(row, targetCol) to its remainder on division by M(row, sourceCol) by subtracting from column ta...
Definition Matrix.cpp:362
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
FracMatrix gramSchmidt() const
Definition Matrix.cpp:665
IntMatrix normalizeRows() const
Definition Matrix.cpp:753
static FracMatrix identity(unsigned dimension)
Return the identity matrix of the specified dimension.
Definition Matrix.cpp:569
FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows=0, unsigned reservedColumns=0)
Definition Matrix.h:298
Fraction determinant(FracMatrix *inverse=nullptr) const
Definition Matrix.cpp:580
void LLL(const Fraction &delta)
Definition Matrix.cpp:713
static IntMatrix identity(unsigned dimension)
Return the identity matrix of the specified dimension.
Definition Matrix.cpp:445
std::pair< IntMatrix, IntMatrix > computeHermiteNormalForm() const
Given the current matrix M, returns the matrices H, U such that H is the column hermite normal form o...
Definition Matrix.cpp:452
DynamicAPInt determinant(IntMatrix *inverse=nullptr) const
Definition Matrix.cpp:546
IntMatrix(unsigned rows, unsigned columns, unsigned reservedRows=0, unsigned reservedColumns=0)
Definition Matrix.h:256
DynamicAPInt normalizeRow(unsigned row, unsigned nCols)
Divide the first nCols of the specified row by their GCD.
Definition Matrix.cpp:538
This is a class to represent a resizable matrix.
Definition Matrix.h:42
void moveColumns(unsigned srcPos, unsigned num, unsigned dstPos)
Move the columns in the source range [srcPos, srcPos + num) to the specified destination [dstPos,...
Definition Matrix.cpp:260
bool hasConsistentState() const
Return whether the Matrix is in a consistent state with all its invariants satisfied.
Definition Matrix.cpp:424
void insertRows(unsigned pos, unsigned count)
Definition Matrix.cpp:216
unsigned getNumRows() const
Definition Matrix.h:86
void swapColumns(unsigned column, unsigned otherColumn)
Swap the given columns.
Definition Matrix.cpp:120
unsigned nRows
The current number of rows, columns, and reserved columns.
Definition Matrix.h:241
void removeColumn(unsigned pos)
Definition Matrix.cpp:194
unsigned appendExtraRow()
Add an extra row at the bottom of the matrix and return its position.
Definition Matrix.cpp:65
unsigned nReservedColumns
Definition Matrix.h:241
void addToColumn(unsigned sourceColumn, unsigned targetColumn, const T &scale)
Add scale multiples of the source column to the target column.
Definition Matrix.cpp:308
Matrix< T > getSubMatrix(unsigned fromRow, unsigned toRow, unsigned fromColumn, unsigned toColumn) const
Definition Matrix.cpp:373
void print(raw_ostream &os) const
Print the matrix.
Definition Matrix.cpp:389
void copyRow(unsigned sourceRow, unsigned targetRow)
Definition Matrix.cpp:244
void scaleRow(unsigned row, const T &scale)
Multiply the specified row by a factor of scale.
Definition Matrix.cpp:302
void insertColumn(unsigned pos)
Definition Matrix.cpp:148
MutableArrayRef< T > getRow(unsigned row)
Get a [Mutable]ArrayRef corresponding to the specified row.
Definition Matrix.cpp:130
void removeColumns(unsigned pos, unsigned count)
Definition Matrix.cpp:198
void insertColumns(unsigned pos, unsigned count)
Definition Matrix.cpp:152
void setRow(unsigned row, ArrayRef< T > elems)
Set the specified row to elems.
Definition Matrix.cpp:140
std::pair< Matrix< T >, Matrix< T > > splitByBitset(ArrayRef< int > indicator)
Split the rows of a matrix into two matrices according to which bits are 1 and which are 0 in a given...
Definition Matrix.cpp:407
void removeRow(unsigned pos)
Definition Matrix.cpp:230
bool operator==(const Matrix< T > &m) const
We cannot use the default implementation of operator== as it compares fields like reservedColumns etc...
Definition Matrix.cpp:33
SmallVector< T, 16 > data
Stores the data.
Definition Matrix.h:245
unsigned getNumColumns() const
Definition Matrix.h:88
T & at(unsigned row, unsigned column)
Access the element at the specified row and column.
Definition Matrix.h:62
void resizeVertically(unsigned newNRows)
Definition Matrix.cpp:104
unsigned getNumReservedRows() const
Return the maximum number of rows/columns that can be added without incurring a reallocation.
Definition Matrix.cpp:55
Matrix< T > transpose() const
Definition Matrix.cpp:80
SmallVector< T, 8 > preMultiplyWithRow(ArrayRef< T > rowVec) const
The given vector is interpreted as a row vector v.
Definition Matrix.cpp:335
static Matrix identity(unsigned dimension)
Return the identity matrix of the specified dimension.
Definition Matrix.cpp:47
void insertRow(unsigned pos)
Definition Matrix.cpp:212
SmallVector< T, 8 > postMultiplyWithColumn(ArrayRef< T > colVec) const
The given vector is interpreted as a column vector v.
Definition Matrix.cpp:346
void negateMatrix()
Negate the entire matrix.
Definition Matrix.cpp:329
void swapRows(unsigned row, unsigned otherRow)
Swap the given rows.
Definition Matrix.cpp:110
void resizeHorizontally(unsigned newNColumns)
Definition Matrix.cpp:90
void reserveRows(unsigned rows)
Reserve enough space to resize to the specified number of rows without reallocations.
Definition Matrix.cpp:60
void negateColumn(unsigned column)
Negate the specified column.
Definition Matrix.cpp:317
void resize(unsigned newNRows, unsigned newNColumns)
Resize the matrix to the specified dimensions.
Definition Matrix.cpp:98
void fillRow(unsigned row, const T &value)
Definition Matrix.cpp:252
void addToRow(unsigned sourceRow, unsigned targetRow, const T &scale)
Add scale multiples of the source row to the target row.
Definition Matrix.cpp:288
void negateRow(unsigned row)
Negate the specified row.
Definition Matrix.cpp:323
void removeRows(unsigned pos, unsigned count)
Remove the rows having positions pos, pos + 1, ... pos + count - 1.
Definition Matrix.cpp:234
DynamicAPInt round(const Fraction &f)
Definition Fraction.h:136
Fraction dotProduct(ArrayRef< Fraction > a, ArrayRef< Fraction > b)
Compute the dot product of two vectors.
Definition Utils.cpp:534
void printWithPrintMetrics(raw_ostream &os, T val, unsigned minSpacing, const PrintTableMetrics &m)
Print val in the table with metrics specified in 'm'.
Definition Utils.h:328
void updatePrintMetrics(T val, PrintTableMetrics &m)
Iterate over each val in the table and update 'm' where .maxPreIndent and .maxPostIndent are initiali...
Definition Utils.h:314
DynamicAPInt normalizeRange(MutableArrayRef< DynamicAPInt > range)
Divide the range by its gcd and return the gcd.
Definition Utils.cpp:350
Include the generated interface declarations.
A class to represent fractions.
Definition Fraction.h:29
DynamicAPInt getAsInteger() const
Definition Fraction.h:51
Example usage: Print .12, 3.4, 56.7 preAlign = ".", minSpacing = 1, .12 .12 3.4 3....
Definition Utils.h:303
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.