Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
primal_edge_norms.cc
Go to the documentation of this file.
1// Copyright 2010-2025 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
15
16#include <algorithm>
17#include <cstdlib>
18
19#include "absl/log/check.h"
22#include "ortools/glop/parameters.pb.h"
29#include "ortools/util/stats.h"
30
31namespace operations_research {
32namespace glop {
33
35 const VariablesInfo& variables_info,
36 const BasisFactorization& basis_factorization)
37 : compact_matrix_(compact_matrix),
38 variables_info_(variables_info),
39 basis_factorization_(basis_factorization),
40 stats_(),
41 recompute_edge_squared_norms_(true),
42 reset_devex_weights_(true),
43 edge_squared_norms_(),
44 matrix_column_norms_(),
45 devex_weights_(),
46 direction_left_inverse_(),
47 num_operations_(0) {}
48
50 SCOPED_TIME_STAT(&stats_);
51 matrix_column_norms_.clear();
52 recompute_edge_squared_norms_ = true;
53 reset_devex_weights_ = true;
54 for (bool* watcher : watchers_) *watcher = true;
55}
56
58 if (pricing_rule_ != GlopParameters ::STEEPEST_EDGE) return false;
59 return recompute_edge_squared_norms_;
60}
61
63 switch (pricing_rule_) {
64 case GlopParameters::DANTZIG:
66 case GlopParameters::STEEPEST_EDGE:
68 case GlopParameters::DEVEX:
69 return GetDevexWeights().const_view();
70 }
71}
72
74 if (recompute_edge_squared_norms_) ComputeEdgeSquaredNorms();
75 return edge_squared_norms_;
76}
77
79 if (reset_devex_weights_) ResetDevexWeights();
80 return devex_weights_;
81}
82
84 if (matrix_column_norms_.empty()) ComputeMatrixColumnNorms();
85 return matrix_column_norms_;
86}
87
89 ColIndex entering_col, const ScatteredColumn& direction) {
90 if (!recompute_edge_squared_norms_) {
91 SCOPED_TIME_STAT(&stats_);
92 // Recompute the squared norm of the edge used during this
93 // iteration, i.e. the entering edge.
94 const Fractional old_squared_norm = edge_squared_norms_[entering_col];
95 const Fractional precise_squared_norm = 1.0 + SquaredNorm(direction);
96 edge_squared_norms_[entering_col] = precise_squared_norm;
97
98 const Fractional precise_norm = sqrt(precise_squared_norm);
99 const Fractional estimated_edges_norm_accuracy =
100 (precise_norm - sqrt(old_squared_norm)) / precise_norm;
101 stats_.edges_norm_accuracy.Add(estimated_edges_norm_accuracy);
102 if (std::abs(estimated_edges_norm_accuracy) >
103 parameters_.recompute_edges_norm_threshold()) {
104 VLOG(1) << "Recomputing edge norms: " << sqrt(precise_squared_norm)
105 << " vs " << sqrt(old_squared_norm);
106 recompute_edge_squared_norms_ = true;
107 for (bool* watcher : watchers_) *watcher = true;
108 }
109
110 if (old_squared_norm < 0.25 * precise_squared_norm) {
111 VLOG(1) << "Imprecise norm, reprice. old=" << old_squared_norm
112 << " new=" << precise_squared_norm;
113 return false;
114 }
115 }
116 return true;
117}
118
120 ColIndex leaving_col,
121 RowIndex leaving_row,
122 const ScatteredColumn& direction,
123 UpdateRow* update_row) {
124 SCOPED_TIME_STAT(&stats_);
125 DCHECK_NE(entering_col, leaving_col);
126 if (!recompute_edge_squared_norms_) {
127 update_row->ComputeUpdateRow(leaving_row);
128 ComputeDirectionLeftInverse(entering_col, direction);
129 UpdateEdgeSquaredNorms(entering_col, leaving_col, leaving_row,
130 direction.values, *update_row);
131 }
132 if (!reset_devex_weights_) {
133 // Resets devex weights once in a while. If so, no need to update them
134 // before.
135 ++num_devex_updates_since_reset_;
136 if (num_devex_updates_since_reset_ >
137 parameters_.devex_weights_reset_period()) {
138 reset_devex_weights_ = true;
139 } else {
140 update_row->ComputeUpdateRow(leaving_row);
141 UpdateDevexWeights(entering_col, leaving_col, leaving_row,
142 direction.values, *update_row);
143 }
144 }
145}
146
147void PrimalEdgeNorms::ComputeMatrixColumnNorms() {
148 SCOPED_TIME_STAT(&stats_);
149 matrix_column_norms_.resize(compact_matrix_.num_cols(), 0.0);
150 for (ColIndex col(0); col < compact_matrix_.num_cols(); ++col) {
151 matrix_column_norms_[col] = SquaredNorm(compact_matrix_.column(col));
152 num_operations_ += compact_matrix_.column(col).num_entries().value();
153 }
154}
155
156void PrimalEdgeNorms::ComputeEdgeSquaredNorms() {
157 SCOPED_TIME_STAT(&stats_);
158
159 // time_limit_->LimitReached() can be costly sometimes, so we only do that
160 // if we feel this will be slow anyway.
161 const bool test_limit = (time_limit_ != nullptr) &&
162 basis_factorization_.NumberOfEntriesInLU() > 10'000;
163
164 // Since we will do a lot of inversions, it is better to be as efficient and
165 // precise as possible by refactorizing the basis.
166 DCHECK(basis_factorization_.IsRefactorized());
167 edge_squared_norms_.resize(compact_matrix_.num_cols(), 1.0);
168 for (const ColIndex col : variables_info_.GetIsRelevantBitRow()) {
169 // Note the +1.0 in the squared norm for the component of the edge on the
170 // 'entering_col'.
171 edge_squared_norms_[col] = 1.0 + basis_factorization_.RightSolveSquaredNorm(
172 compact_matrix_.column(col));
173
174 // This operation can be costly, and we abort if we are stuck here.
175 // Note that we still mark edges as "recomputed" otherwise we can runs into
176 // some DCHECK before we actually abort the solve.
177 if (test_limit && time_limit_->LimitReached()) break;
178 }
179
180 recompute_edge_squared_norms_ = false;
181}
182
183// TODO(user): It should be possible to reorganize the code and call this when
184// the value of direction is no longer needed. This will simplify the code and
185// avoid a copy here.
186void PrimalEdgeNorms::ComputeDirectionLeftInverse(
187 ColIndex entering_col, const ScatteredColumn& direction) {
188 SCOPED_TIME_STAT(&stats_);
189
190 // Initialize direction_left_inverse_ to direction. Note the special case when
191 // the non-zero vector is empty which means we don't know and need to use the
192 // dense version.
193 const ColIndex size = RowToColIndex(direction.values.size());
194 const double kThreshold = 0.05 * size.value();
195 if (!direction_left_inverse_.non_zeros.empty() &&
196 (direction_left_inverse_.non_zeros.size() + direction.non_zeros.size() <
197 2 * kThreshold)) {
198 ClearAndResizeVectorWithNonZeros(size, &direction_left_inverse_);
199 for (const auto e : direction) {
200 direction_left_inverse_[RowToColIndex(e.row())] = e.coefficient();
201 }
202 } else {
203 direction_left_inverse_.values = Transpose(direction.values);
204 direction_left_inverse_.non_zeros.clear();
205 }
206
207 if (direction.non_zeros.size() < kThreshold) {
208 direction_left_inverse_.non_zeros = TransposedView(direction).non_zeros;
209 }
210 basis_factorization_.LeftSolve(&direction_left_inverse_);
211
212 // TODO(user): Refactorize if estimated accuracy above a threshold.
213 IF_STATS_ENABLED(stats_.direction_left_inverse_accuracy.Add(
214 compact_matrix_.ColumnScalarProduct(entering_col,
215 direction_left_inverse_.values) -
216 SquaredNorm(direction.values)));
217 IF_STATS_ENABLED(stats_.direction_left_inverse_density.Add(
218 Density(direction_left_inverse_.values)));
219}
220
221// Let new_edge denote the edge of 'col' in the new basis. We want:
222// reduced_costs_[col] = ScalarProduct(new_edge, basic_objective_);
223// edge_squared_norms_[col] = SquaredNorm(new_edge);
224//
225// In order to compute this, we use the formulas:
226// new_leaving_edge = old_entering_edge / divisor.
227// new_edge = old_edge + update_coeff * new_leaving_edge.
228void PrimalEdgeNorms::UpdateEdgeSquaredNorms(ColIndex entering_col,
229 ColIndex leaving_col,
230 RowIndex leaving_row,
231 const DenseColumn& direction,
232 const UpdateRow& update_row) {
233 SCOPED_TIME_STAT(&stats_);
234
235 // 'pivot' is the value of the entering_edge at 'leaving_row'.
236 // The edge of the 'leaving_col' in the new basis is equal to
237 // entering_edge / 'pivot'.
238 const Fractional pivot = -direction[leaving_row];
239 DCHECK_NE(pivot, 0.0);
240
241 // Note that this should be precise because of the call to
242 // TestEnteringEdgeNormPrecision().
243 const Fractional entering_squared_norm = edge_squared_norms_[entering_col];
244 const Fractional leaving_squared_norm =
245 std::max(1.0, entering_squared_norm / Square(pivot));
246
247 int stat_lower_bounded_norms = 0;
248 const Fractional factor = 2.0 / pivot;
249 const auto view = compact_matrix_.view();
250 auto output = edge_squared_norms_.view();
251 const auto direction_left_inverse =
252 direction_left_inverse_.values.const_view();
253 for (const ColIndex col : update_row.GetNonZeroPositions()) {
254 const Fractional coeff = update_row.GetCoefficient(col);
255 const Fractional scalar_product =
256 view.ColumnScalarProduct(col, direction_left_inverse);
257 num_operations_ += view.ColumnNumEntries(col).value();
258
259 // Update the edge squared norm of this column. Note that the update
260 // formula used is important to maximize the precision. See an explanation
261 // in the dual context in Koberstein's PhD thesis, section 8.2.2.1.
262 output[col] +=
263 coeff * (coeff * leaving_squared_norm + factor * scalar_product);
264
265 // Make sure it doesn't go under a known lower bound (TODO(user): ref?).
266 // This way norms are always >= 1.0 .
267 // TODO(user): precompute 1 / Square(pivot) or 1 / pivot? it will be
268 // slightly faster, but may introduce numerical issues. More generally,
269 // this test is only needed in a few cases, so is it worth it?
270 const Fractional lower_bound = 1.0 + Square(coeff / pivot);
271 if (output[col] < lower_bound) {
272 output[col] = lower_bound;
273 ++stat_lower_bounded_norms;
274 }
275 }
276 output[leaving_col] = leaving_squared_norm;
277 stats_.lower_bounded_norms.Add(stat_lower_bounded_norms);
278}
279
280void PrimalEdgeNorms::UpdateDevexWeights(
281 ColIndex entering_col /* index q in the paper */,
282 ColIndex leaving_col /* index p in the paper */, RowIndex leaving_row,
283 const DenseColumn& direction, const UpdateRow& update_row) {
284 SCOPED_TIME_STAT(&stats_);
285
286 // Compared to steepest edge update, the DEVEX weight uses the largest of the
287 // norms of two vectors to approximate the norm of the sum.
288 const Fractional entering_norm = sqrt(PreciseSquaredNorm(direction));
289 const Fractional pivot_magnitude = std::abs(direction[leaving_row]);
290 const Fractional leaving_norm =
291 std::max(1.0, entering_norm / pivot_magnitude);
292 for (const ColIndex col : update_row.GetNonZeroPositions()) {
293 const Fractional coeff = update_row.GetCoefficient(col);
294 const Fractional update_vector_norm = std::abs(coeff) * leaving_norm;
295 devex_weights_[col] =
296 std::max(devex_weights_[col], Square(update_vector_norm));
297 }
298 devex_weights_[leaving_col] = Square(leaving_norm);
299}
300
301void PrimalEdgeNorms::ResetDevexWeights() {
302 SCOPED_TIME_STAT(&stats_);
303 if (parameters_.initialize_devex_with_column_norms()) {
304 devex_weights_ = GetMatrixColumnNorms();
305 } else {
306 devex_weights_.assign(compact_matrix_.num_cols(), 1.0);
307 }
308 num_devex_updates_since_reset_ = 0;
309 reset_devex_weights_ = false;
310}
311
312} // namespace glop
313} // namespace operations_research
bool IsRefactorized() const
Returns true if the factorization was just recomputed.
Fractional RightSolveSquaredNorm(const ColumnView &a) const
ColumnView column(ColIndex col) const
Definition sparse.h:420
void UpdateBeforeBasisPivot(ColIndex entering_col, ColIndex leaving_col, RowIndex leaving_row, const ScatteredColumn &direction, UpdateRow *update_row)
bool TestEnteringEdgeNormPrecision(ColIndex entering_col, const ScatteredColumn &direction)
PrimalEdgeNorms(const CompactSparseMatrix &compact_matrix, const VariablesInfo &variables_info, const BasisFactorization &basis_factorization)
StrictITISpan< ColIndex, const Fractional > ConstView
Definition lp_types.h:291
void ComputeUpdateRow(RowIndex leaving_row)
Definition update_row.cc:87
const DenseBitRow & GetIsRelevantBitRow() const
double Density(const DenseRow &row)
Definition lp_utils.cc:176
Fractional Square(Fractional f)
Definition lp_utils.h:41
const DenseRow & Transpose(const DenseColumn &col)
Similar comment as the other Transpose() implementation above.
Definition lp_utils.h:199
ColIndex RowToColIndex(RowIndex row)
Get the ColIndex corresponding to the column # row.
Definition lp_types.h:54
void ClearAndResizeVectorWithNonZeros(IndexType size, ScatteredRowOrCol *v)
Sets a dense vector for which the non zeros are known to be non_zeros.
Definition lp_utils.h:290
Fractional PreciseSquaredNorm(const SparseColumn &v)
Definition lp_utils.cc:44
Fractional SquaredNorm(const SparseColumn &v)
Definition lp_utils.cc:36
StrictITIVector< RowIndex, Fractional > DenseColumn
Column-vector types. Column-vector types are indexed by a row index.
Definition lp_types.h:380
StrictITIVector< ColIndex, Fractional > DenseRow
Row-vector types. Row-vector types are indexed by a column index.
Definition lp_types.h:351
const ScatteredRow & TransposedView(const ScatteredColumn &c)
In SWIG mode, we don't want anything besides these top-level includes.
#define IF_STATS_ENABLED(instructions)
Definition stats.h:417
#define SCOPED_TIME_STAT(stats)
Definition stats.h:418
StrictITIVector< Index, Fractional > values