Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
linear_constraint_manager.h
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
14#ifndef OR_TOOLS_SAT_LINEAR_CONSTRAINT_MANAGER_H_
15#define OR_TOOLS_SAT_LINEAR_CONSTRAINT_MANAGER_H_
16
17#include <cstddef>
18#include <cstdint>
19#include <string>
20#include <vector>
21
22#include "absl/container/btree_map.h"
23#include "absl/container/flat_hash_map.h"
24#include "absl/strings/string_view.h"
25#include "absl/types/span.h"
29#include "ortools/sat/integer.h"
32#include "ortools/sat/model.h"
33#include "ortools/sat/sat_parameters.pb.h"
35#include "ortools/sat/util.h"
38
39namespace operations_research {
40namespace sat {
41
42// Stores for each IntegerVariable its temporary LP solution.
43//
44// This is shared between all LinearProgrammingConstraint because in the corner
45// case where we have many different LinearProgrammingConstraint and a lot of
46// variable, we could theoretically use up a quadratic amount of memory
47// otherwise.
49 : public util_intops::StrongVector<IntegerVariable, double> {
50 ModelLpValues() = default;
51};
52
53// Same as ModelLpValues for reduced costs.
55 : public util_intops::StrongVector<IntegerVariable, double> {
56 ModelReducedCosts() = default;
57};
58
59// Stores the mapping integer_variable -> glop::ColIndex.
60// This is shared across all LP, which is fine since there are disjoint.
62 : public util_intops::StrongVector<IntegerVariable, glop::ColIndex> {
64};
65
66// Knowing the symmetry of the IP problem should allow us to
67// solve the LP faster via "folding" techniques.
68//
69// You can read this for the LP part: "Dimension Reduction via Colour
70// Refinement", Martin Grohe, Kristian Kersting, Martin Mladenov, Erkal
71// Selman, https://arxiv.org/abs/1307.5697
72//
73// In the presence of symmetry, by considering all symmetric version of a
74// constraint and summing them, we can derive a new constraint using the sum
75// of the variable on each orbit instead of the individual variables.
76//
77// For the integration in a MIP solver, I couldn't find many reference. The way
78// I did it here is to introduce for each orbit a variable representing the
79// sum of the orbit variable. This allows to represent the folded LP in terms
80// of these variables (that are connected to the rest of the solver) and just
81// reuse the full machinery.
82//
83// There are related info in "Orbital Shrinking", Matteo Fischetti & Leo
84// Liberti, https://link.springer.com/chapter/10.1007/978-3-642-32147-4_6
86 public:
88 : shared_stats_(model->GetOrCreate<SharedStatistics>()),
89 integer_trail_(model->GetOrCreate<IntegerTrail>()) {}
91
92 // This must be called with all orbits before we call FoldLinearConstraint().
93 // Note that sum_var MUST not be in any of the orbits. All orbits must also be
94 // disjoint.
95 //
96 // Precondition: All IntegerVariable must be positive.
97 void AddSymmetryOrbit(IntegerVariable sum_var,
98 absl::Span<const IntegerVariable> orbit);
99
100 // If there are no symmetry, we shouldn't bother calling the functions below.
101 // Note that they will still work, but be no-op.
102 bool HasSymmetry() const { return has_symmetry_; }
103
104 // Accessors by orbit index in [0, num_orbits).
105 int NumOrbits() const { return orbits_.size(); }
106 IntegerVariable OrbitSumVar(int i) const { return orbit_sum_vars_[i]; }
107 absl::Span<const IntegerVariable> Orbit(int i) const { return orbits_[i]; }
108
109 // Returns the orbit number in [0, num_orbits) if var belong to a non-trivial
110 // orbit or if it is a "orbit_sum_var". Returns -1 otherwise.
111 int OrbitIndex(IntegerVariable var) const;
112
113 // Returns true iff var is one of the sum_var passed to AddSymmetryOrbit().
114 bool IsOrbitSumVar(IntegerVariable var) const;
115
116 // This will be only true for variable not appearing in any orbit and for
117 // the orbit sum variables.
118 bool AppearInFoldedProblem(IntegerVariable var) const;
119
120 // Given a constraint on the "original" model variables, try to construct a
121 // symmetric version of it using the orbit sum variables. This might fail if
122 // we encounter integer overflow. Returns true on success. On failure, the
123 // original constraints will not be usable.
124 //
125 // Preconditions: All IntegerVariable must be positive. And the constraint
126 // lb/ub must be tight and not +/- int64_t max.
127 bool FoldLinearConstraint(LinearConstraint* ct, bool* folded = nullptr);
128
129 private:
130 SharedStatistics* shared_stats_;
131 IntegerTrail* integer_trail_;
132
133 bool has_symmetry_ = false;
134 int64_t num_overflows_ = 0;
136
137 // We index our vector by positive variable only.
139
140 // Orbit info index by number in [0, num_orbits);
141 std::vector<IntegerVariable> orbit_sum_vars_;
143};
144
145// This class holds a list of globally valid linear constraints and has some
146// logic to decide which one should be part of the LP relaxation. We want more
147// for a better relaxation, but for efficiency we do not want to have too much
148// constraints while solving the LP.
149//
150// This class is meant to contain all the initial constraints of the LP
151// relaxation and to get new cuts as they are generated. Thus, it can both
152// manage cuts but also only add the initial constraints lazily if there is too
153// many of them.
155 public:
157 // Note that this constraint always contains "tight" lb/ub, some of these
158 // bound might be trivial level zero bounds, and one can know this by
159 // looking at lb_is_trivial/ub_is_trivial.
161
162 double l2_norm = 0.0;
164 size_t hash;
165
166 // Updated only for deletable constraints. This is incremented every time
167 // ChangeLp() is called and the constraint is active in the LP or not in the
168 // LP and violated.
169 double active_count = 0.0;
170
171 // TODO(user): This is the number of time the constraint was consecutively
172 // inactive, and go up to 100 with the default param, so we could optimize
173 // the space used more.
174 uint16_t inactive_count = 0;
175
176 // TODO(user): Pack bool and in general optimize the memory of this class.
178 bool is_in_lp = false;
179 bool ub_is_trivial = false;
180 bool lb_is_trivial = false;
181
182 // For now, we mark all the generated cuts as deletable and the problem
183 // constraints as undeletable.
184 // TODO(user): We can have a better heuristics. Some generated good cuts
185 // can be marked undeletable and some unused problem specified constraints
186 // can be marked deletable.
187 bool is_deletable = false;
188 };
189
191 : sat_parameters_(*model->GetOrCreate<SatParameters>()),
192 integer_trail_(*model->GetOrCreate<IntegerTrail>()),
193 time_limit_(model->GetOrCreate<TimeLimit>()),
194 expanded_lp_solution_(*model->GetOrCreate<ModelLpValues>()),
195 expanded_reduced_costs_(*model->GetOrCreate<ModelReducedCosts>()),
196 model_(model),
197 symmetrizer_(model->GetOrCreate<LinearConstraintSymmetrizer>()) {}
199
200 // Add a new constraint to the manager. Note that we canonicalize constraints
201 // and merge the bounds of constraints with the same terms. We also perform
202 // basic preprocessing. If added is given, it will be set to true if this
203 // constraint was actually a new one and to false if it was dominated by an
204 // already existing one.
205 DEFINE_STRONG_INDEX_TYPE(ConstraintIndex);
206 ConstraintIndex Add(LinearConstraint ct, bool* added = nullptr,
207 bool* folded = nullptr);
208
209 // Same as Add(), but logs some information about the newly added constraint.
210 // Cuts are also handled slightly differently than normal constraints.
211 //
212 // Returns true if a new cut was added and false if this cut is not
213 // efficacious or if it is a duplicate of an already existing one.
214 bool AddCut(LinearConstraint ct, std::string type_name,
215 std::string extra_info = "");
216
217 // These must be level zero bounds.
218 bool UpdateConstraintLb(glop::RowIndex index_in_lp, IntegerValue new_lb);
219 bool UpdateConstraintUb(glop::RowIndex index_in_lp, IntegerValue new_ub);
220
221 // The objective is used as one of the criterion to score cuts.
222 // The more a cut is parallel to the objective, the better its score is.
223 //
224 // Currently this should only be called once per IntegerVariable (Checked). It
225 // is easy to support dynamic modification if it becomes needed.
226 void SetObjectiveCoefficient(IntegerVariable var, IntegerValue coeff);
227
228 // Heuristic to decides what LP is best solved next. We use the model lp
229 // solutions as an heuristic, and it should usually be updated with the last
230 // known solution before this call.
231 //
232 // The current solution state is used for detecting inactive constraints. It
233 // is also updated correctly on constraint deletion/addition so that the
234 // simplex can be fully iterative on restart by loading this modified state.
235 //
236 // Returns true iff LpConstraints() will return a different LP than before.
237 bool ChangeLp(glop::BasisState* solution_state,
238 int* num_new_constraints = nullptr);
239
240 // This can be called initially to add all the current constraint to the LP
241 // returned by GetLp().
243
244 // All the constraints managed by this class.
247 return constraint_infos_;
248 }
249
250 // The set of constraints indices in AllConstraints() that should be part
251 // of the next LP to solve.
252 const std::vector<ConstraintIndex>& LpConstraints() const {
253 return lp_constraints_;
254 }
255
256 // To simplify CutGenerator api.
258 return expanded_lp_solution_;
259 }
261 return expanded_reduced_costs_;
262 }
263
264 // Stats.
265 int64_t num_constraints() const { return constraint_infos_.size(); }
266 int64_t num_constraint_updates() const { return num_constraint_updates_; }
267 int64_t num_simplifications() const { return num_simplifications_; }
268 int64_t num_merged_constraints() const { return num_merged_constraints_; }
270 return num_shortened_constraints_;
271 }
272 int64_t num_split_constraints() const { return num_split_constraints_; }
273 int64_t num_coeff_strenghtening() const { return num_coeff_strenghtening_; }
274 int64_t num_cuts() const { return num_cuts_; }
275 int64_t num_add_cut_calls() const { return num_add_cut_calls_; }
276
277 const absl::btree_map<std::string, int>& type_to_num_cuts() const {
278 return type_to_num_cuts_;
279 }
280
281 // If a debug solution has been loaded, this checks if the given constraint
282 // cut it or not. Returns true if and only if everything is fine and the cut
283 // does not violate the loaded solution.
284 bool DebugCheckConstraint(const LinearConstraint& cut);
285
286 private:
287 // Heuristic that decide which constraints we should remove from the current
288 // LP. Note that such constraints can be added back later by the heuristic
289 // responsible for adding new constraints from the pool.
290 //
291 // Returns true if and only if one or more constraints where removed.
292 //
293 // If the solutions_state is empty, then this function does nothing and
294 // returns false (this is used for tests). Otherwise, the solutions_state is
295 // assumed to correspond to the current LP and to be of the correct size.
296 bool MaybeRemoveSomeInactiveConstraints(glop::BasisState* solution_state);
297
298 // Apply basic inprocessing simplification rules:
299 // - remove fixed variable
300 // - reduce large coefficient (i.e. coeff strenghtenning or big-M reduction).
301 // This uses level-zero bounds.
302 // Returns true if the terms of the constraint changed.
303 bool SimplifyConstraint(LinearConstraint* ct);
304
305 // Helper method to compute objective parallelism for a given constraint. This
306 // also lazily computes objective norm.
307 void ComputeObjectiveParallelism(ConstraintIndex ct_index);
308
309 // Multiplies all active counts and the increment counter by the given
310 // 'scaling_factor'. This should be called when at least one of the active
311 // counts is too high.
312 void RescaleActiveCounts(double scaling_factor);
313
314 // Removes some deletable constraints with low active counts. For now, we
315 // don't remove any constraints which are already in LP.
316 void PermanentlyRemoveSomeConstraints();
317
318 // Make sure the lb/ub are tight and fill lb_is_trivial/ub_is_trivial.
319 void FillDerivedFields(ConstraintInfo* info);
320
321 const SatParameters& sat_parameters_;
322 const IntegerTrail& integer_trail_;
323
324 // Set at true by Add()/SimplifyConstraint() and at false by ChangeLp().
325 bool current_lp_is_changed_ = false;
326
327 // Optimization to avoid calling SimplifyConstraint() when not needed.
328 int64_t last_simplification_timestamp_ = 0;
329
331
332 // The subset of constraints currently in the lp.
333 std::vector<ConstraintIndex> lp_constraints_;
334
335 // We keep a map from the hash of our constraint terms to their position in
336 // constraints_. This is an optimization to detect duplicate constraints. We
337 // are robust to collisions because we always relies on the ground truth
338 // contained in constraints_ and the code is still okay if we do not merge the
339 // constraints.
340 absl::flat_hash_map<size_t, ConstraintIndex> equiv_constraints_;
341
342 int64_t num_constraint_updates_ = 0;
343 int64_t num_simplifications_ = 0;
344 int64_t num_merged_constraints_ = 0;
345 int64_t num_shortened_constraints_ = 0;
346 int64_t num_split_constraints_ = 0;
347 int64_t num_coeff_strenghtening_ = 0;
348
349 int64_t num_cuts_ = 0;
350 int64_t num_add_cut_calls_ = 0;
351 absl::btree_map<std::string, int> type_to_num_cuts_;
352
353 bool objective_is_defined_ = false;
354 bool objective_norm_computed_ = false;
355 double objective_l2_norm_ = 0.0;
356
357 // Total deterministic time spent in this class.
358 double dtime_ = 0.0;
359
360 // Sparse representation of the objective coeffs indexed by positive variables
361 // indices. Important: We cannot use a dense representation here in the corner
362 // case where we have many independent LPs. Alternatively, we could share a
363 // dense vector between all LinearConstraintManager.
364 double sum_of_squared_objective_coeffs_ = 0.0;
365 absl::flat_hash_map<IntegerVariable, double> objective_map_;
366
367 TimeLimit* time_limit_;
368 ModelLpValues& expanded_lp_solution_;
369 ModelReducedCosts& expanded_reduced_costs_;
370 Model* model_;
371 LinearConstraintSymmetrizer* symmetrizer_;
372
373 // We want to decay the active counts of all constraints at each call and
374 // increase the active counts of active/violated constraints. However this can
375 // be too slow in practice. So instead, we keep an increment counter and
376 // update only the active/violated constraints. The counter itself is
377 // increased by a factor at each call. This has the same effect as decaying
378 // all the active counts at each call. This trick is similar to sat clause
379 // management.
380 double constraint_active_count_increase_ = 1.0;
381
382 int32_t num_deletable_constraints_ = 0;
383};
384
385// Before adding cuts to the global pool, it is a classical thing to only keep
386// the top n of a given type during one generation round. This is there to help
387// doing that.
388//
389// TODO(user): Avoid computing efficacity twice.
390// TODO(user): We don't use any orthogonality consideration here.
391// TODO(user): Detect duplicate cuts?
392class TopNCuts {
393 public:
394 explicit TopNCuts(int n) : cuts_(n) {}
395
396 // Adds a cut to the local pool.
397 void AddCut(
398 LinearConstraint ct, absl::string_view name,
400
401 // Empty the local pool and add all its content to the manager.
403
404 private:
405 struct CutCandidate {
406 std::string name;
408 };
409 TopN<CutCandidate, double> cuts_;
410};
411
412} // namespace sat
413} // namespace operations_research
414
415#endif // OR_TOOLS_SAT_LINEAR_CONSTRAINT_MANAGER_H_
ConstraintIndex Add(LinearConstraint ct, bool *added=nullptr, bool *folded=nullptr)
const std::vector< ConstraintIndex > & LpConstraints() const
bool ChangeLp(glop::BasisState *solution_state, int *num_new_constraints=nullptr)
bool AddCut(LinearConstraint ct, std::string type_name, std::string extra_info="")
bool UpdateConstraintUb(glop::RowIndex index_in_lp, IntegerValue new_ub)
bool UpdateConstraintLb(glop::RowIndex index_in_lp, IntegerValue new_lb)
These must be level zero bounds.
const util_intops::StrongVector< ConstraintIndex, ConstraintInfo > & AllConstraints() const
All the constraints managed by this class.
const absl::btree_map< std::string, int > & type_to_num_cuts() const
const util_intops::StrongVector< IntegerVariable, double > & ReducedCosts()
const util_intops::StrongVector< IntegerVariable, double > & LpValues()
To simplify CutGenerator api.
void SetObjectiveCoefficient(IntegerVariable var, IntegerValue coeff)
int NumOrbits() const
Accessors by orbit index in [0, num_orbits).
bool FoldLinearConstraint(LinearConstraint *ct, bool *folded=nullptr)
void AddSymmetryOrbit(IntegerVariable sum_var, absl::Span< const IntegerVariable > orbit)
absl::Span< const IntegerVariable > Orbit(int i) const
bool IsOrbitSumVar(IntegerVariable var) const
Returns true iff var is one of the sum_var passed to AddSymmetryOrbit().
Simple class to add statistics by name and print them at the end.
void TransferToManager(LinearConstraintManager *manager)
Empty the local pool and add all its content to the manager.
void AddCut(LinearConstraint ct, absl::string_view name, const util_intops::StrongVector< IntegerVariable, double > &lp_solution)
Adds a cut to the local pool.
In SWIG mode, we don't want anything besides these top-level includes.
Same as ModelLpValues for reduced costs.