OR-Tools  9.1
linear_programming_constraint.h
Go to the documentation of this file.
1// Copyright 2010-2021 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_PROGRAMMING_CONSTRAINT_H_
15#define OR_TOOLS_SAT_LINEAR_PROGRAMMING_CONSTRAINT_H_
16
17#include <cstdint>
18#include <limits>
19#include <utility>
20#include <vector>
21
22#include "absl/container/flat_hash_map.h"
29#include "ortools/sat/cuts.h"
31#include "ortools/sat/integer.h"
35#include "ortools/sat/model.h"
36#include "ortools/sat/util.h"
38#include "ortools/util/rev.h"
40
41namespace operations_research {
42namespace sat {
43
44// Stores for each IntegerVariable its temporary LP solution.
45//
46// This is shared between all LinearProgrammingConstraint because in the corner
47// case where we have many different LinearProgrammingConstraint and a lot of
48// variable, we could theoretically use up a quadratic amount of memory
49// otherwise.
50//
51// TODO(user): find a better way?
53 : public absl::StrongVector<IntegerVariable, double> {
55};
56
57// Helper struct to combine info generated from solving LP.
60 double lp_objective = -std::numeric_limits<double>::infinity();
62};
63
64// Simple class to combine linear expression efficiently. First in a sparse
65// way that switch to dense when the number of non-zeros grows.
67 public:
68 // This must be called with the correct size before any other functions are
69 // used.
70 void ClearAndResize(int size);
71
72 // Does vector[col] += value and return false in case of overflow.
73 bool Add(glop::ColIndex col, IntegerValue value);
74
75 // Similar to Add() but for multiplier * terms.
76 // Returns false in case of overflow.
78 IntegerValue multiplier,
79 const std::vector<std::pair<glop::ColIndex, IntegerValue>>& terms);
80
81 // This is not const only because non_zeros is sorted. Note that sorting the
82 // non-zeros make the result deterministic whether or not we were in sparse
83 // mode.
84 //
85 // TODO(user): Ideally we should convert to IntegerVariable as late as
86 // possible. Prefer to use GetTerms().
88 const std::vector<IntegerVariable>& integer_variables,
89 IntegerValue upper_bound, LinearConstraint* result);
90
91 // Similar to ConvertToLinearConstraint().
92 std::vector<std::pair<glop::ColIndex, IntegerValue>> GetTerms();
93
94 // We only provide the const [].
95 IntegerValue operator[](glop::ColIndex col) const {
96 return dense_vector_[col];
97 }
98
99 const bool IsSparse() const { return is_sparse_; }
100
101 private:
102 // If is_sparse is true we maintain the non_zeros positions and bool vector
103 // of dense_vector_. Otherwise we don't. Note that we automatically switch
104 // from sparse to dense as needed.
105 bool is_sparse_ = true;
106 std::vector<glop::ColIndex> non_zeros_;
108
109 // The dense representation of the vector.
111};
112
113// A SAT constraint that enforces a set of linear inequality constraints on
114// integer variables using an LP solver.
115//
116// The propagator uses glop's revised simplex for feasibility and propagation.
117// It uses the Reduced Cost Strengthening technique, a classic in mixed integer
118// programming, for instance see the thesis of Tobias Achterberg,
119// "Constraint Integer Programming", sections 7.7 and 8.8, algorithm 7.11.
120// http://nbn-resolving.de/urn:nbn:de:0297-zib-11129
121//
122// Per-constraint bounds propagation is NOT done by this constraint,
123// it should be done by redundant constraints, as reduced cost propagation
124// may miss some filtering.
125//
126// Note that this constraint works with double floating-point numbers, so one
127// could be worried that it may filter too much in case of precision issues.
128// However, by default, we interpret the LP result by recomputing everything
129// in integer arithmetic, so we are exact.
130class LinearProgrammingDispatcher;
133 public:
134 typedef glop::RowIndex ConstraintIndex;
135
137
138 // Add a new linear constraint to this LP.
140
141 // Set the coefficient of the variable in the objective. Calling it twice will
142 // overwrite the previous value.
143 void SetObjectiveCoefficient(IntegerVariable ivar, IntegerValue coeff);
144
145 // The main objective variable should be equal to the linear sum of
146 // the arguments passed to SetObjectiveCoefficient().
147 void SetMainObjectiveVariable(IntegerVariable ivar) { objective_cp_ = ivar; }
148
149 // Register a new cut generator with this constraint.
150 void AddCutGenerator(CutGenerator generator);
151
152 // Returns the LP value and reduced cost of a variable in the current
153 // solution. These functions should only be called when HasSolution() is true.
154 //
155 // Note that this solution is always an OPTIMAL solution of an LP above or
156 // at the current decision level. We "erase" it when we backtrack over it.
157 bool HasSolution() const { return lp_solution_is_set_; }
158 double SolutionObjectiveValue() const { return lp_objective_; }
159 double GetSolutionValue(IntegerVariable variable) const;
160 double GetSolutionReducedCost(IntegerVariable variable) const;
161 bool SolutionIsInteger() const { return lp_solution_is_integer_; }
162
163 // PropagatorInterface API.
164 bool Propagate() override;
165 bool IncrementalPropagate(const std::vector<int>& watch_indices) override;
166 void RegisterWith(Model* model);
167
168 // ReversibleInterface API.
169 void SetLevel(int level) override;
170
171 int NumVariables() const { return integer_variables_.size(); }
172 const std::vector<IntegerVariable>& integer_variables() const {
173 return integer_variables_;
174 }
175 std::string DimensionString() const { return lp_data_.GetDimensionString(); }
176
177 // Returns a IntegerLiteral guided by the underlying LP constraints.
178 //
179 // This looks at all unassigned 0-1 variables, takes the one with
180 // a support value closest to 0.5, and tries to assign it to 1.
181 // If all 0-1 variables have an integer support, returns kNoLiteralIndex.
182 // Tie-breaking is done using the variable natural order.
183 //
184 // TODO(user): This fixes to 1, but for some problems fixing to 0
185 // or to the std::round(support value) might work better. When this is the
186 // case, change behaviour automatically?
188
189 // Returns a IntegerLiteral guided by the underlying LP constraints.
190 //
191 // This computes the mean of reduced costs over successive calls,
192 // and tries to fix the variable which has the highest reduced cost.
193 // Tie-breaking is done using the variable natural order.
194 // Only works for 0/1 variables.
195 //
196 // TODO(user): Try to get better pseudocosts than averaging every time
197 // the heuristic is called. MIP solvers initialize this with strong branching,
198 // then keep track of the pseudocosts when doing tree search. Also, this
199 // version only branches on var >= 1 and keeps track of reduced costs from var
200 // = 1 to var = 0. This works better than the conventional MIP where the
201 // chosen variable will be argmax_var min(pseudocost_var(0->1),
202 // pseudocost_var(1->0)), probably because we are doing DFS search where MIP
203 // does BFS. This might depend on the model, more trials are necessary. We
204 // could also do exponential smoothing instead of decaying every N calls, i.e.
205 // pseudo = a * pseudo + (1-a) reduced.
207
208 // Returns a IntegerLiteral guided by the underlying LP constraints.
209 //
210 // This computes the mean of reduced costs over successive calls,
211 // and tries to fix the variable which has the highest reduced cost.
212 // Tie-breaking is done using the variable natural order.
214
215 // Average number of nonbasic variables with zero reduced costs.
216 double average_degeneracy() const {
217 return average_degeneracy_.CurrentAverage();
218 }
219
221 return total_num_simplex_iterations_;
222 }
223
224 // Returns some statistics about this LP.
225 std::string Statistics() const;
226
227 private:
228 // Helper methods for branching. Returns true if branching on the given
229 // variable helps with more propagation or finds a conflict.
230 bool BranchOnVar(IntegerVariable var);
231 LPSolveInfo SolveLpForBranching();
232
233 // Helper method to fill reduced cost / dual ray reason in 'integer_reason'.
234 // Generates a set of IntegerLiterals explaining why the best solution can not
235 // be improved using reduced costs. This is used to generate explanations for
236 // both infeasibility and bounds deductions.
237 void FillReducedCostReasonIn(const glop::DenseRow& reduced_costs,
238 std::vector<IntegerLiteral>* integer_reason);
239
240 // Reinitialize the LP from a potentially new set of constraints.
241 // This fills all data structure and properly rescale the underlying LP.
242 //
243 // Returns false if the problem is UNSAT (it can happen when presolve is off
244 // and some LP constraint are trivially false).
245 bool CreateLpFromConstraintManager();
246
247 // Solve the LP, returns false if something went wrong in the LP solver.
248 bool SolveLp();
249
250 // Add a "MIR" cut obtained by first taking the linear combination of the
251 // row of the matrix according to "integer_multipliers" and then trying
252 // some integer rounding heuristic.
253 //
254 // Return true if a new cut was added to the cut manager.
255 bool AddCutFromConstraints(
256 const std::string& name,
257 const std::vector<std::pair<glop::RowIndex, IntegerValue>>&
258 integer_multipliers);
259
260 // Second half of AddCutFromConstraints().
261 bool PostprocessAndAddCut(
262 const std::string& name, const std::string& info,
263 IntegerVariable first_new_var, IntegerVariable first_slack,
264 const std::vector<ImpliedBoundsProcessor::SlackInfo>& ib_slack_infos,
265 LinearConstraint* cut);
266
267 // Computes and adds the corresponding type of cuts.
268 // This can currently only be called at the root node.
269 void AddCGCuts();
270 void AddMirCuts();
271 void AddZeroHalfCuts();
272
273 // Updates the bounds of the LP variables from the CP bounds.
274 void UpdateBoundsOfLpVariables();
275
276 // Use the dual optimal lp values to compute an EXACT lower bound on the
277 // objective. Fills its reason and perform reduced cost strenghtening.
278 // Returns false in case of conflict.
279 bool ExactLpReasonning();
280
281 // Same as FillDualRayReason() but perform the computation EXACTLY. Returns
282 // false in the case that the problem is not provably infeasible with exact
283 // computations, true otherwise.
284 bool FillExactDualRayReason();
285
286 // Returns number of non basic variables with zero reduced costs.
287 int64_t CalculateDegeneracy();
288
289 // From a set of row multipliers (at LP scale), scale them back to the CP
290 // world and then make them integer (eventually multiplying them by a new
291 // scaling factor returned in *scaling).
292 //
293 // Note that this will loose some precision, but our subsequent computation
294 // will still be exact as it will work for any set of multiplier.
295 std::vector<std::pair<glop::RowIndex, IntegerValue>> ScaleLpMultiplier(
296 bool take_objective_into_account,
297 const std::vector<std::pair<glop::RowIndex, double>>& lp_multipliers,
298 glop::Fractional* scaling, int max_pow = 62) const;
299
300 // Computes from an integer linear combination of the integer rows of the LP a
301 // new constraint of the form "sum terms <= upper_bound". All computation are
302 // exact here.
303 //
304 // Returns false if we encountered any integer overflow.
305 bool ComputeNewLinearConstraint(
306 const std::vector<std::pair<glop::RowIndex, IntegerValue>>&
307 integer_multipliers,
308 ScatteredIntegerVector* scattered_vector,
309 IntegerValue* upper_bound) const;
310
311 // Simple heuristic to try to minimize |upper_bound - ImpliedLB(terms)|. This
312 // should make the new constraint tighter and correct a bit the imprecision
313 // introduced by rounding the floating points values.
314 void AdjustNewLinearConstraint(
315 std::vector<std::pair<glop::RowIndex, IntegerValue>>* integer_multipliers,
316 ScatteredIntegerVector* scattered_vector,
317 IntegerValue* upper_bound) const;
318
319 // Shortcut for an integer linear expression type.
320 using LinearExpression = std::vector<std::pair<glop::ColIndex, IntegerValue>>;
321
322 // Converts a dense representation of a linear constraint to a sparse one
323 // expressed in terms of IntegerVariable.
324 void ConvertToLinearConstraint(
326 IntegerValue upper_bound, LinearConstraint* result);
327
328 // Compute the implied lower bound of the given linear expression using the
329 // current variable bound. Return kMinIntegerValue in case of overflow.
330 IntegerValue GetImpliedLowerBound(const LinearConstraint& terms) const;
331
332 // Tests for possible overflow in the propagation of the given linear
333 // constraint.
334 bool PossibleOverflow(const LinearConstraint& constraint);
335
336 // Reduce the coefficient of the constraint so that we cannot have overflow
337 // in the propagation of the given linear constraint. Note that we may loose
338 // some strength by doing so.
339 //
340 // We make sure that any partial sum involving any variable value in their
341 // domain do not exceed 2 ^ max_pow.
342 void PreventOverflow(LinearConstraint* constraint, int max_pow = 62);
343
344 // Fills integer_reason_ with the reason for the implied lower bound of the
345 // given linear expression. We relax the reason if we have some slack.
346 void SetImpliedLowerBoundReason(const LinearConstraint& terms,
347 IntegerValue slack);
348
349 // Fills the deductions vector with reduced cost deductions that can be made
350 // from the current state of the LP solver. The given delta should be the
351 // difference between the cp objective upper bound and lower bound given by
352 // the lp.
353 void ReducedCostStrengtheningDeductions(double cp_objective_delta);
354
355 // Returns the variable value on the same scale as the CP variable value.
356 glop::Fractional GetVariableValueAtCpScale(glop::ColIndex var);
357
358 // Gets or creates an LP variable that mirrors a CP variable.
359 // The variable should be a positive reference.
360 glop::ColIndex GetOrCreateMirrorVariable(IntegerVariable positive_variable);
361
362 // This must be called on an OPTIMAL LP and will update the data for
363 // LPReducedCostAverageDecision().
364 void UpdateAverageReducedCosts();
365
366 // Callback underlying LPReducedCostAverageBranching().
367 IntegerLiteral LPReducedCostAverageDecision();
368
369 // Updates the simplex iteration limit for the next visit.
370 // As per current algorithm, we use a limit which is dependent on size of the
371 // problem and drop it significantly if degeneracy is detected. We use
372 // DUAL_FEASIBLE status as a signal to correct the prediction. The next limit
373 // is capped by 'min_iter' and 'max_iter'. Note that this is enabled only for
374 // linearization level 2 and above.
375 void UpdateSimplexIterationLimit(const int64_t min_iter,
376 const int64_t max_iter);
377
378 // This epsilon is related to the precision of the value/reduced_cost returned
379 // by the LP once they have been scaled back into the CP domain. So for large
380 // domain or cost coefficient, we may have some issues.
381 static constexpr double kCpEpsilon = 1e-4;
382
383 // Same but at the LP scale.
384 static constexpr double kLpEpsilon = 1e-6;
385
386 // Anything coming from the LP with a magnitude below that will be assumed to
387 // be zero.
388 static constexpr double kZeroTolerance = 1e-12;
389
390 // Class responsible for managing all possible constraints that may be part
391 // of the LP.
392 LinearConstraintManager constraint_manager_;
393
394 // Initial problem in integer form.
395 // We always sort the inner vectors by increasing glop::ColIndex.
396 struct LinearConstraintInternal {
397 IntegerValue lb;
398 IntegerValue ub;
399 LinearExpression terms;
400 };
401 LinearExpression integer_objective_;
402 IntegerValue integer_objective_offset_ = IntegerValue(0);
403 IntegerValue objective_infinity_norm_ = IntegerValue(0);
406
407 // Underlying LP solver API.
408 glop::LinearProgram lp_data_;
409 glop::RevisedSimplex simplex_;
410 int64_t next_simplex_iter_ = 500;
411
412 // For the scaling.
413 glop::LpScalingHelper scaler_;
414
415 // Temporary data for cuts.
416 ZeroHalfCutHelper zero_half_cut_helper_;
417 CoverCutHelper cover_cut_helper_;
418 IntegerRoundingCutHelper integer_rounding_cut_helper_;
419 LinearConstraint cut_;
420
421 ScatteredIntegerVector tmp_scattered_vector_;
422
423 std::vector<double> tmp_lp_values_;
424 std::vector<IntegerValue> tmp_var_lbs_;
425 std::vector<IntegerValue> tmp_var_ubs_;
426 std::vector<glop::RowIndex> tmp_slack_rows_;
427 std::vector<IntegerValue> tmp_slack_bounds_;
428
429 // Used by ScaleLpMultiplier().
430 mutable std::vector<std::pair<glop::RowIndex, double>> tmp_cp_multipliers_;
431
432 // Structures used for mirroring IntegerVariables inside the underlying LP
433 // solver: an integer variable var is mirrored by mirror_lp_variable_[var].
434 // Note that these indices are dense in [0, mirror_lp_variable_.size()] so
435 // they can be used as vector indices.
436 //
437 // TODO(user): This should be absl::StrongVector<glop::ColIndex,
438 // IntegerVariable>.
439 std::vector<IntegerVariable> integer_variables_;
440 absl::flat_hash_map<IntegerVariable, glop::ColIndex> mirror_lp_variable_;
441
442 // We need to remember what to optimize if an objective is given, because
443 // then we will switch the objective between feasibility and optimization.
444 bool objective_is_defined_ = false;
445 IntegerVariable objective_cp_;
446
447 // Singletons from Model.
448 const SatParameters& sat_parameters_;
449 Model* model_;
450 TimeLimit* time_limit_;
451 IntegerTrail* integer_trail_;
452 Trail* trail_;
453 IntegerEncoder* integer_encoder_;
454 ModelRandomGenerator* random_;
455
456 // Used while deriving cuts.
457 ImpliedBoundsProcessor implied_bounds_processor_;
458
459 // The dispatcher for all LP propagators of the model, allows to find which
460 // LinearProgrammingConstraint has a given IntegerVariable.
461 LinearProgrammingDispatcher* dispatcher_;
462
463 std::vector<IntegerLiteral> integer_reason_;
464 std::vector<IntegerLiteral> deductions_;
465 std::vector<IntegerLiteral> deductions_reason_;
466
467 // Repository of IntegerSumLE that needs to be kept around for the lazy
468 // reasons. Those are new integer constraint that are created each time we
469 // solve the LP to a dual-feasible solution. Propagating these constraints
470 // both improve the objective lower bound but also perform reduced cost
471 // fixing.
472 int rev_optimal_constraints_size_ = 0;
473 std::vector<std::unique_ptr<IntegerSumLE>> optimal_constraints_;
474
475 // Last OPTIMAL solution found by a call to the underlying LP solver.
476 // On IncrementalPropagate(), if the bound updates do not invalidate this
477 // solution, Propagate() will not find domain reductions, no need to call it.
478 int lp_solution_level_ = 0;
479 bool lp_solution_is_set_ = false;
480 bool lp_solution_is_integer_ = false;
481 double lp_objective_;
482 std::vector<double> lp_solution_;
483 std::vector<double> lp_reduced_cost_;
484
485 // If non-empty, this is the last known optimal lp solution at root-node. If
486 // the variable bounds changed, or cuts where added, it is possible that this
487 // solution is no longer optimal though.
488 std::vector<double> level_zero_lp_solution_;
489
490 // True if the last time we solved the exact same LP at level zero, no cuts
491 // and no lazy constraints where added.
492 bool lp_at_level_zero_is_final_ = false;
493
494 // Same as lp_solution_ but this vector is indexed differently.
495 LinearProgrammingConstraintLpSolution& expanded_lp_solution_;
496
497 // Linear constraints cannot be created or modified after this is registered.
498 bool lp_constraint_is_registered_ = false;
499
500 std::vector<CutGenerator> cut_generators_;
501
502 // Store some statistics for HeuristicLPReducedCostAverage().
503 bool compute_reduced_cost_averages_ = false;
504 int num_calls_since_reduced_cost_averages_reset_ = 0;
505 std::vector<double> sum_cost_up_;
506 std::vector<double> sum_cost_down_;
507 std::vector<int> num_cost_up_;
508 std::vector<int> num_cost_down_;
509 std::vector<double> rc_scores_;
510
511 // All the entries before rev_rc_start_ in the sorted positions correspond
512 // to fixed variables and can be ignored.
513 int rev_rc_start_ = 0;
514 RevRepository<int> rc_rev_int_repository_;
515 std::vector<std::pair<double, int>> positions_by_decreasing_rc_score_;
516
517 // Defined as average number of nonbasic variables with zero reduced costs.
518 IncrementalAverage average_degeneracy_;
519 bool is_degenerate_ = false;
520
521 // Used by the strong branching heuristic.
522 int branching_frequency_ = 1;
523 int64_t count_since_last_branching_ = 0;
524
525 // Sum of all simplex iterations performed by this class. This is useful to
526 // test the incrementality and compare to other solvers.
527 int64_t total_num_simplex_iterations_ = 0;
528
529 // Some stats on the LP statuses encountered.
530 int64_t num_solves_ = 0;
531 std::vector<int64_t> num_solves_by_status_;
532};
533
534// A class that stores which LP propagator is associated to each variable.
535// We need to give the hash_map a name so it can be used as a singleton in our
536// model.
537//
538// Important: only positive variable do appear here.
540 : public absl::flat_hash_map<IntegerVariable,
541 LinearProgrammingConstraint*> {
542 public:
544};
545
546// A class that stores the collection of all LP constraints in a model.
548 : public std::vector<LinearProgrammingConstraint*> {
549 public:
551};
552
553// Cut generator for the circuit constraint, where in any feasible solution, the
554// arcs that are present (variable at 1) must form a circuit through all the
555// nodes of the graph. Self arc are forbidden in this case.
556//
557// In more generality, this currently enforce the resulting graph to be strongly
558// connected. Note that we already assume basic constraint to be in the lp, so
559// we do not add any cuts for components of size 1.
561 int num_nodes, const std::vector<int>& tails, const std::vector<int>& heads,
562 const std::vector<Literal>& literals, Model* model);
563
564// Almost the same as CreateStronglyConnectedGraphCutGenerator() but for each
565// components, computes the demand needed to serves it, and depending on whether
566// it contains the depot (node zero) or not, compute the minimum number of
567// vehicle that needs to cross the component border.
568CutGenerator CreateCVRPCutGenerator(int num_nodes,
569 const std::vector<int>& tails,
570 const std::vector<int>& heads,
571 const std::vector<Literal>& literals,
572 const std::vector<int64_t>& demands,
573 int64_t capacity, Model* model);
574} // namespace sat
575} // namespace operations_research
576
577#endif // OR_TOOLS_SAT_LINEAR_PROGRAMMING_CONSTRAINT_H_
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
std::string GetDimensionString() const
Definition: lp_data.cc:425
std::function< IntegerLiteral()> HeuristicLpReducedCostBinary(Model *model)
bool IncrementalPropagate(const std::vector< int > &watch_indices) override
std::function< IntegerLiteral()> HeuristicLpMostInfeasibleBinary(Model *model)
const std::vector< IntegerVariable > & integer_variables() const
void SetObjectiveCoefficient(IntegerVariable ivar, IntegerValue coeff)
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
void ConvertToLinearConstraint(const std::vector< IntegerVariable > &integer_variables, IntegerValue upper_bound, LinearConstraint *result)
bool Add(glop::ColIndex col, IntegerValue value)
bool AddLinearExpressionMultiple(IntegerValue multiplier, const std::vector< std::pair< glop::ColIndex, IntegerValue > > &terms)
std::vector< std::pair< glop::ColIndex, IntegerValue > > GetTerms()
const std::string name
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
double upper_bound
GRBmodel * model
ColIndex col
Definition: markowitz.cc:183
CutGenerator CreateCVRPCutGenerator(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, const std::vector< int64_t > &demands, int64_t capacity, Model *model)
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
CutGenerator CreateStronglyConnectedGraphCutGenerator(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, Model *model)
Collection of objects used to extend the Constraint Solver library.
int64_t capacity