Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
constraint_violation.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_CONSTRAINT_VIOLATION_H_
15#define OR_TOOLS_SAT_CONSTRAINT_VIOLATION_H_
16
17#include <cstddef>
18#include <cstdint>
19#include <memory>
20#include <optional>
21#include <utility>
22#include <vector>
23
24#include "absl/container/flat_hash_map.h"
25#include "absl/log/check.h"
26#include "absl/types/span.h"
30#include "ortools/sat/util.h"
31#include "ortools/util/bitset.h"
35
36namespace operations_research {
37namespace sat {
38
40 public:
42
43 // Returns the index of the new constraint.
44 int NewConstraint(Domain domain);
45
46 // Incrementaly build the constraint.
47 //
48 // In case of duplicate variables on the same constraint, the code assumes
49 // constraints are built in-order as it checks for duplication.
50 //
51 // Note that the code assume that a Boolean variable DO NOT appear both in the
52 // enforcement list and in the constraint. Otherwise the update will just be
53 // wrong. This should be enforced by our presolve.
54 void AddEnforcementLiteral(int ct_index, int lit);
55 void AddLiteral(int ct_index, int lit, int64_t coeff = 1);
56 void AddTerm(int ct_index, int var, int64_t coeff, int64_t offset = 0);
57 void AddOffset(int ct_index, int64_t offset);
58 void AddLinearExpression(int ct_index, const LinearExpressionProto& expr,
59 int64_t multiplier);
60
61 // Important: this needs to be called after all constraint has been added
62 // and before the class starts to be used. This is DCHECKed.
63 void PrecomputeCompactView(absl::Span<const int64_t> var_max_variation);
64
65 // Compute activities.
66 void ComputeInitialActivities(absl::Span<const int64_t> solution);
67
68 // Update the activities of each constraints.
69 // Also update the current score for the given deltas.
70 //
71 // Note that the score of the changed variable will not be updated correctly!
73 int var, int64_t delta, absl::Span<const double> weights,
74 absl::Span<const int64_t> jump_deltas, absl::Span<double> jump_scores,
75 std::vector<int>* constraints_with_changed_violations);
76
77 // Also for feasibility jump.
78 void UpdateScoreOnWeightUpdate(int c, absl::Span<const int64_t> jump_deltas,
79 absl::Span<double> var_to_score_change);
80
81 // Variables whose score/jump might have changed since the last clear.
82 //
83 // Note that because we reason on a per-constraint basis, this is actually
84 // independent of the set of positive constraint weight used.
86 absl::Span<const int> VariablesAffectedByLastUpdate() const {
87 return last_affected_variables_.PositionsSetAtLeastOnce();
88 }
89
90 // Query violation.
91 int64_t Activity(int c) const;
92 int64_t Violation(int c) const;
93 bool IsViolated(int c) const;
94 bool AppearsInViolatedConstraints(int var) const;
95
96 // Used to DCHECK the state of the evaluator.
97 bool VarIsConsistent(int var) const;
98
99 // Intersect constraint bounds with [lb..ub].
100 // It returns true if a reduction of the domain took place.
101 bool ReduceBounds(int c, int64_t lb, int64_t ub);
102
103 // Model getters.
104 int num_constraints() const { return num_constraints_; }
105
106 // Returns the weighted sum of the violation.
107 // Note that weights might have more entries than the number of constraints.
108 double WeightedViolation(absl::Span<const double> weights) const;
109
110 // Computes how much the weighted violation will change if var was changed
111 // from its old value by += delta.
112 double WeightedViolationDelta(absl::Span<const double> weights, int var,
113 int64_t delta) const;
114
115 // The violation for each constraint is a piecewise linear function. This
116 // computes and aggregates all the breakpoints for the given variable and its
117 // domain.
118 //
119 // Note that if the domain contains less than two values, we return an empty
120 // vector. This function is not meant to be used for such domains.
121 std::vector<int64_t> SlopeBreakpoints(int var, int64_t current_value,
122 const Domain& var_domain) const;
123
124 // Checks if the jump value of a variable is always optimal.
125 bool ViolationChangeIsConvex(int var) const;
126
127 double DeterministicTime() const {
128 return 5e-9 * static_cast<double>(num_ops_);
129 }
130
131 int64_t ObjectiveCoefficient(int var) const {
132 if (var >= columns_.size()) return 0.0;
133 const SpanData& data = columns_[var];
134 if (data.num_linear_entries == 0) return 0.0;
135 const int i = data.start + data.num_neg_literal + data.num_pos_literal;
136 const int c = ct_buffer_[i];
137 if (c != 0) return 0.0;
138 return coeff_buffer_[data.linear_start];
139 }
140
141 absl::Span<const int> ConstraintToVars(int c) const {
142 const SpanData& data = rows_[c];
143 const int size =
144 data.num_pos_literal + data.num_neg_literal + data.num_linear_entries;
145 if (size == 0) return {};
146 return absl::MakeSpan(&row_var_buffer_[data.start], size);
147 }
148
149 private:
150 // Cell in the sparse matrix.
151 struct Entry {
152 int ct_index;
153 int64_t coefficient;
154 };
155
156 // Column-view of the enforcement literals.
157 struct LiteralEntry {
158 int ct_index;
159 bool positive; // bool_var or its negation.
160 };
161
162 struct SpanData {
163 int start = 0;
164 int num_pos_literal = 0;
165 int num_neg_literal = 0;
166 int linear_start = 0;
167 int num_linear_entries = 0;
168 };
169
170 absl::Span<const int> VarToConstraints(int var) const {
171 if (var >= columns_.size()) return {};
172 const SpanData& data = columns_[var];
173 const int size =
174 data.num_pos_literal + data.num_neg_literal + data.num_linear_entries;
175 if (size == 0) return {};
176 return absl::MakeSpan(&ct_buffer_[data.start], size);
177 }
178
179 void ComputeAndCacheDistance(int ct_index);
180
181 // Incremental row-based update.
182 void UpdateScoreOnNewlyEnforced(int c, double weight,
183 absl::Span<const int64_t> jump_deltas,
184 absl::Span<double> jump_scores);
185 void UpdateScoreOnNewlyUnenforced(int c, double weight,
186 absl::Span<const int64_t> jump_deltas,
187 absl::Span<double> jump_scores);
188 void UpdateScoreOfEnforcementIncrease(int c, double score_change,
189 absl::Span<const int64_t> jump_deltas,
190 absl::Span<double> jump_scores);
191 void UpdateScoreOnActivityChange(int c, double weight, int64_t activity_delta,
192 absl::Span<const int64_t> jump_deltas,
193 absl::Span<double> jump_scores);
194
195 // Constraint indexed data (static).
196 int num_constraints_ = 0;
197 std::vector<Domain> domains_;
198 std::vector<int64_t> offsets_;
199
200 // Variable indexed data.
201 // Note that this is just used at construction and is replaced by a compact
202 // view when PrecomputeCompactView() is called.
203 bool creation_phase_ = true;
204 std::vector<std::vector<Entry>> var_entries_;
205 std::vector<std::vector<LiteralEntry>> literal_entries_;
206
207 // Memory efficient column based data (static).
208 std::vector<SpanData> columns_;
209 std::vector<int> ct_buffer_;
210 std::vector<int64_t> coeff_buffer_;
211
212 // Memory efficient row based data (static).
213 std::vector<SpanData> rows_;
214 std::vector<int> row_var_buffer_;
215 std::vector<int64_t> row_coeff_buffer_;
216
217 // In order to avoid scanning long constraint we compute for each of them
218 // the maximum activity variation of one variable (max-min) * abs(coeff).
219 // If the current activity plus this is still feasible, then the constraint
220 // do not need to be scanned.
221 std::vector<int64_t> row_max_variations_;
222
223 // Temporary data.
224 std::vector<int> tmp_row_sizes_;
225 std::vector<int> tmp_row_num_positive_literals_;
226 std::vector<int> tmp_row_num_negative_literals_;
227 std::vector<int> tmp_row_num_linear_entries_;
228
229 // Constraint indexed data (dynamic).
230 std::vector<bool> is_violated_;
231 std::vector<int64_t> activities_;
232 std::vector<int64_t> distances_;
233 std::vector<int> num_false_enforcement_;
234
235 // Code to update the scores on a variable change.
236 std::vector<int64_t> old_distances_;
237 std::vector<int> old_num_false_enforcement_;
238 std::vector<int64_t> cached_deltas_;
239 std::vector<double> cached_scores_;
240
241 SparseBitset<int> last_affected_variables_;
242
243 mutable size_t num_ops_ = 0;
244};
245
246// View of a generic (non linear) constraint for the LsEvaluator.
248 public:
250 virtual ~CompiledConstraint() = default;
251
252 // Recomputes the violation of the constraint from scratch.
253 void InitializeViolation(absl::Span<const int64_t> solution);
254
255 // Updates the violation with the new value.
256 virtual void PerformMove(int var, int64_t old_value,
257 absl::Span<const int64_t> solution_with_new_value);
258
259 // Returns the delta if var changes from old_value to solution[var].
260 virtual int64_t ViolationDelta(
261 int var, int64_t old_value,
262 absl::Span<const int64_t> solution_with_new_value);
263
264 // Returns the sorted vector of variables used by this constraint. This is
265 // used to known when a violation might change, and is only called once during
266 // initialization, so speed is not to much of a concern here.
267 //
268 // The global proto is needed to resolve interval variables reference.
269 virtual std::vector<int> UsedVariables(
270 const CpModelProto& model_proto) const = 0;
271
272 // The cached violation of this constraint.
273 int64_t violation() const { return violation_; }
274
275 protected:
276 // Computes the violation of a constraint.
277 //
278 // This is called by InitializeViolation() and also the default implementation
279 // of ViolationDelta().
280 virtual int64_t ComputeViolation(absl::Span<const int64_t> solution) = 0;
281
282 int64_t violation_;
283};
284
285// Intermediate class for all constraints that store directly their proto as
286// part of their implementation.
288 public:
290 ~CompiledConstraintWithProto() override = default;
291
292 const ConstraintProto& ct_proto() const { return ct_proto_; }
293
294 // This just returns the variables used by the stored ct_proto_.
295 std::vector<int> UsedVariables(const CpModelProto& model_proto) const final;
296
297 private:
298 const ConstraintProto& ct_proto_;
299};
300
301// Evaluation container for the local search.
302//
303// TODO(user): Ideas for constraint generated moves or sequences of moves?
304
305// Note(user): This class do not handle ALL constraint yet. So it is not because
306// there is no violation here that the solution will be feasible. It is
307// important to check feasibility once this is used. Note that in practice, we
308// can be lucky, and feasible on a subset of hard constraint is enough.
310 public:
311 // The cp_model must outlive this class.
312 LsEvaluator(const CpModelProto& cp_model, const SatParameters& params,
314 LsEvaluator(const CpModelProto& cp_model, const SatParameters& params,
315 const std::vector<bool>& ignored_constraints,
316 const std::vector<ConstraintProto>& additional_constraints,
318
319 // Intersects the domain of the objective with [lb..ub].
320 // It returns true if a reduction of the domain took place.
321 bool ReduceObjectiveBounds(int64_t lb, int64_t ub);
322
323 // Recomputes the violations of all constraints (resp only non-linear one).
324 void ComputeAllViolations(absl::Span<const int64_t> solution);
325 void ComputeAllNonLinearViolations(absl::Span<const int64_t> solution);
326
327 // Recomputes the violations of all impacted non linear constraints.
328 void UpdateNonLinearViolations(int var, int64_t old_value,
329 absl::Span<const int64_t> new_solution);
330
331 // Function specific to the linear only feasibility jump.
332 void UpdateLinearScores(int var, int64_t old_value, int64_t new_value,
333 absl::Span<const double> weights,
334 absl::Span<const int64_t> jump_deltas,
335 absl::Span<double> jump_scores);
336
337 // Must be called after UpdateLinearScores() / UpdateNonLinearViolations()
338 // in order to update the ViolatedConstraints().
339 void UpdateViolatedList();
340
341 absl::Span<const int> VariablesAffectedByLastLinearUpdate() const {
342 return linear_evaluator_.VariablesAffectedByLastUpdate();
343 }
344
345 // Simple summation metric for the constraint and objective violations.
346 int64_t SumOfViolations();
347
348 // Returns the objective activity in the current state.
349 int64_t ObjectiveActivity() const;
350
351 bool IsObjectiveConstraint(int c) const {
352 return cp_model_.has_objective() && c == 0;
353 }
354
355 int64_t ObjectiveCoefficient(int var) const {
356 return cp_model_.has_objective()
357 ? linear_evaluator_.ObjectiveCoefficient(var)
358 : 0;
359 }
360
361 // The number of "internal" constraints in the evaluator. This might not
362 // be the same as the number of initial constraints of the model.
363 int NumLinearConstraints() const;
364 int NumNonLinearConstraints() const;
365 int NumEvaluatorConstraints() const;
366 int NumInfeasibleConstraints() const;
367
368 // Returns the weighted sum of violation. The weights must have the same
369 // size as NumEvaluatorConstraints().
370 int64_t Violation(int c) const;
371 bool IsViolated(int c) const;
372 double WeightedViolation(absl::Span<const double> weights) const;
373
374 // Computes the delta in weighted violation if solution[var] += delta.
375 // We need a temporary mutable solution to evaluate the violation of generic
376 // constraints. If linear_only is true, only the linear violation will be
377 // used.
378 double WeightedViolationDelta(bool linear_only,
379 absl::Span<const double> weights, int var,
380 int64_t delta,
381 absl::Span<int64_t> mutable_solution) const;
382
384 return linear_evaluator_;
385 }
386
388 return &linear_evaluator_;
389 }
390
391 // List of the currently violated constraints.
392 // - It is initialized by RecomputeViolatedList()
393 // - And incrementally maintained by UpdateVariableValue()
394 //
395 // The order depends on the algorithm used and shouldn't be relied on.
396 void RecomputeViolatedList(bool linear_only);
397 absl::Span<const int> ViolatedConstraints() const {
398 return violated_constraints_.values();
399 }
400
401 // Returns the number of constraints in ViolatedConstraints containing `var`.
403 return num_violated_constraint_per_var_ignoring_objective_[var];
404 }
405
406 // Indicates if the computed jump value is always the best choice.
408
409 const std::vector<int>& last_update_violation_changes() const {
410 return last_update_violation_changes_;
411 }
412
413 absl::Span<const int> ConstraintToVars(int c) const {
414 if (c < NumLinearConstraints()) {
415 return linear_evaluator_.ConstraintToVars(c);
416 }
417 return absl::MakeConstSpan(constraint_to_vars_[c - NumLinearConstraints()]);
418 }
419
420 // Note that the constraint indexing is different here than in the other
421 // functions.
422 absl::Span<const int> VarToGeneralConstraints(int var) const {
423 return var_to_constraints_[var];
424 }
425 absl::Span<const int> GeneralConstraintToVars(int general_c) const {
426 return constraint_to_vars_[general_c];
427 }
428
429 // TODO(user): Properly account all big time consumers.
430 double DeterministicTime() const {
431 return linear_evaluator_.DeterministicTime() + dtime_;
432 }
433
434 private:
435 void CompileConstraintsAndObjective(
436 const std::vector<bool>& ignored_constraints,
437 const std::vector<ConstraintProto>& additional_constraints);
438
439 void CompileOneConstraint(const ConstraintProto& ct_proto);
440 void BuildVarConstraintGraph();
441 void UpdateViolatedList(int c);
442
443 const CpModelProto& cp_model_;
444 const SatParameters& params_;
445 CpModelProto expanded_constraints_;
446 LinearIncrementalEvaluator linear_evaluator_;
447 std::vector<std::unique_ptr<CompiledConstraint>> constraints_;
448 std::vector<std::vector<int>> var_to_constraints_;
449 std::vector<double> var_to_dtime_estimate_;
450 std::vector<std::vector<int>> constraint_to_vars_;
451 std::vector<bool> jump_value_optimal_;
452 TimeLimit* time_limit_;
453
454 UnsafeDenseSet<int> violated_constraints_;
455 std::vector<int> num_violated_constraint_per_var_ignoring_objective_;
456
457 // Constraint index with changed violations.
458 std::vector<int> last_update_violation_changes_;
459
460 mutable double dtime_ = 0;
461};
462
463// ================================
464// Individual compiled constraints.
465// ================================
466
467// The violation of a bool_xor constraint is 0 or 1.
468class CompiledBoolXorConstraint : public CompiledConstraintWithProto {
469 public:
471 ~CompiledBoolXorConstraint() override = default;
472
473 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
474 int64_t ViolationDelta(
475 int /*var*/, int64_t /*old_value*/,
476 absl::Span<const int64_t> solution_with_new_value) override;
477};
478
479// The violation of a lin_max constraint is:
480// - the sum(max(0, expr_value - target_value) forall expr). This part will be
481// maintained by the linear part.
482// - target_value - max(expressions) if positive.
484 public:
486 ~CompiledLinMaxConstraint() override = default;
487
488 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
489};
490
491// The violation of an int_prod constraint is
492// abs(value(target) - prod(value(expr)).
494 public:
496 ~CompiledIntProdConstraint() override = default;
497
498 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
499};
500
501// The violation of an int_div constraint is
502// abs(value(target) - value(expr0) / value(expr1)).
504 public:
506 ~CompiledIntDivConstraint() override = default;
507
508 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
509};
510
511// The violation of an int_mod constraint is defined as follow:
512//
513// if target and expr0 have the same sign:
514// min(
515// abs(value(target) - (value(expr0) % value(expr1))),
516// abs(value(target)) + abs((value(expr0) % value(expr1)) - value(expr1)),
517// abs(value(expr0) % value(expr1)) + abs(value(target) - value(expr1)),
518// )
519//
520// if target and expr0 have different sign:
521// abs(target) + abs(expr0)
522// Note: the modulo (expr1) is always fixed.
524 public:
526 ~CompiledIntModConstraint() override = default;
527
528 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
529};
530
531// The violation of a all_diff is the number of unordered pairs of expressions
532// with the same value.
534 public:
536 ~CompiledAllDiffConstraint() override = default;
537
538 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
539
540 private:
541 std::vector<int64_t> values_;
542};
543
544// This is more compact and faster to destroy than storing a
545// LinearExpressionProto.
548 const LinearExpressionProto& proto) {
549 if (!proto.vars().empty()) {
550 DCHECK_EQ(proto.vars().size(), 1);
551 var = proto.vars(0);
552 coeff = proto.coeffs(0);
553 }
554 offset = proto.offset();
555 }
556
557 void AppendVarTo(std::vector<int>& result) const {
558 if (coeff != 0) result.push_back(var);
560
561 int var = 0;
562 int64_t coeff = 0;
563 int64_t offset = 0;
566// Special constraint for no overlap between two intervals.
567// We usually expand small no-overlap in n^2 such constraint, so we want to
568// be compact and efficient here.
569template <bool has_enforcement = true>
571 public:
572 struct Interval {
573 explicit Interval(const ConstraintProto& x)
580 const ConstraintProto& x2)
581 : interval1_(x1), interval2_(x2) {
582 if (has_enforcement) {
583 enforcements_.assign(x1.enforcement_literal().begin(),
584 x1.enforcement_literal().end());
585 enforcements_.insert(enforcements_.end(),
586 x2.enforcement_literal().begin(),
587 x2.enforcement_literal().end());
588 gtl::STLSortAndRemoveDuplicates(&enforcements_);
589 }
590 }
591
592 ~CompiledNoOverlapWithTwoIntervals() final = default;
593
594 int64_t ComputeViolation(absl::Span<const int64_t> solution) final {
595 // Optimization hack: If we create a ComputeViolationInternal() that we call
596 // from here and in ViolationDelta(), then the later is not inlined below in
597 // ViolationDelta() where it matter a lot for performance.
598 violation_ = 0;
600 return violation_;
601 }
602
603 int64_t ViolationDelta(
604 int /*var*/, int64_t /*old_value*/,
605 absl::Span<const int64_t> solution_with_new_value) final;
606
607 std::vector<int> UsedVariables(const CpModelProto& model_proto) const final;
608
609 private:
610 std::vector<int> enforcements_;
611 const Interval interval1_;
612 const Interval interval2_;
613};
614
615class CompiledNoOverlap2dConstraint : public CompiledConstraintWithProto {
616 public:
618 const CpModelProto& cp_model);
619 ~CompiledNoOverlap2dConstraint() override = default;
620
621 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
622
623 private:
624 const CpModelProto& cp_model_;
625};
626
627template <bool has_enforcement = true>
629 public:
630 struct Box {
631 Box(const ConstraintProto& x, const ConstraintProto& y)
643 const ConstraintProto& y1,
645 const ConstraintProto& y2)
646 : box1_(x1, y1), box2_(x2, y2) {
647 if (has_enforcement) {
648 enforcements_.assign(x1.enforcement_literal().begin(),
649 x1.enforcement_literal().end());
650 enforcements_.insert(enforcements_.end(),
651 y1.enforcement_literal().begin(),
652 y1.enforcement_literal().end());
653 enforcements_.insert(enforcements_.end(),
654 x2.enforcement_literal().begin(),
655 x2.enforcement_literal().end());
656 enforcements_.insert(enforcements_.end(),
657 y2.enforcement_literal().begin(),
658 y2.enforcement_literal().end());
659 gtl::STLSortAndRemoveDuplicates(&enforcements_);
660 }
661 }
662
663 ~CompiledNoOverlap2dWithTwoBoxes() final = default;
664
665 int64_t ComputeViolation(absl::Span<const int64_t> solution) final {
666 // Optimization hack: If we create a ComputeViolationInternal() that we call
667 // from here and in ViolationDelta(), then the later is not inlined below in
668 // ViolationDelta() where it matter a lot for performance.
669 violation_ = 0;
671 return violation_;
672 }
673
674 // Note(user): this is the same implementation as the base one, but it
675 // avoid one virtual call !
676 int64_t ViolationDelta(
677 int /*var*/, int64_t /*old_value*/,
678 absl::Span<const int64_t> solution_with_new_value) final;
679
680 std::vector<int> UsedVariables(const CpModelProto& model_proto) const final;
681
682 private:
683 std::vector<int> enforcements_;
684 const Box box1_;
685 const Box box2_;
686};
687
688// This can be used to encode reservoir or a cumulative constraints for LS. We
689// have a set of event time, and we use for overall violation the sum of
690// overload over time.
691//
692// This version support an incremental computation when just a few events
693// changes, which is roughly O(n) instead of O(n log n) which makes it
694// significantly faster than recomputing and sorting the profile on each
695// ViolationDelta().
696class CompiledReservoirConstraint : public CompiledConstraint {
697 public:
699 std::vector<std::optional<int>> is_active,
700 std::vector<LinearExpressionProto> times,
701 std::vector<LinearExpressionProto> demands)
702 : capacity_(std::move(capacity)),
703 is_active_(std::move(is_active)),
704 times_(std::move(times)),
705 demands_(std::move(demands)) {
706 const int num_events = times_.size();
707 time_values_.resize(num_events, 0);
708 demand_values_.resize(num_events, 0);
709 InitializeDenseIndexToEvents();
710 }
711
712 // Note that since we have our own ViolationDelta() implementation this is
713 // only used for initialization and our PerformMove(). It is why we set
714 // violations_ here.
715 int64_t ComputeViolation(absl::Span<const int64_t> solution) final {
716 violation_ = BuildProfileAndReturnViolation(solution);
718 }
719
720 void PerformMove(int /*var*/, int64_t /*old_value*/,
721 absl::Span<const int64_t> solution_with_new_value) final {
722 // TODO(user): we could probably be more incremental here, but it is a bit
723 // tricky to get right and not too important since the time is dominated by
724 // evaluating moves, not taking them.
725 ComputeViolation(solution_with_new_value);
726 }
727
728 int64_t ViolationDelta(
729 int var, int64_t /*old_value*/,
730 absl::Span<const int64_t> solution_with_new_value) final {
731 return IncrementalViolation(var, solution_with_new_value) - violation_;
732 }
733
734 std::vector<int> UsedVariables(const CpModelProto& model_proto) const final;
735
736 private:
737 // This works in O(n log n).
738 int64_t BuildProfileAndReturnViolation(absl::Span<const int64_t> solution);
739
740 // This works in O(n) + O(d log d) where d is the number of modified events
741 // compare to the base solution. In most situation it should be O(1).
742 int64_t IncrementalViolation(int var, absl::Span<const int64_t> solution);
743
744 // This is used to speed up IncrementalViolation().
745 void InitializeDenseIndexToEvents();
746 void AppendVariablesForEvent(int i, std::vector<int>* result) const;
747
748 // The const data from the constructor.
749 // Note that is_active_ might be empty if all events are mandatory.
750 const LinearExpressionProto capacity_;
751 const std::vector<std::optional<int>> is_active_;
752 const std::vector<LinearExpressionProto> times_;
753 const std::vector<LinearExpressionProto> demands_;
754
755 // Remap all UsedVariables() to a dense index in [0, num_used_vars).
756 absl::flat_hash_map<int, int> var_to_dense_index_;
757 CompactVectorVector<int, int> dense_index_to_events_;
758
759 struct Event {
760 int64_t time;
761 int64_t demand;
762 bool operator<(const Event& o) const { return time < o.time; }
763 };
764 std::vector<Event> profile_;
765 std::vector<Event> profile_delta_;
766
767 // This is filled by BuildProfileAndReturnViolation() and correspond to the
768 // value in the current solutions.
769 int64_t capacity_value_;
770 std::vector<int64_t> time_values_;
771 std::vector<int64_t> demand_values_;
772};
773
774} // namespace sat
775} // namespace operations_research
776
777#endif // OR_TOOLS_SAT_CONSTRAINT_VIOLATION_H_
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
CompiledAllDiffConstraint(const ConstraintProto &ct_proto)
--— CompiledAllDiffConstraint --—
CompiledBoolXorConstraint(const ConstraintProto &ct_proto)
--— CompiledBoolXorConstraint --—
int64_t ViolationDelta(int, int64_t, absl::Span< const int64_t > solution_with_new_value) override
Returns the delta if var changes from old_value to solution[var].
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
CompiledConstraintWithProto(const ConstraintProto &ct_proto)
--— CompiledConstraintWithProto --—
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
This just returns the variables used by the stored ct_proto_.
View of a generic (non linear) constraint for the LsEvaluator.
int64_t violation() const
The cached violation of this constraint.
virtual std::vector< int > UsedVariables(const CpModelProto &model_proto) const =0
virtual void PerformMove(int var, int64_t old_value, absl::Span< const int64_t > solution_with_new_value)
Updates the violation with the new value.
virtual int64_t ComputeViolation(absl::Span< const int64_t > solution)=0
void InitializeViolation(absl::Span< const int64_t > solution)
Recomputes the violation of the constraint from scratch.
virtual int64_t ViolationDelta(int var, int64_t old_value, absl::Span< const int64_t > solution_with_new_value)
Returns the delta if var changes from old_value to solution[var].
CompiledIntDivConstraint(const ConstraintProto &ct_proto)
--— CompiledIntDivConstraint --—
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
CompiledIntModConstraint(const ConstraintProto &ct_proto)
--— CompiledIntModConstraint --—
CompiledIntProdConstraint(const ConstraintProto &ct_proto)
--— CompiledIntProdConstraint --—
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
CompiledLinMaxConstraint(const ConstraintProto &ct_proto)
--— CompiledLinMaxConstraint --—
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
CompiledNoOverlap2dConstraint(const ConstraintProto &ct_proto, const CpModelProto &cp_model)
int64_t ViolationDelta(int, int64_t, absl::Span< const int64_t > solution_with_new_value) final
int64_t ComputeViolation(absl::Span< const int64_t > solution) final
CompiledNoOverlap2dWithTwoBoxes(const ConstraintProto &x1, const ConstraintProto &y1, const ConstraintProto &x2, const ConstraintProto &y2)
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
int64_t ViolationDelta(int, int64_t, absl::Span< const int64_t > solution_with_new_value) final
--— CompiledNoOverlapWithTwoIntervals --—
int64_t ComputeViolation(absl::Span< const int64_t > solution) final
CompiledNoOverlapWithTwoIntervals(const ConstraintProto &x1, const ConstraintProto &x2)
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
CompiledReservoirConstraint(LinearExpressionProto capacity, std::vector< std::optional< int > > is_active, std::vector< LinearExpressionProto > times, std::vector< LinearExpressionProto > demands)
void PerformMove(int, int64_t, absl::Span< const int64_t > solution_with_new_value) final
Updates the violation with the new value.
int64_t ComputeViolation(absl::Span< const int64_t > solution) final
int64_t ViolationDelta(int var, int64_t, absl::Span< const int64_t > solution_with_new_value) final
Returns the delta if var changes from old_value to solution[var].
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
::int32_t enforcement_literal(int index) const
void UpdateScoreOnWeightUpdate(int c, absl::Span< const int64_t > jump_deltas, absl::Span< double > var_to_score_change)
Also for feasibility jump.
double WeightedViolationDelta(absl::Span< const double > weights, int var, int64_t delta) const
void ComputeInitialActivities(absl::Span< const int64_t > solution)
Compute activities.
void AddLiteral(int ct_index, int lit, int64_t coeff=1)
int NewConstraint(Domain domain)
Returns the index of the new constraint.
double WeightedViolation(absl::Span< const double > weights) const
bool VarIsConsistent(int var) const
Used to DCHECK the state of the evaluator.
void UpdateVariableAndScores(int var, int64_t delta, absl::Span< const double > weights, absl::Span< const int64_t > jump_deltas, absl::Span< double > jump_scores, std::vector< int > *constraints_with_changed_violations)
absl::Span< const int > VariablesAffectedByLastUpdate() const
void AddLinearExpression(int ct_index, const LinearExpressionProto &expr, int64_t multiplier)
void PrecomputeCompactView(absl::Span< const int64_t > var_max_variation)
absl::Span< const int > ConstraintToVars(int c) const
bool ViolationChangeIsConvex(int var) const
Checks if the jump value of a variable is always optimal.
std::vector< int64_t > SlopeBreakpoints(int var, int64_t current_value, const Domain &var_domain) const
void AddTerm(int ct_index, int var, int64_t coeff, int64_t offset=0)
int NumViolatedConstraintsForVarIgnoringObjective(int var) const
Returns the number of constraints in ViolatedConstraints containing var.
double WeightedViolation(absl::Span< const double > weights) const
void ComputeAllNonLinearViolations(absl::Span< const int64_t > solution)
const LinearIncrementalEvaluator & LinearEvaluator()
void UpdateLinearScores(int var, int64_t old_value, int64_t new_value, absl::Span< const double > weights, absl::Span< const int64_t > jump_deltas, absl::Span< double > jump_scores)
Function specific to the linear only feasibility jump.
bool VariableOnlyInLinearConstraintWithConvexViolationChange(int var) const
Indicates if the computed jump value is always the best choice.
void ComputeAllViolations(absl::Span< const int64_t > solution)
Recomputes the violations of all constraints (resp only non-linear one).
void UpdateNonLinearViolations(int var, int64_t old_value, absl::Span< const int64_t > new_solution)
Recomputes the violations of all impacted non linear constraints.
bool ReduceObjectiveBounds(int64_t lb, int64_t ub)
int64_t SumOfViolations()
Simple summation metric for the constraint and objective violations.
int64_t ObjectiveActivity() const
Returns the objective activity in the current state.
absl::Span< const int > ViolatedConstraints() const
absl::Span< const int > VariablesAffectedByLastLinearUpdate() const
LsEvaluator(const CpModelProto &cp_model, const SatParameters &params, TimeLimit *time_limit)
The cp_model must outlive this class.
absl::Span< const int > ConstraintToVars(int c) const
LinearIncrementalEvaluator * MutableLinearEvaluator()
absl::Span< const int > VarToGeneralConstraints(int var) const
double WeightedViolationDelta(bool linear_only, absl::Span< const double > weights, int var, int64_t delta, absl::Span< int64_t > mutable_solution) const
absl::Span< const int > GeneralConstraintToVars(int general_c) const
const std::vector< int > & last_update_violation_changes() const
time_limit
Definition solve.cc:22
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition stl_util.h:55
In SWIG mode, we don't want anything besides these top-level includes.
Select next search node to expand Select next item_i to add this new search node to the search Generate a new search node where item_i is not in the knapsack Check validity of this new partial solution(using propagators) - If valid
DenseSet< T, false > UnsafeDenseSet
Definition dense_set.h:135
ClosedInterval::Iterator end(ClosedInterval interval)
STL namespace.
Box(const ConstraintProto &x, const ConstraintProto &y)
ViewOfAffineLinearExpressionProto(const LinearExpressionProto &proto)