Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
markowitz.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// LU decomposition algorithm of a sparse matrix B with Markowitz pivot
15// selection strategy. The algorithm constructs a lower matrix L, upper matrix
16// U, row permutation P and a column permutation Q such that L.U = P.B.Q^{-1}.
17//
18// The current algorithm is a mix of ideas that can be found in the literature
19// and of some optimizations tailored for its use in a revised simplex algorithm
20// (like a fast processing of the singleton columns present in B). It constructs
21// L and U column by column from left to right.
22//
23// A key concept is the one of the residual matrix which is the bottom right
24// square submatrix that still needs to be factorized during the classical
25// Gaussian elimination. The algorithm maintains the non-zero pattern of its
26// rows and its row/column degrees.
27//
28// At each step, a number of columns equal to 'markowitz_zlatev_parameter' are
29// chosen as candidates from the residual matrix. They are the ones with minimal
30// residual column degree. They can be found easily because the columns of the
31// residual matrix are kept in a priority queue.
32//
33// We compute the numerical value of these residual columns like in a
34// left-looking algorithm by solving a sparse lower-triangular system with the
35// current L constructed so far. Note that this step is highly optimized for
36// sparsity and we reuse the computations done in the previous steps (if the
37// candidate column was already considered before). As a by-product, we also
38// get the corresponding column of U.
39//
40// Among the entries of these columns, a pivot is chosen such that the product:
41// (num_column_entries - 1) * (num_row_entries - 1)
42// is minimized. Only the pivots with a magnitude greater than
43// 'lu_factorization_pivot_threshold' times the maximum magnitude of the
44// corresponding residual column are considered for stability reasons.
45//
46// Once the pivot is chosen, the residual column divided by the pivot becomes a
47// column of L, and the non-zero pattern of the new residual submatrix is
48// updated by subtracting the outer product of this pivot column times the pivot
49// row. The product minimized above is thus an upper bound of the number of
50// fill-in created during a step.
51//
52// References:
53//
54// J. R. Gilbert and T. Peierls, "Sparse partial pivoting in time proportional
55// to arithmetic operations," SIAM J. Sci. Statist. Comput., 9 (1988): 862-874.
56//
57// I.S. Duff, A.M. Erisman and J.K. Reid, "Direct Methods for Sparse Matrices",
58// Clarendon, Oxford, UK, 1987, ISBN 0-19-853421-3,
59// http://www.amazon.com/dp/0198534213
60//
61// T.A. Davis, "Direct methods for Sparse Linear Systems", SIAM, Philadelphia,
62// 2006, ISBN-13: 978-0-898716-13, http://www.amazon.com/dp/0898716136
63//
64// TODO(user): Determine whether any of these would bring any benefit:
65// - S.C. Eisenstat and J.W.H. Liu, "The theory of elimination trees for
66// sparse unsymmetric matrices," SIAM J. Matrix Anal. Appl., 26:686-705,
67// January 2005
68// - S.C. Eisenstat and J.W.H. Liu. "Algorithmic aspects of elimination trees
69// for sparse unsymmetric matrices," SIAM J. Matrix Anal. Appl.,
70// 29:1363-1381, January 2008.
71// - http://perso.ens-lyon.fr/~bucar/papers/kauc.pdf
72
73#ifndef OR_TOOLS_GLOP_MARKOWITZ_H_
74#define OR_TOOLS_GLOP_MARKOWITZ_H_
75
76#include <cstdint>
77#include <queue>
78#include <string>
79#include <vector>
80
81#include "absl/container/inlined_vector.h"
84#include "ortools/glop/parameters.pb.h"
85#include "ortools/glop/status.h"
90#include "ortools/util/stats.h"
91
92namespace operations_research {
93namespace glop {
94
95// Holds the non-zero positions (by row) and column/row degree of the residual
96// matrix during the Gaussian elimination.
97//
98// During each step of Gaussian elimination, a row and a column will be
99// "removed" from the residual matrix. Note however that the row and column
100// indices of the non-removed part do not change, so the residual matrix at a
101// given step will only correspond to a subset of the initial indices.
103 public:
105
106 // This type is neither copyable nor movable.
109
110 // Releases the memory used by this class.
111 void Clear();
112
113 // Resets the pattern to the one of an empty square matrix of the given size.
114 void Reset(RowIndex num_rows, ColIndex num_cols);
115
116 // Resets the pattern to the one of the given matrix but only for the
117 // rows/columns whose given permutation is kInvalidRow or kInvalidCol.
118 // This also fills the singleton columns/rows with the corresponding entries.
120 const RowPermutation& row_perm,
121 const ColumnPermutation& col_perm,
122 std::vector<ColIndex>* singleton_columns,
123 std::vector<RowIndex>* singleton_rows);
124
125 // Adds a non-zero entry to the matrix. There should be no duplicates.
126 void AddEntry(RowIndex row, ColIndex col);
127
128 // Marks the given pivot row and column as deleted.
129 // This is called at each step of the Gaussian elimination on the pivot.
130 void DeleteRowAndColumn(RowIndex pivot_row, ColIndex pivot_col);
131
132 // Decreases the degree of a row/column. This is the basic operation used to
133 // keep the correct degree after a call to DeleteRowAndColumn(). This is
134 // because row_non_zero_[row] is only lazily cleaned.
135 int32_t DecreaseRowDegree(RowIndex row);
136 int32_t DecreaseColDegree(ColIndex col);
137
138 // Returns true if the column has been deleted by DeleteRowAndColumn().
139 bool IsColumnDeleted(ColIndex col) const;
140
141 // Removes from the corresponding row_non_zero_[row] the columns that have
142 // been previously deleted by DeleteRowAndColumn().
143 void RemoveDeletedColumnsFromRow(RowIndex row);
144
145 // Returns the first non-deleted column index from this row or kInvalidCol if
146 // none can be found.
147 ColIndex GetFirstNonDeletedColumnFromRow(RowIndex row) const;
148
149 // Performs a generic Gaussian update of the residual matrix:
150 // - DeleteRowAndColumn() must already have been called.
151 // - The non-zero pattern is augmented (set union) by the one of the
152 // outer product of the pivot column and row.
153 //
154 // Important: as a small optimization, this function does not call
155 // DecreaseRowDegree() on the row in the pivot column. This has to be done by
156 // the client.
157 void Update(RowIndex pivot_row, ColIndex pivot_col,
158 const SparseColumn& column);
159
160 // Returns the degree (i.e. the number of non-zeros) of the given column.
161 // This is only valid for the column indices still in the residual matrix.
162 int32_t ColDegree(ColIndex col) const {
163 DCHECK(!deleted_columns_[col]);
164 return col_degree_[col];
165 }
166
167 // Returns the degree (i.e. the number of non-zeros) of the given row.
168 // This is only valid for the row indices still in the residual matrix.
169 int32_t RowDegree(RowIndex row) const { return row_degree_[row]; }
170
171 // Returns the set of non-zeros of the given row (unsorted).
172 // Call RemoveDeletedColumnsFromRow(row) to clean the row first.
173 // This is only valid for the row indices still in the residual matrix.
174 const absl::InlinedVector<ColIndex, 6>& RowNonZero(RowIndex row) const {
175 return row_non_zero_[row];
176 }
177
178 private:
179 // Augments the non-zero pattern of the given row by taking its union with the
180 // non-zero pattern of the given pivot_row.
181 void MergeInto(RowIndex pivot_row, RowIndex row);
182
183 // Different version of MergeInto() that works only if the non-zeros position
184 // of each row are sorted in increasing order. The output will also be sorted.
185 //
186 // TODO(user): This is currently not used but about the same speed as the
187 // non-sorted version. Investigate more.
188 void MergeIntoSorted(RowIndex pivot_row, RowIndex row);
189
190 // Using InlinedVector helps because we usually have many rows with just a few
191 // non-zeros. Note that on a 64 bits computer we get exactly 6 inlined int32_t
192 // elements without extra space, and the size of the inlined vector is 4 times
193 // 64 bits.
194 //
195 // TODO(user): We could be even more efficient since a size of int32_t is
196 // enough for us and we could store in common the inlined/not-inlined size.
198 row_non_zero_;
201 DenseBooleanRow deleted_columns_;
202 DenseBooleanRow bool_scratchpad_;
203 std::vector<ColIndex> col_scratchpad_;
204 ColIndex num_non_deleted_columns_;
205};
206
207// Adjustable priority queue of columns. Pop() returns a column with the
208// smallest degree first (degree = number of entries in the column).
209// Empty columns (i.e. with degree 0) are not stored in the queue.
211 public:
213
214 // This type is neither copyable nor movable.
217
218 // Releases the memory used by this class.
219 void Clear();
220
221 // Clears the queue and prepares it to store up to num_cols column indices
222 // with a degree from 1 to max_degree included.
223 void Reset(int32_t max_degree, ColIndex num_cols);
224
225 // Changes the degree of a column and make sure it is in the queue. The degree
226 // must be non-negative (>= 0) and at most equal to the value of num_cols used
227 // in Reset(). A degree of zero will remove the column from the queue.
228 void PushOrAdjust(ColIndex col, int32_t degree);
229
230 // Removes the column index with higher priority from the queue and returns
231 // it. Returns kInvalidCol if the queue is empty.
232 ColIndex Pop();
233
234 private:
237 std::vector<std::vector<ColIndex>> col_by_degree_;
238 int32_t min_degree_;
239};
240
241// Contains a set of columns indexed by ColIndex. This is like a SparseMatrix
242// but this class is optimized for the case where only a small subset of columns
243// is needed at the same time (like it is the case in our LU algorithm). It
244// reuses the memory of the columns that are no longer needed.
246 public:
248
249 // This type is neither copyable nor movable.
254
255 // Resets the repository to num_cols empty columns.
256 void Reset(ColIndex num_cols);
257
258 // Returns the column with given index.
259 const SparseColumn& column(ColIndex col) const;
260
261 // Gets the mutable column with given column index. The returned vector
262 // address is only valid until the next call to mutable_column().
264
265 // Clears the column with given index and releases its memory to the common
266 // memory pool that is used to create new mutable_column() on demand.
267 void ClearAndReleaseColumn(ColIndex col);
268
269 // Reverts this class to its initial state. This releases the memory of the
270 // columns that were used but not the memory of this class member (this should
271 // be fine).
272 void Clear();
273
274 private:
275 // mutable_column(col) is stored in columns_[mapping_[col]].
276 // The columns_ that can be reused have their index stored in free_columns_.
277 const SparseColumn empty_column_;
279 std::vector<int> free_columns_;
280 std::vector<SparseColumn> columns_;
281};
282
283// The class that computes either the actual L.U decomposition, or the
284// permutation P and Q such that P.B.Q^{-1} will have a sparse L.U
285// decomposition.
287 public:
288 Markowitz() = default;
289
290 // This type is neither copyable nor movable.
291 Markowitz(const Markowitz&) = delete;
292 Markowitz& operator=(const Markowitz&) = delete;
293
294 // Computes the full factorization with P, Q, L and U.
295 //
296 // If the matrix is singular, the returned status will indicate it and the
297 // permutation (col_perm) will contain a maximum non-singular set of columns
298 // of the matrix. Moreover, by adding singleton columns with a one at the rows
299 // such that 'row_perm[row] == kInvalidRow', then the matrix will be
300 // non-singular.
301 ABSL_MUST_USE_RESULT Status
302 ComputeLU(const CompactSparseMatrixView& basis_matrix,
303 RowPermutation* row_perm, ColumnPermutation* col_perm,
305
306 // Only computes P and Q^{-1}, L and U can be computed later from these
307 // permutations using another algorithm (for instance left-looking L.U). This
308 // may be faster than computing the full L and U at the same time but the
309 // current implementation is not optimized for this.
310 //
311 // It behaves the same as ComputeLU() for singular matrices.
312 //
313 // This function also works with a non-square matrix. It will return a set of
314 // independent columns of maximum size. If all the given columns are
315 // independent, the returned Status will be OK.
316 ABSL_MUST_USE_RESULT Status ComputeRowAndColumnPermutation(
317 const CompactSparseMatrixView& basis_matrix, RowPermutation* row_perm,
318 ColumnPermutation* col_perm);
319
320 // Releases the memory used by this class.
321 void Clear();
322
323 // Returns an estimate of the time spent in the last factorization.
325
326 // Returns a string containing the statistics for this class.
327 std::string StatString() const { return stats_.StatString(); }
328
329 // Sets the current parameters.
330 void SetParameters(const GlopParameters& parameters) {
331 parameters_ = parameters;
332 }
333
334 private:
335 // Statistics about this class.
336 struct Stats : public StatsGroup {
337 Stats()
338 : StatsGroup("Markowitz"),
339 basis_singleton_column_ratio("basis_singleton_column_ratio", this),
340 basis_residual_singleton_column_ratio(
341 "basis_residual_singleton_column_ratio", this),
342 pivots_without_fill_in_ratio("pivots_without_fill_in_ratio", this),
343 degree_two_pivot_columns("degree_two_pivot_columns", this) {}
344 RatioDistribution basis_singleton_column_ratio;
345 RatioDistribution basis_residual_singleton_column_ratio;
346 RatioDistribution pivots_without_fill_in_ratio;
347 RatioDistribution degree_two_pivot_columns;
348 };
349 Stats stats_;
350
351 // Fast track for singleton columns of the matrix. Fills a part of the row and
352 // column permutation that move these columns in order to form an identity
353 // sub-matrix on the upper left.
354 //
355 // Note(user): Linear programming bases usually have a reasonable percentage
356 // of slack columns in them, so this gives a big speedup.
357 void ExtractSingletonColumns(const CompactSparseMatrixView& basis_matrix,
358 RowPermutation* row_perm,
359 ColumnPermutation* col_perm, int* index);
360
361 // Fast track for columns that form a triangular matrix. This does not find
362 // all of them, but because the column are ordered in the same way they were
363 // ordered at the end of the previous factorization, this is likely to find
364 // quite a few.
365 //
366 // The main gain here is that it avoids taking these columns into account in
367 // InitializeResidualMatrix() and later in RemoveRowFromResidualMatrix().
368 void ExtractResidualSingletonColumns(
369 const CompactSparseMatrixView& basis_matrix, RowPermutation* row_perm,
370 ColumnPermutation* col_perm, int* index);
371
372 // Helper function for determining if a column is a residual singleton column.
373 // If it is, RowIndex* row contains the index of the single residual edge.
374 bool IsResidualSingletonColumn(const ColumnView& column,
375 const RowPermutation& row_perm, RowIndex* row);
376
377 // Returns the column of the current residual matrix with an index 'col' in
378 // the initial matrix. We compute it by solving a linear system with the
379 // current lower_ and the last computed column 'col' of a previous residual
380 // matrix. This uses the same algorithm as a left-looking factorization (see
381 // lu_factorization.h for more details).
382 const SparseColumn& ComputeColumn(const RowPermutation& row_perm,
383 ColIndex col);
384
385 // Finds an entry in the residual matrix with a low Markowitz score and a high
386 // enough magnitude. Returns its Markowitz score and updates the given
387 // pointers.
388 //
389 // We use the strategy of Zlatev, "On some pivotal strategies in Gaussian
390 // elimination by sparse technique" (1980). SIAM J. Numer. Anal. 17 18-30. It
391 // consists of looking for the best pivot in only a few columns (usually 3
392 // or 4) amongst the ones which have the lowest number of entries.
393 //
394 // Amongst the pivots with a minimum Markowitz number, we choose the one
395 // with highest magnitude. This doesn't apply to pivots with a 0 Markowitz
396 // number because all such pivots will have to be taken at some point anyway.
397 int64_t FindPivot(const RowPermutation& row_perm,
398 const ColumnPermutation& col_perm, RowIndex* pivot_row,
399 ColIndex* pivot_col, Fractional* pivot_coefficient);
400
401 // Updates the degree of a given column in the internal structure of the
402 // class.
403 void UpdateDegree(ColIndex col, int degree);
404
405 // Removes all the coefficients in the residual matrix that are on the given
406 // row or column. In both cases, the pivot row or column is ignored.
407 void RemoveRowFromResidualMatrix(RowIndex pivot_row, ColIndex pivot_col);
408 void RemoveColumnFromResidualMatrix(RowIndex pivot_row, ColIndex pivot_col);
409
410 // Updates the residual matrix given the pivot position. This is needed if the
411 // pivot row and pivot column both have more than one entry. Otherwise, the
412 // residual matrix can be updated more efficiently by calling one of the
413 // Remove...() functions above.
414 void UpdateResidualMatrix(RowIndex pivot_row, ColIndex pivot_col);
415
416 // Pointer to the matrix to factorize.
417 CompactSparseMatrixView const* basis_matrix_;
418
419 // These matrices are transformed during the algorithm into the final L and U
420 // matrices modulo some row and column permutations. Note that the columns of
421 // these matrices stay in the initial order.
422 SparseMatrixWithReusableColumnMemory permuted_lower_;
423 SparseMatrixWithReusableColumnMemory permuted_upper_;
424
425 // These matrices will hold the final L and U. The are created columns by
426 // columns from left to right, and at the end, their rows are permuted by
427 // ComputeLU() to become triangular.
428 TriangularMatrix lower_;
429 TriangularMatrix upper_;
430
431 // The columns of permuted_lower_ for which we do need a call to
432 // PermutedLowerSparseSolve(). This speeds up ComputeColumn().
433 DenseBooleanRow permuted_lower_column_needs_solve_;
434
435 // Contains the non-zero positions of the current residual matrix (the
436 // lower-right square matrix that gets smaller by one row and column at each
437 // Gaussian elimination step).
438 MatrixNonZeroPattern residual_matrix_non_zero_;
439
440 // Data structure to access the columns by increasing degree.
441 ColumnPriorityQueue col_by_degree_;
442
443 // True as long as only singleton columns of the residual matrix are used.
444 bool contains_only_singleton_columns_;
445
446 // Boolean used to know when col_by_degree_ become useful.
447 bool is_col_by_degree_initialized_;
448
449 // FindPivot() needs to look at the first entries of col_by_degree_, it
450 // temporary put them here before pushing them back to col_by_degree_.
451 std::vector<ColIndex> examined_col_;
452
453 // Singleton column indices are kept here rather than in col_by_degree_ to
454 // optimize the algorithm: as long as this or singleton_row_ are not empty,
455 // col_by_degree_ do not need to be initialized nor updated.
456 std::vector<ColIndex> singleton_column_;
457
458 // List of singleton row indices.
459 std::vector<RowIndex> singleton_row_;
460
461 // Proto holding all the parameters of this algorithm.
462 GlopParameters parameters_;
463
464 // Number of floating point operations of the last factorization.
465 int64_t num_fp_operations_;
466};
467
468} // namespace glop
469} // namespace operations_research
470
471#endif // OR_TOOLS_GLOP_MARKOWITZ_H_
Statistic on the distribution of a sequence of ratios, displayed as %.
Definition stats.h:265
Base class to print a nice summary of a group of statistics.
Definition stats.h:128
std::string StatString() const
Definition stats.cc:77
void Clear()
Releases the memory used by this class.
Definition markowitz.cc:813
ColumnPriorityQueue(const ColumnPriorityQueue &)=delete
This type is neither copyable nor movable.
void PushOrAdjust(ColIndex col, int32_t degree)
Definition markowitz.cc:827
ColumnPriorityQueue & operator=(const ColumnPriorityQueue &)=delete
void Reset(int32_t max_degree, ColIndex num_cols)
Definition markowitz.cc:819
Markowitz & operator=(const Markowitz &)=delete
void Clear()
Releases the memory used by this class.
Definition markowitz.cc:173
std::string StatString() const
Returns a string containing the statistics for this class.
Definition markowitz.h:327
ABSL_MUST_USE_RESULT Status ComputeRowAndColumnPermutation(const CompactSparseMatrixView &basis_matrix, RowPermutation *row_perm, ColumnPermutation *col_perm)
Definition markowitz.cc:31
double DeterministicTimeOfLastFactorization() const
Returns an estimate of the time spent in the last factorization.
Definition markowitz.cc:557
ABSL_MUST_USE_RESULT Status ComputeLU(const CompactSparseMatrixView &basis_matrix, RowPermutation *row_perm, ColumnPermutation *col_perm, TriangularMatrix *lower, TriangularMatrix *upper)
Definition markowitz.cc:153
Markowitz(const Markowitz &)=delete
This type is neither copyable nor movable.
void SetParameters(const GlopParameters &parameters)
Sets the current parameters.
Definition markowitz.h:330
void AddEntry(RowIndex row, ColIndex col)
Adds a non-zero entry to the matrix. There should be no duplicates.
Definition markowitz.cc:632
bool IsColumnDeleted(ColIndex col) const
Returns true if the column has been deleted by DeleteRowAndColumn().
Definition markowitz.cc:656
MatrixNonZeroPattern(const MatrixNonZeroPattern &)=delete
This type is neither copyable nor movable.
ColIndex GetFirstNonDeletedColumnFromRow(RowIndex row) const
Definition markowitz.cc:674
const absl::InlinedVector< ColIndex, 6 > & RowNonZero(RowIndex row) const
Definition markowitz.h:174
MatrixNonZeroPattern & operator=(const MatrixNonZeroPattern &)=delete
void Reset(RowIndex num_rows, ColIndex num_cols)
Resets the pattern to the one of an empty square matrix of the given size.
Definition markowitz.cc:570
void DeleteRowAndColumn(RowIndex pivot_row, ColIndex pivot_col)
Definition markowitz.cc:646
void Update(RowIndex pivot_row, ColIndex pivot_col, const SparseColumn &column)
Definition markowitz.cc:682
void InitializeFromMatrixSubset(const CompactSparseMatrixView &basis_matrix, const RowPermutation &row_perm, const ColumnPermutation &col_perm, std::vector< ColIndex > *singleton_columns, std::vector< RowIndex > *singleton_rows)
Definition markowitz.cc:580
void Clear()
Releases the memory used by this class.
Definition markowitz.cc:561
SparseMatrixWithReusableColumnMemory(const SparseMatrixWithReusableColumnMemory &)=delete
This type is neither copyable nor movable.
void Reset(ColIndex num_cols)
Resets the repository to num_cols empty columns.
Definition markowitz.cc:868
SparseMatrixWithReusableColumnMemory & operator=(const SparseMatrixWithReusableColumnMemory &)=delete
SatParameters parameters
double lower
double upper
int index
ColIndex col
Definition markowitz.cc:187
RowIndex row
Definition markowitz.cc:186
Permutation< ColIndex > ColumnPermutation
Definition permutation.h:97
Permutation< RowIndex > RowPermutation
Definition permutation.h:96
StrictITIVector< ColIndex, bool > DenseBooleanRow
Row of booleans.
Definition lp_types.h:356
In SWIG mode, we don't want anything besides these top-level includes.
util_intops::StrongVector< ColumnEntryIndex, ElementIndex, ElementAllocator > SparseColumn
int column