Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
constraint_violation.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 <cstdint>
18#include <cstdlib>
19#include <limits>
20#include <memory>
21#include <optional>
22#include <utility>
23#include <vector>
24
25#include "absl/algorithm/container.h"
26#include "absl/container/flat_hash_map.h"
27#include "absl/container/flat_hash_set.h"
28#include "absl/log/check.h"
29#include "absl/log/log.h"
30#include "absl/types/span.h"
36#include "ortools/sat/util.h"
41
42namespace operations_research {
43namespace sat {
44
45namespace {
46
47int64_t ExprValue(const LinearExpressionProto& expr,
48 absl::Span<const int64_t> solution) {
49 int64_t result = expr.offset();
50 for (int i = 0; i < expr.vars_size(); ++i) {
51 result += solution[expr.vars(i)] * expr.coeffs(i);
52 }
53 return result;
54}
55
56int64_t AffineValue(const ViewOfAffineLinearExpressionProto& affine,
57 absl::Span<const int64_t> solution) {
58 if (affine.coeff == 0) return affine.offset;
59 return affine.coeff * solution[affine.var] + affine.offset;
60}
61
65 result.set_offset(a.offset() + b.offset());
66 result.mutable_vars()->Reserve(a.vars().size() + b.vars().size());
67 result.mutable_coeffs()->Reserve(a.vars().size() + b.vars().size());
68 for (const LinearExpressionProto& p : {a, b}) {
69 for (int i = 0; i < p.vars().size(); ++i) {
70 result.add_vars(p.vars(i));
71 result.add_coeffs(p.coeffs(i));
72 }
73 }
74 return result;
75}
76
77LinearExpressionProto NegatedLinearExpression(LinearExpressionProto a) {
78 LinearExpressionProto result = a;
79 result.set_offset(-a.offset());
80 for (int64_t& coeff : *result.mutable_coeffs()) {
81 coeff = -coeff;
82 }
83 return result;
84}
85
86int64_t ExprMin(const LinearExpressionProto& expr, const CpModelProto& model) {
87 int64_t result = expr.offset();
88 for (int i = 0; i < expr.vars_size(); ++i) {
89 const IntegerVariableProto& var_proto = model.variables(expr.vars(i));
90 if (expr.coeffs(i) > 0) {
91 result += expr.coeffs(i) * var_proto.domain(0);
92 } else {
93 result += expr.coeffs(i) * var_proto.domain(var_proto.domain_size() - 1);
94 }
95 }
96 return result;
97}
98
99int64_t ExprMax(const LinearExpressionProto& expr, const CpModelProto& model) {
100 int64_t result = expr.offset();
101 for (int i = 0; i < expr.vars_size(); ++i) {
102 const IntegerVariableProto& var_proto = model.variables(expr.vars(i));
103 if (expr.coeffs(i) > 0) {
104 result += expr.coeffs(i) * var_proto.domain(var_proto.domain_size() - 1);
105 } else {
106 result += expr.coeffs(i) * var_proto.domain(0);
107 }
108 }
109 return result;
110}
111
112bool LiteralValue(int lit, absl::Span<const int64_t> solution) {
113 if (RefIsPositive(lit)) {
114 return solution[lit] != 0;
115 } else {
116 return solution[PositiveRef(lit)] == 0;
117 }
118}
119
120} // namespace
121
122// ---- LinearIncrementalEvaluator -----
123
125 DCHECK(creation_phase_);
126 domains_.push_back(domain);
127 offsets_.push_back(0);
128 activities_.push_back(0);
129 num_false_enforcement_.push_back(0);
130 distances_.push_back(0);
131 is_violated_.push_back(false);
132 return num_constraints_++;
133}
134
136 DCHECK(creation_phase_);
137 const int var = PositiveRef(lit);
138 if (literal_entries_.size() <= var) {
139 literal_entries_.resize(var + 1);
140 }
141 literal_entries_[var].push_back(
142 {.ct_index = ct_index, .positive = RefIsPositive(lit)});
143}
144
145void LinearIncrementalEvaluator::AddLiteral(int ct_index, int lit,
146 int64_t coeff) {
147 DCHECK(creation_phase_);
148 if (RefIsPositive(lit)) {
149 AddTerm(ct_index, lit, coeff, 0);
150 } else {
151 AddTerm(ct_index, PositiveRef(lit), -coeff, coeff);
152 }
153}
154
155void LinearIncrementalEvaluator::AddTerm(int ct_index, int var, int64_t coeff,
156 int64_t offset) {
157 DCHECK(creation_phase_);
158 DCHECK_GE(var, 0);
159 if (coeff == 0) return;
160
161 if (var_entries_.size() <= var) {
162 var_entries_.resize(var + 1);
163 }
164 if (!var_entries_[var].empty() &&
165 var_entries_[var].back().ct_index == ct_index) {
166 var_entries_[var].back().coefficient += coeff;
167 if (var_entries_[var].back().coefficient == 0) {
168 var_entries_[var].pop_back();
169 }
170 } else {
171 var_entries_[var].push_back({.ct_index = ct_index, .coefficient = coeff});
172 }
173 AddOffset(ct_index, offset);
174 DCHECK(VarIsConsistent(var));
175}
176
177void LinearIncrementalEvaluator::AddOffset(int ct_index, int64_t offset) {
178 DCHECK(creation_phase_);
179 offsets_[ct_index] += offset;
180}
181
183 int ct_index, const LinearExpressionProto& expr, int64_t multiplier) {
184 DCHECK(creation_phase_);
185 AddOffset(ct_index, expr.offset() * multiplier);
186 for (int i = 0; i < expr.vars_size(); ++i) {
187 if (expr.coeffs(i) * multiplier == 0) continue;
188 AddTerm(ct_index, expr.vars(i), expr.coeffs(i) * multiplier);
189 }
190}
191
193 if (var_entries_.size() <= var) return true;
194
195 absl::flat_hash_set<int> visited;
196 for (const Entry& entry : var_entries_[var]) {
197 if (!visited.insert(entry.ct_index).second) return false;
198 }
199 return true;
200}
201
203 absl::Span<const int64_t> solution) {
204 DCHECK(!creation_phase_);
205
206 // Resets the activity as the offset and the number of false enforcement to 0.
207 activities_ = offsets_;
208 last_affected_variables_.ClearAndResize(columns_.size());
209 num_false_enforcement_.assign(num_constraints_, 0);
210
211 // Update these numbers for all columns.
212 const int num_vars = columns_.size();
213 for (int var = 0; var < num_vars; ++var) {
214 const SpanData& data = columns_[var];
215 const int64_t value = solution[var];
216
217 if (value == 0 && data.num_pos_literal > 0) {
218 const int* ct_indices = &ct_buffer_[data.start];
219 for (int k = 0; k < data.num_pos_literal; ++k) {
220 num_false_enforcement_[ct_indices[k]]++;
221 }
222 }
223
224 if (value == 1 && data.num_neg_literal > 0) {
225 const int* ct_indices = &ct_buffer_[data.start + data.num_pos_literal];
226 for (int k = 0; k < data.num_neg_literal; ++k) {
227 num_false_enforcement_[ct_indices[k]]++;
228 }
229 }
230
231 if (value != 0 && data.num_linear_entries > 0) {
232 const int* ct_indices =
233 &ct_buffer_[data.start + data.num_pos_literal + data.num_neg_literal];
234 const int64_t* coeffs = &coeff_buffer_[data.linear_start];
235 for (int k = 0; k < data.num_linear_entries; ++k) {
236 activities_[ct_indices[k]] += coeffs[k] * value;
237 }
238 }
239 }
240
241 // Cache violations (not counting enforcement).
242 for (int c = 0; c < num_constraints_; ++c) {
243 distances_[c] = domains_[c].Distance(activities_[c]);
244 is_violated_[c] = Violation(c) > 0;
245 }
246}
247
249 last_affected_variables_.ClearAndResize(columns_.size());
250}
251
252// Tricky: Here we reuse last_affected_variables_ to reset
253// var_to_score_change. And in particular we need to list all variable whose
254// score changed here. Not just the one for which we have a decrease.
256 int c, absl::Span<const int64_t> jump_deltas,
257 absl::Span<double> var_to_score_change) {
258 if (c >= rows_.size()) return;
259
260 DCHECK_EQ(num_false_enforcement_[c], 0);
261 const SpanData& data = rows_[c];
262
263 // Update enforcement part. Because we only update weight of currently
264 // infeasible constraint, all change are 0 -> 1 transition and change by the
265 // same amount, which is the current distance.
266 const double enforcement_change = static_cast<double>(-distances_[c]);
267 if (enforcement_change != 0.0) {
268 int i = data.start;
269 const int end = data.num_pos_literal + data.num_neg_literal;
270 num_ops_ += end;
271 for (int k = 0; k < end; ++k, ++i) {
272 const int var = row_var_buffer_[i];
273 if (!last_affected_variables_[var]) {
274 var_to_score_change[var] = enforcement_change;
275 last_affected_variables_.Set(var);
276 } else {
277 var_to_score_change[var] += enforcement_change;
278 }
279 }
280 }
281
282 // Update linear part.
283 if (data.num_linear_entries > 0) {
284 const int* row_vars = &row_var_buffer_[data.start + data.num_pos_literal +
285 data.num_neg_literal];
286 const int64_t* row_coeffs = &row_coeff_buffer_[data.linear_start];
287 num_ops_ += 2 * data.num_linear_entries;
288
289 // Computing general Domain distance is slow.
290 // TODO(user): optimize even more for one sided constraints.
291 // Note(user): I tried to factor the two usage of this, but it is slower.
292 const Domain& rhs = domains_[c];
293 const int64_t rhs_min = rhs.Min();
294 const int64_t rhs_max = rhs.Max();
295 const bool is_simple = rhs.NumIntervals() == 2;
296 const auto violation = [&rhs, rhs_min, rhs_max, is_simple](int64_t v) {
297 if (v >= rhs_max) {
298 return v - rhs_max;
299 } else if (v <= rhs_min) {
300 return rhs_min - v;
301 } else {
302 return is_simple ? int64_t{0} : rhs.Distance(v);
303 }
304 };
305
306 const int64_t old_distance = distances_[c];
307 const int64_t activity = activities_[c];
308 for (int k = 0; k < data.num_linear_entries; ++k) {
309 const int var = row_vars[k];
310 const int64_t coeff = row_coeffs[k];
311 const int64_t diff =
312 violation(activity + coeff * jump_deltas[var]) - old_distance;
313 if (!last_affected_variables_[var]) {
314 var_to_score_change[var] = static_cast<double>(diff);
315 last_affected_variables_.Set(var);
316 } else {
317 var_to_score_change[var] += static_cast<double>(diff);
318 }
319 }
320 }
321}
322
323void LinearIncrementalEvaluator::UpdateScoreOnNewlyEnforced(
324 int c, double weight, absl::Span<const int64_t> jump_deltas,
325 absl::Span<double> jump_scores) {
326 const SpanData& data = rows_[c];
327
328 // Everyone else had a zero cost transition that now become enforced ->
329 // unenforced. So they all have better score.
330 const double weight_time_violation =
331 weight * static_cast<double>(distances_[c]);
332 if (weight_time_violation > 0.0) {
333 int i = data.start;
334 const int end = data.num_pos_literal + data.num_neg_literal;
335 num_ops_ += end;
336 for (int k = 0; k < end; ++k, ++i) {
337 const int var = row_var_buffer_[i];
338 jump_scores[var] -= weight_time_violation;
339 last_affected_variables_.Set(var);
340 }
341 }
342
343 // Update linear part! It was zero and is now a diff.
344 {
345 int i = data.start + data.num_pos_literal + data.num_neg_literal;
346 int j = data.linear_start;
347 num_ops_ += 2 * data.num_linear_entries;
348 const int64_t old_distance = distances_[c];
349 for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
350 const int var = row_var_buffer_[i];
351 const int64_t coeff = row_coeff_buffer_[j];
352 const int64_t new_distance =
353 domains_[c].Distance(activities_[c] + coeff * jump_deltas[var]);
354 jump_scores[var] +=
355 weight * static_cast<double>(new_distance - old_distance);
356 last_affected_variables_.Set(var);
357 }
358 }
359}
360
361void LinearIncrementalEvaluator::UpdateScoreOnNewlyUnenforced(
362 int c, double weight, absl::Span<const int64_t> jump_deltas,
363 absl::Span<double> jump_scores) {
364 const SpanData& data = rows_[c];
365
366 // Everyone else had a enforced -> unenforced transition that now become zero.
367 // So they all have worst score, and we don't need to update
368 // last_affected_variables_.
369 const double weight_time_violation =
370 weight * static_cast<double>(distances_[c]);
371 if (weight_time_violation > 0.0) {
372 int i = data.start;
373 const int end = data.num_pos_literal + data.num_neg_literal;
374 num_ops_ += end;
375 for (int k = 0; k < end; ++k, ++i) {
376 const int var = row_var_buffer_[i];
377 jump_scores[var] += weight_time_violation;
378 }
379 }
380
381 // Update linear part! It had a diff and is now zero.
382 {
383 int i = data.start + data.num_pos_literal + data.num_neg_literal;
384 int j = data.linear_start;
385 num_ops_ += 2 * data.num_linear_entries;
386 const int64_t old_distance = distances_[c];
387 for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
388 const int var = row_var_buffer_[i];
389 const int64_t coeff = row_coeff_buffer_[j];
390 const int64_t new_distance =
391 domains_[c].Distance(activities_[c] + coeff * jump_deltas[var]);
392 jump_scores[var] -=
393 weight * static_cast<double>(new_distance - old_distance);
394 last_affected_variables_.Set(var);
395 }
396 }
397}
398
399// We just need to modify the old/new transition that decrease the number of
400// enforcement literal at false.
401void LinearIncrementalEvaluator::UpdateScoreOfEnforcementIncrease(
402 int c, double score_change, absl::Span<const int64_t> jump_deltas,
403 absl::Span<double> jump_scores) {
404 if (score_change == 0.0) return;
405
406 const SpanData& data = rows_[c];
407 int i = data.start;
408 num_ops_ += data.num_pos_literal;
409 for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
410 const int var = row_var_buffer_[i];
411 if (jump_deltas[var] == 1) {
412 jump_scores[var] += score_change;
413 if (score_change < 0.0) {
414 last_affected_variables_.Set(var);
415 }
416 }
417 }
418 num_ops_ += data.num_neg_literal;
419 for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
420 const int var = row_var_buffer_[i];
421 if (jump_deltas[var] == -1) {
422 jump_scores[var] += score_change;
423 if (score_change < 0.0) {
424 last_affected_variables_.Set(var);
425 }
426 }
427 }
428}
429
430void LinearIncrementalEvaluator::UpdateScoreOnActivityChange(
431 int c, double weight, int64_t activity_delta,
432 absl::Span<const int64_t> jump_deltas, absl::Span<double> jump_scores) {
433 if (activity_delta == 0) return;
434 const SpanData& data = rows_[c];
435
436 // In some cases, we can know that the score of all the involved variable
437 // will not change. This is the case if whatever 1 variable change the
438 // violation delta before/after is the same.
439 //
440 // TODO(user): Maintain more precise bounds.
441 // - We could easily compute on each ComputeInitialActivities() the
442 // maximum increase/decrease per variable, and take the max as each
443 // variable changes?
444 // - Know if a constraint is only <= or >= !
445 const int64_t old_activity = activities_[c];
446 const int64_t new_activity = old_activity + activity_delta;
447 int64_t min_range;
448 int64_t max_range;
449 if (new_activity > old_activity) {
450 min_range = old_activity - row_max_variations_[c];
451 max_range = new_activity + row_max_variations_[c];
452 } else {
453 min_range = new_activity - row_max_variations_[c];
454 max_range = old_activity + row_max_variations_[c];
455 }
456
457 // If the violation delta was zero and will still always be zero, we can skip.
458 if (Domain(min_range, max_range).IsIncludedIn(domains_[c])) return;
459
460 // Enforcement is always enforced -> un-enforced.
461 // So it was -weight_time_distance and is now -weight_time_new_distance.
462 const double delta =
463 -weight *
464 static_cast<double>(domains_[c].Distance(new_activity) - distances_[c]);
465 if (delta != 0.0) {
466 int i = data.start;
467 const int end = data.num_pos_literal + data.num_neg_literal;
468 num_ops_ += end;
469 for (int k = 0; k < end; ++k, ++i) {
470 const int var = row_var_buffer_[i];
471 jump_scores[var] += delta;
472 if (delta < 0.0) {
473 last_affected_variables_.Set(var);
474 }
475 }
476 }
477
478 // If we are infeasible and no move can correct it, both old_b - old_a and
479 // new_b - new_a will have the same value. We only needed to update the
480 // violation of the enforced literal.
481 if (min_range >= domains_[c].Max() || max_range <= domains_[c].Min()) return;
482
483 // Update linear part.
484 if (data.num_linear_entries > 0) {
485 const int* row_vars = &row_var_buffer_[data.start + data.num_pos_literal +
486 data.num_neg_literal];
487 const int64_t* row_coeffs = &row_coeff_buffer_[data.linear_start];
488 num_ops_ += 2 * data.num_linear_entries;
489
490 // Computing general Domain distance is slow.
491 // TODO(user): optimize even more for one sided constraints.
492 // Note(user): I tried to factor the two usage of this, but it is slower.
493 const Domain& rhs = domains_[c];
494 const int64_t rhs_min = rhs.Min();
495 const int64_t rhs_max = rhs.Max();
496 const bool is_simple = rhs.NumIntervals() == 2;
497 const auto violation = [&rhs, rhs_min, rhs_max, is_simple](int64_t v) {
498 if (v >= rhs_max) {
499 return v - rhs_max;
500 } else if (v <= rhs_min) {
501 return rhs_min - v;
502 } else {
503 return is_simple ? int64_t{0} : rhs.Distance(v);
504 }
505 };
506
507 const int64_t old_a_minus_new_a =
508 distances_[c] - domains_[c].Distance(new_activity);
509 for (int k = 0; k < data.num_linear_entries; ++k) {
510 const int var = row_vars[k];
511 const int64_t impact = row_coeffs[k] * jump_deltas[var];
512 const int64_t old_b = violation(old_activity + impact);
513 const int64_t new_b = violation(new_activity + impact);
514
515 // The old score was:
516 // weight * static_cast<double>(old_b - old_a);
517 // the new score is
518 // weight * static_cast<double>(new_b - new_a); so the diff is:
519 // weight * static_cast<double>(new_b - new_a - old_b + old_a)
520 const int64_t diff = old_a_minus_new_a + new_b - old_b;
521
522 // TODO(user): If a variable is at its lower (resp. upper) bound, then
523 // we know that the score will always move in the same direction, so we
524 // might skip the last_affected_variables_ update.
525 jump_scores[var] += weight * static_cast<double>(diff);
526 last_affected_variables_.Set(var);
527 }
528 }
529}
530
531// Note that the code assumes that a column has no duplicates ct indices.
533 int var, int64_t delta, absl::Span<const double> weights,
534 absl::Span<const int64_t> jump_deltas, absl::Span<double> jump_scores,
535 std::vector<int>* constraints_with_changed_violation) {
536 DCHECK(!creation_phase_);
537 DCHECK_NE(delta, 0);
538 if (var >= columns_.size()) return;
539
540 const SpanData& data = columns_[var];
541 int i = data.start;
542 num_ops_ += data.num_pos_literal;
543 for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
544 const int c = ct_buffer_[i];
545 const int64_t v0 = Violation(c);
546 if (delta == 1) {
547 num_false_enforcement_[c]--;
548 DCHECK_GE(num_false_enforcement_[c], 0);
549 if (num_false_enforcement_[c] == 0) {
550 UpdateScoreOnNewlyEnforced(c, weights[c], jump_deltas, jump_scores);
551 } else if (num_false_enforcement_[c] == 1) {
552 const double enforcement_change =
553 weights[c] * static_cast<double>(distances_[c]);
554 UpdateScoreOfEnforcementIncrease(c, enforcement_change, jump_deltas,
555 jump_scores);
556 }
557 } else {
558 num_false_enforcement_[c]++;
559 if (num_false_enforcement_[c] == 1) {
560 UpdateScoreOnNewlyUnenforced(c, weights[c], jump_deltas, jump_scores);
561 } else if (num_false_enforcement_[c] == 2) {
562 const double enforcement_change =
563 weights[c] * static_cast<double>(distances_[c]);
564 UpdateScoreOfEnforcementIncrease(c, -enforcement_change, jump_deltas,
565 jump_scores);
566 }
567 }
568 const int64_t v1 = Violation(c);
569 is_violated_[c] = v1 > 0;
570 if (v1 != v0) {
571 constraints_with_changed_violation->push_back(c);
572 }
573 }
574 num_ops_ += data.num_neg_literal;
575 for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
576 const int c = ct_buffer_[i];
577 const int64_t v0 = Violation(c);
578 if (delta == -1) {
579 num_false_enforcement_[c]--;
580 DCHECK_GE(num_false_enforcement_[c], 0);
581 if (num_false_enforcement_[c] == 0) {
582 UpdateScoreOnNewlyEnforced(c, weights[c], jump_deltas, jump_scores);
583 } else if (num_false_enforcement_[c] == 1) {
584 const double enforcement_change =
585 weights[c] * static_cast<double>(distances_[c]);
586 UpdateScoreOfEnforcementIncrease(c, enforcement_change, jump_deltas,
587 jump_scores);
588 }
589 } else {
590 num_false_enforcement_[c]++;
591 if (num_false_enforcement_[c] == 1) {
592 UpdateScoreOnNewlyUnenforced(c, weights[c], jump_deltas, jump_scores);
593 } else if (num_false_enforcement_[c] == 2) {
594 const double enforcement_change =
595 weights[c] * static_cast<double>(distances_[c]);
596 UpdateScoreOfEnforcementIncrease(c, -enforcement_change, jump_deltas,
597 jump_scores);
598 }
599 }
600 const int64_t v1 = Violation(c);
601 is_violated_[c] = v1 > 0;
602 if (v1 != v0) {
603 constraints_with_changed_violation->push_back(c);
604 }
605 }
606 int j = data.linear_start;
607 num_ops_ += 2 * data.num_linear_entries;
608 for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
609 const int c = ct_buffer_[i];
610 const int64_t v0 = Violation(c);
611 const int64_t coeff = coeff_buffer_[j];
612
613 if (num_false_enforcement_[c] == 1) {
614 // Only the 1 -> 0 are impacted.
615 // This is the same as the 1->2 transition, but the old 1->0 needs to
616 // be changed from - weight * distance to - weight * new_distance.
617 const int64_t new_distance =
618 domains_[c].Distance(activities_[c] + coeff * delta);
619 if (new_distance != distances_[c]) {
620 UpdateScoreOfEnforcementIncrease(
621 c, -weights[c] * static_cast<double>(distances_[c] - new_distance),
622 jump_deltas, jump_scores);
623 }
624 } else if (num_false_enforcement_[c] == 0) {
625 UpdateScoreOnActivityChange(c, weights[c], coeff * delta, jump_deltas,
626 jump_scores);
627 }
628
629 activities_[c] += coeff * delta;
630 distances_[c] = domains_[c].Distance(activities_[c]);
631 const int64_t v1 = Violation(c);
632 is_violated_[c] = v1 > 0;
633 if (v1 != v0) {
634 constraints_with_changed_violation->push_back(c);
635 }
636 }
637}
638
640 return activities_[c];
641}
642
644 return num_false_enforcement_[c] > 0 ? 0 : distances_[c];
645}
646
648 DCHECK_EQ(is_violated_[c], Violation(c) > 0);
649 return is_violated_[c];
650}
651
652bool LinearIncrementalEvaluator::ReduceBounds(int c, int64_t lb, int64_t ub) {
653 if (domains_[c].Min() >= lb && domains_[c].Max() <= ub) return false;
654 domains_[c] = domains_[c].IntersectionWith(Domain(lb, ub));
655 distances_[c] = domains_[c].Distance(activities_[c]);
656 return true;
657}
658
660 absl::Span<const double> weights) const {
661 double result = 0.0;
662 DCHECK_GE(weights.size(), num_constraints_);
663 for (int c = 0; c < num_constraints_; ++c) {
664 if (num_false_enforcement_[c] > 0) continue;
665 result += weights[c] * static_cast<double>(distances_[c]);
666 }
667 return result;
668}
669
670// Most of the time is spent in this function.
671//
672// TODO(user): We can safely abort early if we know that delta will be >= 0.
673// TODO(user): Maybe we can compute an absolute value instead of removing
674// old_distance.
676 absl::Span<const double> weights, int var, int64_t delta) const {
677 DCHECK_NE(delta, 0);
678 if (var >= columns_.size()) return 0.0;
679 const SpanData& data = columns_[var];
680
681 int i = data.start;
682 double result = 0.0;
683 num_ops_ += data.num_pos_literal;
684 for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
685 const int c = ct_buffer_[i];
686 if (num_false_enforcement_[c] == 0) {
687 // Since delta != 0, we are sure this is an enforced -> unenforced change.
688 DCHECK_EQ(delta, -1);
689 result -= weights[c] * static_cast<double>(distances_[c]);
690 } else {
691 if (delta == 1 && num_false_enforcement_[c] == 1) {
692 result += weights[c] * static_cast<double>(distances_[c]);
693 }
694 }
695 }
696
697 num_ops_ += data.num_neg_literal;
698 for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
699 const int c = ct_buffer_[i];
700 if (num_false_enforcement_[c] == 0) {
701 // Since delta != 0, we are sure this is an enforced -> unenforced change.
702 DCHECK_EQ(delta, 1);
703 result -= weights[c] * static_cast<double>(distances_[c]);
704 } else {
705 if (delta == -1 && num_false_enforcement_[c] == 1) {
706 result += weights[c] * static_cast<double>(distances_[c]);
707 }
708 }
709 }
710
711 int j = data.linear_start;
712 num_ops_ += 2 * data.num_linear_entries;
713 for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
714 const int c = ct_buffer_[i];
715 if (num_false_enforcement_[c] > 0) continue;
716 const int64_t coeff = coeff_buffer_[j];
717 const int64_t old_distance = distances_[c];
718 const int64_t new_distance =
719 domains_[c].Distance(activities_[c] + coeff * delta);
720 result += weights[c] * static_cast<double>(new_distance - old_distance);
721 }
722
723 return result;
724}
725
727 if (var >= columns_.size()) return false;
728 for (const int c : VarToConstraints(var)) {
729 if (Violation(c) > 0) return true;
730 }
731 return false;
732}
733
735 int var, int64_t current_value, const Domain& var_domain) const {
736 std::vector<int64_t> result = var_domain.FlattenedIntervals();
737 if (var_domain.Size() <= 2 || var >= columns_.size()) return result;
738
739 const SpanData& data = columns_[var];
740 int i = data.start + data.num_pos_literal + data.num_neg_literal;
741 int j = data.linear_start;
742 for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
743 const int c = ct_buffer_[i];
744 if (num_false_enforcement_[c] > 0) continue;
745
746 // We only consider min / max.
747 // There is a change when we cross the slack.
748 // TODO(user): Deal with holes?
749 const int64_t coeff = coeff_buffer_[j];
750 const int64_t activity = activities_[c] - current_value * coeff;
751
752 const int64_t slack_min = CapSub(domains_[c].Min(), activity);
753 const int64_t slack_max = CapSub(domains_[c].Max(), activity);
754 if (slack_min != std::numeric_limits<int64_t>::min()) {
755 const int64_t ceil_bp = MathUtil::CeilOfRatio(slack_min, coeff);
756 if (ceil_bp != result.back() && var_domain.Contains(ceil_bp)) {
757 result.push_back(ceil_bp);
758 }
759 const int64_t floor_bp = MathUtil::FloorOfRatio(slack_min, coeff);
760 if (floor_bp != result.back() && var_domain.Contains(floor_bp)) {
761 result.push_back(floor_bp);
762 }
763 }
764 if (slack_min != slack_max &&
765 slack_max != std::numeric_limits<int64_t>::min()) {
766 const int64_t ceil_bp = MathUtil::CeilOfRatio(slack_max, coeff);
767 if (ceil_bp != result.back() && var_domain.Contains(ceil_bp)) {
768 result.push_back(ceil_bp);
769 }
770 const int64_t floor_bp = MathUtil::FloorOfRatio(slack_max, coeff);
771 if (floor_bp != result.back() && var_domain.Contains(floor_bp)) {
772 result.push_back(floor_bp);
773 }
774 }
775 }
776
778 return result;
779}
780
782 absl::Span<const int64_t> var_max_variation) {
783 creation_phase_ = false;
784 if (num_constraints_ == 0) return;
785
786 // Compute the total size.
787 // Note that at this point the constraint indices are not "encoded" yet.
788 int total_size = 0;
789 int total_linear_size = 0;
790 tmp_row_sizes_.assign(num_constraints_, 0);
791 tmp_row_num_positive_literals_.assign(num_constraints_, 0);
792 tmp_row_num_negative_literals_.assign(num_constraints_, 0);
793 tmp_row_num_linear_entries_.assign(num_constraints_, 0);
794 for (const auto& column : literal_entries_) {
795 total_size += column.size();
796 for (const auto [c, is_positive] : column) {
797 tmp_row_sizes_[c]++;
798 if (is_positive) {
799 tmp_row_num_positive_literals_[c]++;
800 } else {
801 tmp_row_num_negative_literals_[c]++;
802 }
803 }
804 }
805
806 row_max_variations_.assign(num_constraints_, 0);
807 for (int var = 0; var < var_entries_.size(); ++var) {
808 const int64_t range = var_max_variation[var];
809 const auto& column = var_entries_[var];
810 total_size += column.size();
811 total_linear_size += column.size();
812 for (const auto [c, coeff] : column) {
813 tmp_row_sizes_[c]++;
814 tmp_row_num_linear_entries_[c]++;
815 row_max_variations_[c] =
816 std::max(row_max_variations_[c], range * std::abs(coeff));
817 }
818 }
819
820 // Compactify for faster WeightedViolationDelta().
821 ct_buffer_.reserve(total_size);
822 coeff_buffer_.reserve(total_linear_size);
823 columns_.resize(std::max(literal_entries_.size(), var_entries_.size()));
824 for (int var = 0; var < columns_.size(); ++var) {
825 columns_[var].start = static_cast<int>(ct_buffer_.size());
826 columns_[var].linear_start = static_cast<int>(coeff_buffer_.size());
827 if (var < literal_entries_.size()) {
828 for (const auto [c, is_positive] : literal_entries_[var]) {
829 if (is_positive) {
830 columns_[var].num_pos_literal++;
831 ct_buffer_.push_back(c);
832 }
833 }
834 for (const auto [c, is_positive] : literal_entries_[var]) {
835 if (!is_positive) {
836 columns_[var].num_neg_literal++;
837 ct_buffer_.push_back(c);
838 }
839 }
840 }
841 if (var < var_entries_.size()) {
842 for (const auto [c, coeff] : var_entries_[var]) {
843 columns_[var].num_linear_entries++;
844 ct_buffer_.push_back(c);
845 coeff_buffer_.push_back(coeff);
846 }
847 }
848 }
849
850 // We do not need var_entries_ or literal_entries_ anymore.
851 //
852 // TODO(user): We could delete them before. But at the time of this
853 // optimization, I didn't want to change the behavior of the algorithm at all.
854 gtl::STLClearObject(&var_entries_);
855 gtl::STLClearObject(&literal_entries_);
856
857 // Initialize the SpanData.
858 // Transform tmp_row_sizes_ to starts in the row_var_buffer_.
859 // Transform tmp_row_num_linear_entries_ to starts in the row_coeff_buffer_.
860 int offset = 0;
861 int linear_offset = 0;
862 rows_.resize(num_constraints_);
863 for (int c = 0; c < num_constraints_; ++c) {
864 rows_[c].num_pos_literal = tmp_row_num_positive_literals_[c];
865 rows_[c].num_neg_literal = tmp_row_num_negative_literals_[c];
866 rows_[c].num_linear_entries = tmp_row_num_linear_entries_[c];
867
868 rows_[c].start = offset;
869 offset += tmp_row_sizes_[c];
870 tmp_row_sizes_[c] = rows_[c].start;
871
872 rows_[c].linear_start = linear_offset;
873 linear_offset += tmp_row_num_linear_entries_[c];
874 tmp_row_num_linear_entries_[c] = rows_[c].linear_start;
875 }
876 DCHECK_EQ(offset, total_size);
877 DCHECK_EQ(linear_offset, total_linear_size);
878
879 // Copy data.
880 row_var_buffer_.resize(total_size);
881 row_coeff_buffer_.resize(total_linear_size);
882 for (int var = 0; var < columns_.size(); ++var) {
883 const SpanData& data = columns_[var];
884 int i = data.start;
885 for (int k = 0; k < data.num_pos_literal; ++i, ++k) {
886 const int c = ct_buffer_[i];
887 row_var_buffer_[tmp_row_sizes_[c]++] = var;
888 }
889 }
890 for (int var = 0; var < columns_.size(); ++var) {
891 const SpanData& data = columns_[var];
892 int i = data.start + data.num_pos_literal;
893 for (int k = 0; k < data.num_neg_literal; ++i, ++k) {
894 const int c = ct_buffer_[i];
895 row_var_buffer_[tmp_row_sizes_[c]++] = var;
896 }
897 }
898 for (int var = 0; var < columns_.size(); ++var) {
899 const SpanData& data = columns_[var];
900 int i = data.start + data.num_pos_literal + data.num_neg_literal;
901 int j = data.linear_start;
902 for (int k = 0; k < data.num_linear_entries; ++i, ++j, ++k) {
903 const int c = ct_buffer_[i];
904 row_var_buffer_[tmp_row_sizes_[c]++] = var;
905 row_coeff_buffer_[tmp_row_num_linear_entries_[c]++] = coeff_buffer_[j];
906 }
907 }
908
909 cached_deltas_.assign(columns_.size(), 0);
910 cached_scores_.assign(columns_.size(), 0);
911 last_affected_variables_.ClearAndResize(columns_.size());
912}
913
915 for (const int c : VarToConstraints(var)) {
916 if (domains_[c].NumIntervals() > 2) return false;
917 }
918 return true;
919}
920
921// ----- CompiledConstraint -----
922
924 absl::Span<const int64_t> solution) {
926}
927
929 int var, int64_t old_value,
930 absl::Span<const int64_t> solution_with_new_value) {
931 violation_ += ViolationDelta(var, old_value, solution_with_new_value);
932}
933
935 absl::Span<const int64_t> solution) {
937}
938
939// ----- CompiledConstraintWithProto -----
940
944
946 const CpModelProto& model_proto) const {
947 std::vector<int> result = sat::UsedVariables(ct_proto_);
948 for (const int i_var : UsedIntervals(ct_proto_)) {
949 const ConstraintProto& interval_proto = model_proto.constraints(i_var);
950 for (const int var : sat::UsedVariables(interval_proto)) {
951 result.push_back(var);
952 }
953 }
955 result.shrink_to_fit();
956 return result;
957}
958
959// ----- CompiledBoolXorConstraint -----
960
964
966 absl::Span<const int64_t> solution) {
967 int64_t sum_of_literals = 0;
968 for (const int lit : ct_proto().bool_xor().literals()) {
969 sum_of_literals += LiteralValue(lit, solution);
970 }
971 return 1 - (sum_of_literals % 2);
972}
973
975 int /*var*/, int64_t /*old_value*/,
976 absl::Span<const int64_t> /*solution_with_new_value*/) {
977 return violation() == 0 ? 1 : -1;
978}
979
980// ----- CompiledLinMaxConstraint -----
981
985
987 absl::Span<const int64_t> solution) {
988 const int64_t target_value =
989 ExprValue(ct_proto().lin_max().target(), solution);
990 int64_t max_of_expressions = std::numeric_limits<int64_t>::min();
991 for (const LinearExpressionProto& expr : ct_proto().lin_max().exprs()) {
992 const int64_t expr_value = ExprValue(expr, solution);
993 max_of_expressions = std::max(max_of_expressions, expr_value);
994 }
995 return std::max(target_value - max_of_expressions, int64_t{0});
996}
997
998// ----- CompiledIntProdConstraint -----
999
1003
1005 absl::Span<const int64_t> solution) {
1006 const int64_t target_value =
1007 ExprValue(ct_proto().int_prod().target(), solution);
1008 int64_t prod_value = 1;
1009 for (const LinearExpressionProto& expr : ct_proto().int_prod().exprs()) {
1010 prod_value *= ExprValue(expr, solution);
1011 }
1012 return std::abs(target_value - prod_value);
1013}
1014
1015// ----- CompiledIntDivConstraint -----
1016
1020
1022 absl::Span<const int64_t> solution) {
1023 const int64_t target_value =
1024 ExprValue(ct_proto().int_div().target(), solution);
1025 DCHECK_EQ(ct_proto().int_div().exprs_size(), 2);
1026 const int64_t div_value = ExprValue(ct_proto().int_div().exprs(0), solution) /
1027 ExprValue(ct_proto().int_div().exprs(1), solution);
1028 return std::abs(target_value - div_value);
1029}
1030
1031// ----- CompiledIntModConstraint -----
1032
1036
1038 absl::Span<const int64_t> solution) {
1039 const int64_t target_value =
1040 ExprValue(ct_proto().int_mod().target(), solution);
1041 DCHECK_EQ(ct_proto().int_mod().exprs_size(), 2);
1042 // Note: The violation computation assumes the modulo is constant.
1043 const int64_t expr_value = ExprValue(ct_proto().int_mod().exprs(0), solution);
1044 const int64_t mod_value = ExprValue(ct_proto().int_mod().exprs(1), solution);
1045 const int64_t rhs = expr_value % mod_value;
1046 if ((expr_value >= 0 && target_value >= 0) ||
1047 (expr_value <= 0 && target_value <= 0)) {
1048 // Easy case.
1049 return std::min({std::abs(target_value - rhs),
1050 std::abs(target_value) + std::abs(mod_value - rhs),
1051 std::abs(rhs) + std::abs(mod_value - target_value)});
1052 } else {
1053 // Different signs.
1054 // We use the sum of the absolute value to have a better gradient.
1055 // We could also use the min of target_move and the expr_move.
1056 return std::abs(target_value) + std::abs(expr_value);
1057 }
1058}
1059
1060// ----- CompiledAllDiffConstraint -----
1061
1065
1067 absl::Span<const int64_t> solution) {
1068 values_.clear();
1069 for (const LinearExpressionProto& expr : ct_proto().all_diff().exprs()) {
1070 values_.push_back(ExprValue(expr, solution));
1071 }
1072 std::sort(values_.begin(), values_.end());
1073
1074 int64_t value = values_[0];
1075 int counter = 1;
1076 int64_t violation = 0;
1077 for (int i = 1; i < values_.size(); ++i) {
1078 const int64_t new_value = values_[i];
1079 if (new_value == value) {
1080 counter++;
1081 } else {
1082 violation += counter * (counter - 1) / 2;
1083 counter = 1;
1084 value = new_value;
1085 }
1086 }
1087 violation += counter * (counter - 1) / 2;
1088 return violation;
1089}
1090
1091// ----- CompiledNoOverlapWithTwoIntervals -----
1092
1093template <bool has_enforcement>
1095 int /*var*/, int64_t /*old_value*/, absl::Span<const int64_t> solution) {
1096 if (has_enforcement) {
1097 for (const int lit : enforcements_) {
1098 if (!LiteralValue(lit, solution)) return -violation_;
1099 }
1100 }
1101
1102 const int64_t s1 = AffineValue(interval1_.start, solution);
1103 const int64_t e1 = AffineValue(interval1_.end, solution);
1104 const int64_t s2 = AffineValue(interval2_.start, solution);
1105 const int64_t e2 = AffineValue(interval2_.end, solution);
1106 const int64_t repair = std::min(e2 - s1, e1 - s2);
1107 if (repair <= 0) return -violation_; // disjoint
1108 return repair - violation_;
1109}
1110
1111template <bool has_enforcement>
1112std::vector<int>
1114 const CpModelProto& /*model_proto*/) const {
1115 std::vector<int> result;
1116 if (has_enforcement) {
1117 for (const int ref : enforcements_) result.push_back(PositiveRef(ref));
1118 }
1119 interval1_.start.AppendVarTo(result);
1120 interval1_.end.AppendVarTo(result);
1121 interval2_.start.AppendVarTo(result);
1122 interval2_.end.AppendVarTo(result);
1124 result.shrink_to_fit();
1125 return result;
1126}
1127
1128// ----- CompiledNoOverlap2dConstraint -----
1129
1131 const ConstraintProto& interval2,
1132 absl::Span<const int64_t> solution) {
1133 for (const int lit : interval1.enforcement_literal()) {
1134 if (!LiteralValue(lit, solution)) return 0;
1135 }
1136 for (const int lit : interval2.enforcement_literal()) {
1137 if (!LiteralValue(lit, solution)) return 0;
1138 }
1139
1140 const int64_t start1 = ExprValue(interval1.interval().start(), solution);
1141 const int64_t end1 = ExprValue(interval1.interval().end(), solution);
1142
1143 const int64_t start2 = ExprValue(interval2.interval().start(), solution);
1144 const int64_t end2 = ExprValue(interval2.interval().end(), solution);
1145
1146 if (start1 >= end2 || start2 >= end1) return 0; // Disjoint.
1147
1148 // We force a min cost of 1 to cover the case where a interval of size 0 is in
1149 // the middle of another interval.
1150 return std::max(std::min(std::min(end2 - start2, end1 - start1),
1151 std::min(end2 - start1, end1 - start2)),
1152 int64_t{1});
1153}
1154
1156 const ConstraintProto& interval2,
1157 absl::Span<const int64_t> solution) {
1158 for (const int lit : interval1.enforcement_literal()) {
1159 if (!LiteralValue(lit, solution)) return 0;
1160 }
1161 for (const int lit : interval2.enforcement_literal()) {
1162 if (!LiteralValue(lit, solution)) return 0;
1163 }
1164
1165 const int64_t start1 = ExprValue(interval1.interval().start(), solution);
1166 const int64_t end1 = ExprValue(interval1.interval().end(), solution);
1167
1168 const int64_t start2 = ExprValue(interval2.interval().start(), solution);
1169 const int64_t end2 = ExprValue(interval2.interval().end(), solution);
1170
1171 return std::max(std::min(end2 - start1, end1 - start2), int64_t{0});
1172}
1173
1177
1179 absl::Span<const int64_t> solution) {
1180 DCHECK_GE(ct_proto().no_overlap_2d().x_intervals_size(), 2);
1181 const int size = ct_proto().no_overlap_2d().x_intervals_size();
1182
1183 int64_t violation = 0;
1184 for (int i = 0; i + 1 < size; ++i) {
1185 const ConstraintProto& x_i =
1186 cp_model_.constraints(ct_proto().no_overlap_2d().x_intervals(i));
1187 const ConstraintProto& y_i =
1188 cp_model_.constraints(ct_proto().no_overlap_2d().y_intervals(i));
1189 for (int j = i + 1; j < size; ++j) {
1190 const ConstraintProto& x_j =
1191 cp_model_.constraints(ct_proto().no_overlap_2d().x_intervals(j));
1192 const ConstraintProto& y_j =
1193 cp_model_.constraints(ct_proto().no_overlap_2d().y_intervals(j));
1194
1195 // TODO(user): Experiment with
1196 // violation +=
1197 // std::max(std::min(NoOverlapMinRepairDistance(x_i, x_j, solution),
1198 // NoOverlapMinRepairDistance(y_i, y_j, solution)),
1199 // int64_t{0});
1200 // Currently, the effect is unclear on 2d packing problems.
1201 violation +=
1202 std::max(std::min(NoOverlapMinRepairDistance(x_i, x_j, solution) *
1205 OverlapOfTwoIntervals(x_i, x_j, solution)),
1206 int64_t{0});
1207 }
1208 }
1209 return violation;
1210}
1211
1212template <bool has_enforcement>
1214 int /*var*/, int64_t /*old_value*/, absl::Span<const int64_t> solution) {
1215 if (has_enforcement) {
1216 for (const int lit : enforcements_) {
1217 if (!LiteralValue(lit, solution)) return -violation_;
1218 }
1219 }
1220
1221 const int64_t x1 = AffineValue(box1_.x_min, solution);
1222 const int64_t X1 = AffineValue(box1_.x_max, solution);
1223 const int64_t x2 = AffineValue(box2_.x_min, solution);
1224 const int64_t X2 = AffineValue(box2_.x_max, solution);
1225 const int64_t repair_x = std::min(X2 - x1, X1 - x2);
1226 if (repair_x <= 0) return -violation_; // disjoint
1227
1228 const int64_t y1 = AffineValue(box1_.y_min, solution);
1229 const int64_t Y1 = AffineValue(box1_.y_max, solution);
1230 const int64_t y2 = AffineValue(box2_.y_min, solution);
1231 const int64_t Y2 = AffineValue(box2_.y_max, solution);
1232 const int64_t repair_y = std::min(Y2 - y1, Y1 - y2);
1233 if (repair_y <= 0) return -violation_; // disjoint
1234
1235 const int64_t overlap_x =
1236 std::min(std::max(std::min(X2 - x2, X1 - x1), int64_t{1}), repair_x);
1237 const int64_t overlap_y =
1238 std::min(std::max(std::min(Y2 - y2, Y1 - y1), int64_t{1}), repair_y);
1239 return std::min(repair_x * overlap_y, repair_y * overlap_x) - violation_;
1240}
1241
1242template <bool has_enforcement>
1243std::vector<int>
1245 const CpModelProto& /*model_proto*/) const {
1246 std::vector<int> result;
1247 if (has_enforcement) {
1248 for (const int ref : enforcements_) result.push_back(PositiveRef(ref));
1249 }
1250 box1_.x_min.AppendVarTo(result);
1251 box1_.x_max.AppendVarTo(result);
1252 box1_.y_min.AppendVarTo(result);
1253 box1_.y_max.AppendVarTo(result);
1254 box2_.x_min.AppendVarTo(result);
1255 box2_.x_max.AppendVarTo(result);
1256 box2_.y_min.AppendVarTo(result);
1257 box2_.y_max.AppendVarTo(result);
1259 result.shrink_to_fit();
1260 return result;
1261}
1262
1263// ----- CompiledCircuitConstraint -----
1264
1265// The violation of a circuit has three parts:
1266// 1. Flow imbalance, maintained by the linear part.
1267// 2. The number of non-skipped SCCs in the graph minus 1.
1268// 3. The number of non-skipped SCCs that cannot be reached from any other
1269// component minus 1.
1270//
1271// #3 is not necessary for correctness, but makes the function much smoother.
1272//
1273// The only difference between single and multi circuit is flow balance at the
1274// depot, so we use the same compiled constraint for both.
1276 public:
1278 ~CompiledCircuitConstraint() override = default;
1279
1280 int64_t ComputeViolation(absl::Span<const int64_t> solution) override;
1281 void PerformMove(int var, int64_t old_value,
1282 absl::Span<const int64_t> new_solution) override;
1283 int64_t ViolationDelta(
1284 int var, int64_t old_value,
1285 absl::Span<const int64_t> solution_with_new_value) override;
1286
1287 private:
1288 struct SccOutput {
1289 void emplace_back(const int* start, const int* end);
1290 void reset(int num_nodes);
1291
1292 int num_components = 0;
1293 std::vector<bool> skipped;
1294 std::vector<int> root;
1295 };
1296 void InitGraph(absl::Span<const int64_t> solution);
1297 bool UpdateGraph(int var, int64_t value);
1298 int64_t ViolationForCurrentGraph();
1299
1300 absl::flat_hash_map<int, std::vector<int>> arcs_by_lit_;
1301 absl::Span<const int> literals_;
1302 absl::Span<const int> tails_;
1303 absl::Span<const int> heads_;
1304 // Stores the currently active arcs per tail node.
1305 std::vector<DenseSet<int>> graph_;
1306 SccOutput sccs_;
1307 SccOutput committed_sccs_;
1308 std::vector<bool> has_in_arc_;
1310 scc_finder_;
1311};
1312
1313void CompiledCircuitConstraint::SccOutput::emplace_back(int const* start,
1314 int const* end) {
1315 const int root_node = *start;
1316 const int size = end - start;
1317 if (size > 1) {
1318 ++num_components;
1319 }
1320 for (; start != end; ++start) {
1321 root[*start] = root_node;
1322 skipped[*start] = (size == 1);
1323 }
1324}
1325void CompiledCircuitConstraint::SccOutput::reset(int num_nodes) {
1326 num_components = 0;
1327 root.clear();
1328 root.resize(num_nodes);
1329 skipped.clear();
1330 skipped.resize(num_nodes);
1331}
1332
1336 const bool routes = ct_proto.has_routes();
1337 tails_ = routes ? ct_proto.routes().tails() : ct_proto.circuit().tails();
1338 heads_ = absl::MakeConstSpan(routes ? ct_proto.routes().heads()
1339 : ct_proto.circuit().heads());
1340 literals_ = absl::MakeConstSpan(routes ? ct_proto.routes().literals()
1341 : ct_proto.circuit().literals());
1342 graph_.resize(*absl::c_max_element(tails_) + 1);
1343 for (int i = 0; i < literals_.size(); ++i) {
1344 arcs_by_lit_[literals_[i]].push_back(i);
1345 }
1346}
1347
1348void CompiledCircuitConstraint::InitGraph(absl::Span<const int64_t> solution) {
1349 for (DenseSet<int>& edges : graph_) {
1350 edges.clear();
1351 }
1352 for (int i = 0; i < tails_.size(); ++i) {
1353 if (!LiteralValue(literals_[i], solution)) continue;
1354 graph_[tails_[i]].insert(heads_[i]);
1355 }
1356}
1357
1358bool CompiledCircuitConstraint::UpdateGraph(int var, int64_t value) {
1359 bool needs_update = false;
1360 const int enabled_lit =
1361 value != 0 ? PositiveRef(var) : NegatedRef(PositiveRef(var));
1362 const int disabled_lit = NegatedRef(enabled_lit);
1363 for (const int arc : arcs_by_lit_[disabled_lit]) {
1364 const int tail = tails_[arc];
1365 const int head = heads_[arc];
1366 // Removing a self arc cannot change violation.
1367 needs_update = needs_update || tail != head;
1368 graph_[tails_[arc]].erase(heads_[arc]);
1369 }
1370 for (const int arc : arcs_by_lit_[enabled_lit]) {
1371 const int tail = tails_[arc];
1372 const int head = heads_[arc];
1373 // Adding an arc can only change violation if it connects new SCCs.
1374 needs_update = needs_update ||
1375 committed_sccs_.root[tail] != committed_sccs_.root[head];
1376 graph_[tails_[arc]].insert(heads_[arc]);
1377 }
1378 return needs_update;
1379}
1380
1382 int var, int64_t, absl::Span<const int64_t> new_solution) {
1383 UpdateGraph(var, new_solution[var]);
1384 violation_ = ViolationForCurrentGraph();
1385 std::swap(committed_sccs_, sccs_);
1386}
1387
1389 absl::Span<const int64_t> solution) {
1390 InitGraph(solution);
1391 int64_t result = ViolationForCurrentGraph();
1392 std::swap(committed_sccs_, sccs_);
1393 return result;
1394}
1395
1397 int var, int64_t old_value,
1398 absl::Span<const int64_t> solution_with_new_value) {
1399 int64_t result = 0;
1400 if (UpdateGraph(var, solution_with_new_value[var])) {
1401 result = ViolationForCurrentGraph() - violation_;
1402 }
1403 UpdateGraph(var, old_value);
1404 return result;
1405}
1406
1407int64_t CompiledCircuitConstraint::ViolationForCurrentGraph() {
1408 const int num_nodes = graph_.size();
1409 sccs_.reset(num_nodes);
1410 scc_finder_.FindStronglyConnectedComponents(num_nodes, graph_, &sccs_);
1411 // Skipping all nodes causes off-by-one errors below, so it's simpler to
1412 // handle explicitly.
1413 if (sccs_.num_components == 0) return 0;
1414 // Count the number of SCCs that have inbound cross-component arcs
1415 // as a smoother measure of progress towards strong connectivity.
1416 int num_half_connected_components = 0;
1417 has_in_arc_.clear();
1418 has_in_arc_.resize(num_nodes, false);
1419 for (int tail = 0; tail < graph_.size(); ++tail) {
1420 if (sccs_.skipped[tail]) continue;
1421 for (const int head : graph_[tail]) {
1422 const int head_root = sccs_.root[head];
1423 if (sccs_.root[tail] == head_root) continue;
1424 if (has_in_arc_[head_root]) continue;
1425 if (sccs_.skipped[head_root]) continue;
1426 has_in_arc_[head_root] = true;
1427 ++num_half_connected_components;
1428 }
1429 }
1430 const int64_t violation = sccs_.num_components - 1 + sccs_.num_components -
1431 num_half_connected_components - 1 +
1432 (ct_proto().has_routes() ? sccs_.skipped[0] : 0);
1433 VLOG(2) << "#SCCs=" << sccs_.num_components << " #nodes=" << num_nodes
1434 << " #half_connected_components=" << num_half_connected_components
1435 << " violation=" << violation;
1436 return violation;
1437}
1438
1440 const ConstraintProto& ct_proto) {
1441 const bool routes = ct_proto.has_routes();
1442 auto heads = routes ? ct_proto.routes().heads() : ct_proto.circuit().heads();
1443 auto tails = routes ? ct_proto.routes().tails() : ct_proto.circuit().tails();
1444 auto literals =
1445 routes ? ct_proto.routes().literals() : ct_proto.circuit().literals();
1446
1447 std::vector<std::vector<int>> inflow_lits;
1448 std::vector<std::vector<int>> outflow_lits;
1449 for (int i = 0; i < heads.size(); ++i) {
1450 if (heads[i] >= inflow_lits.size()) {
1451 inflow_lits.resize(heads[i] + 1);
1452 }
1453 inflow_lits[heads[i]].push_back(literals[i]);
1454 if (tails[i] >= outflow_lits.size()) {
1455 outflow_lits.resize(tails[i] + 1);
1456 }
1457 outflow_lits[tails[i]].push_back(literals[i]);
1458 }
1459 if (routes) {
1460 const int depot_net_flow = linear_evaluator.NewConstraint({0, 0});
1461 for (const int lit : inflow_lits[0]) {
1462 linear_evaluator.AddLiteral(depot_net_flow, lit, 1);
1463 }
1464 for (const int lit : outflow_lits[0]) {
1465 linear_evaluator.AddLiteral(depot_net_flow, lit, -1);
1466 }
1467 }
1468 for (int i = routes ? 1 : 0; i < inflow_lits.size(); ++i) {
1469 const int inflow_ct = linear_evaluator.NewConstraint({1, 1});
1470 for (const int lit : inflow_lits[i]) {
1471 linear_evaluator.AddLiteral(inflow_ct, lit);
1472 }
1473 }
1474 for (int i = routes ? 1 : 0; i < outflow_lits.size(); ++i) {
1475 const int outflow_ct = linear_evaluator.NewConstraint({1, 1});
1476 for (const int lit : outflow_lits[i]) {
1477 linear_evaluator.AddLiteral(outflow_ct, lit);
1478 }
1479 }
1480}
1481
1482// ----- LsEvaluator -----
1483
1485 const SatParameters& params, TimeLimit* time_limit)
1486 : cp_model_(cp_model), params_(params), time_limit_(time_limit) {
1487 var_to_constraints_.resize(cp_model_.variables_size());
1488 var_to_dtime_estimate_.resize(cp_model_.variables_size());
1489 jump_value_optimal_.resize(cp_model_.variables_size(), true);
1490 num_violated_constraint_per_var_ignoring_objective_.assign(
1491 cp_model_.variables_size(), 0);
1492
1493 std::vector<bool> ignored_constraints(cp_model_.constraints_size(), false);
1494 std::vector<ConstraintProto> additional_constraints;
1495 CompileConstraintsAndObjective(ignored_constraints, additional_constraints);
1496 BuildVarConstraintGraph();
1497 violated_constraints_.reserve(NumEvaluatorConstraints());
1498}
1499
1501 const CpModelProto& cp_model, const SatParameters& params,
1502 const std::vector<bool>& ignored_constraints,
1503 const std::vector<ConstraintProto>& additional_constraints,
1505 : cp_model_(cp_model), params_(params), time_limit_(time_limit) {
1506 var_to_constraints_.resize(cp_model_.variables_size());
1507 var_to_dtime_estimate_.resize(cp_model_.variables_size());
1508 jump_value_optimal_.resize(cp_model_.variables_size(), true);
1509 num_violated_constraint_per_var_ignoring_objective_.assign(
1510 cp_model_.variables_size(), 0);
1511 CompileConstraintsAndObjective(ignored_constraints, additional_constraints);
1512 BuildVarConstraintGraph();
1513 violated_constraints_.reserve(NumEvaluatorConstraints());
1514}
1515
1516void LsEvaluator::BuildVarConstraintGraph() {
1517 // Clear the var <-> constraint graph.
1518 for (std::vector<int>& ct_indices : var_to_constraints_) ct_indices.clear();
1519 constraint_to_vars_.resize(constraints_.size());
1520
1521 // Build the var <-> constraint graph.
1522 for (int ct_index = 0; ct_index < constraints_.size(); ++ct_index) {
1523 constraint_to_vars_[ct_index] =
1524 constraints_[ct_index]->UsedVariables(cp_model_);
1525
1526 const double dtime = 1e-8 * constraint_to_vars_[ct_index].size();
1527 for (const int var : constraint_to_vars_[ct_index]) {
1528 var_to_constraints_[var].push_back(ct_index);
1529 var_to_dtime_estimate_[var] += dtime;
1530 }
1531 }
1532
1533 // Remove duplicates.
1534 for (std::vector<int>& constraints : var_to_constraints_) {
1535 gtl::STLSortAndRemoveDuplicates(&constraints);
1536 }
1537 for (std::vector<int>& vars : constraint_to_vars_) {
1539 }
1540
1541 // Scan the model to decide if a variable is linked to a convex evaluation.
1542 jump_value_optimal_.resize(cp_model_.variables_size());
1543 for (int i = 0; i < cp_model_.variables_size(); ++i) {
1544 if (!var_to_constraints_[i].empty()) {
1545 jump_value_optimal_[i] = false;
1546 continue;
1547 }
1548
1549 const IntegerVariableProto& var_proto = cp_model_.variables(i);
1550 if (var_proto.domain_size() == 2 && var_proto.domain(0) == 0 &&
1551 var_proto.domain(1) == 1) {
1552 // Boolean variables violation change is always convex.
1553 jump_value_optimal_[i] = true;
1554 continue;
1555 }
1556
1557 jump_value_optimal_[i] = linear_evaluator_.ViolationChangeIsConvex(i);
1558 }
1559}
1560
1561void LsEvaluator::CompileOneConstraint(const ConstraintProto& ct) {
1562 switch (ct.constraint_case()) {
1564 // Encoding using enforcement literal is slightly more efficient.
1565 const int ct_index = linear_evaluator_.NewConstraint(Domain(1, 1));
1566 for (const int lit : ct.enforcement_literal()) {
1567 linear_evaluator_.AddEnforcementLiteral(ct_index, lit);
1568 }
1569 for (const int lit : ct.bool_or().literals()) {
1570 linear_evaluator_.AddEnforcementLiteral(ct_index, NegatedRef(lit));
1571 }
1572 break;
1573 }
1575 const int num_literals = ct.bool_and().literals_size();
1576 const int ct_index =
1577 linear_evaluator_.NewConstraint(Domain(num_literals));
1578 for (const int lit : ct.enforcement_literal()) {
1579 linear_evaluator_.AddEnforcementLiteral(ct_index, lit);
1580 }
1581 for (const int lit : ct.bool_and().literals()) {
1582 linear_evaluator_.AddLiteral(ct_index, lit);
1583 }
1584 break;
1585 }
1587 DCHECK(ct.enforcement_literal().empty());
1588 const int ct_index = linear_evaluator_.NewConstraint({0, 1});
1589 for (const int lit : ct.at_most_one().literals()) {
1590 linear_evaluator_.AddLiteral(ct_index, lit);
1591 }
1592 break;
1593 }
1595 DCHECK(ct.enforcement_literal().empty());
1596 const int ct_index = linear_evaluator_.NewConstraint({1, 1});
1597 for (const int lit : ct.exactly_one().literals()) {
1598 linear_evaluator_.AddLiteral(ct_index, lit);
1599 }
1600 break;
1601 }
1603 constraints_.emplace_back(new CompiledBoolXorConstraint(ct));
1604 break;
1605 }
1607 constraints_.emplace_back(new CompiledAllDiffConstraint(ct));
1608 break;
1609 }
1611 // This constraint is split into linear precedences and its max
1612 // maintenance.
1613 const LinearExpressionProto& target = ct.lin_max().target();
1614 for (const LinearExpressionProto& expr : ct.lin_max().exprs()) {
1615 const int64_t max_value =
1616 ExprMax(target, cp_model_) - ExprMin(expr, cp_model_);
1617 const int precedence_index =
1618 linear_evaluator_.NewConstraint({0, max_value});
1619 linear_evaluator_.AddLinearExpression(precedence_index, target, 1);
1620 linear_evaluator_.AddLinearExpression(precedence_index, expr, -1);
1621 }
1622
1623 // Penalty when target > all expressions.
1624 constraints_.emplace_back(new CompiledLinMaxConstraint(ct));
1625 break;
1626 }
1628 constraints_.emplace_back(new CompiledIntProdConstraint(ct));
1629 break;
1630 }
1632 constraints_.emplace_back(new CompiledIntDivConstraint(ct));
1633 break;
1634 }
1636 DCHECK_EQ(ExprMin(ct.int_mod().exprs(1), cp_model_),
1637 ExprMax(ct.int_mod().exprs(1), cp_model_));
1638 constraints_.emplace_back(new CompiledIntModConstraint(ct));
1639 break;
1640 }
1642 const Domain domain = ReadDomainFromProto(ct.linear());
1643 const int ct_index = linear_evaluator_.NewConstraint(domain);
1644 for (const int lit : ct.enforcement_literal()) {
1645 linear_evaluator_.AddEnforcementLiteral(ct_index, lit);
1646 }
1647 for (int i = 0; i < ct.linear().vars_size(); ++i) {
1648 const int var = ct.linear().vars(i);
1649 const int64_t coeff = ct.linear().coeffs(i);
1650 linear_evaluator_.AddTerm(ct_index, var, coeff);
1651 }
1652 break;
1653 }
1655 const int size = ct.no_overlap().intervals_size();
1656 if (size <= 1) break;
1657 if (size > params_.feasibility_jump_max_expanded_constraint_size()) {
1658 // Similar code to the kCumulative constraint.
1659 // The violation will be the area above the capacity.
1660 LinearExpressionProto one;
1661 one.set_offset(1);
1662 std::vector<std::optional<int>> is_active;
1663 std::vector<LinearExpressionProto> times;
1664 std::vector<LinearExpressionProto> demands;
1665 const int num_intervals = ct.no_overlap().intervals().size();
1666 for (int i = 0; i < num_intervals; ++i) {
1667 const ConstraintProto& interval_ct =
1668 cp_model_.constraints(ct.no_overlap().intervals(i));
1669 if (interval_ct.enforcement_literal().empty()) {
1670 is_active.push_back(std::nullopt);
1671 is_active.push_back(std::nullopt);
1672 } else {
1673 CHECK_EQ(interval_ct.enforcement_literal().size(), 1);
1674 is_active.push_back(interval_ct.enforcement_literal(0));
1675 is_active.push_back(interval_ct.enforcement_literal(0));
1676 }
1677
1678 times.push_back(interval_ct.interval().start());
1679 times.push_back(LinearExprSum(interval_ct.interval().start(),
1680 interval_ct.interval().size()));
1681 demands.push_back(one);
1682 demands.push_back(NegatedLinearExpression(one));
1683 }
1684 constraints_.emplace_back(new CompiledReservoirConstraint(
1685 std::move(one), std::move(is_active), std::move(times),
1686 std::move(demands)));
1687 } else {
1688 // We expand the no_overlap constraints into a quadratic number of
1689 // disjunctions.
1690 for (int i = 0; i + 1 < size; ++i) {
1691 const ConstraintProto& proto_i =
1692 cp_model_.constraints(ct.no_overlap().intervals(i));
1693 const IntervalConstraintProto& interval_i = proto_i.interval();
1694 const int64_t min_start_i = ExprMin(interval_i.start(), cp_model_);
1695 const int64_t max_end_i = ExprMax(interval_i.end(), cp_model_);
1696 for (int j = i + 1; j < size; ++j) {
1697 const ConstraintProto& proto_j =
1698 cp_model_.constraints(ct.no_overlap().intervals(j));
1699 const IntervalConstraintProto& interval_j = proto_j.interval();
1700 const int64_t min_start_j = ExprMin(interval_j.start(), cp_model_);
1701 const int64_t max_end_j = ExprMax(interval_j.end(), cp_model_);
1702 if (min_start_i >= max_end_j || min_start_j >= max_end_i) continue;
1703
1704 const bool has_enforcement =
1705 !proto_i.enforcement_literal().empty() ||
1706 !proto_j.enforcement_literal().empty();
1707 if (has_enforcement) {
1708 constraints_.emplace_back(
1709 new CompiledNoOverlapWithTwoIntervals<true>(proto_i,
1710 proto_j));
1711 } else {
1712 constraints_.emplace_back(
1713 new CompiledNoOverlapWithTwoIntervals<false>(proto_i,
1714 proto_j));
1715 }
1716 }
1717 }
1718 }
1719 break;
1720 }
1722 LinearExpressionProto capacity = ct.cumulative().capacity();
1723 std::vector<std::optional<int>> is_active;
1724 std::vector<LinearExpressionProto> times;
1725 std::vector<LinearExpressionProto> demands;
1726 const int num_intervals = ct.cumulative().intervals().size();
1727 for (int i = 0; i < num_intervals; ++i) {
1728 const ConstraintProto& interval_ct =
1729 cp_model_.constraints(ct.cumulative().intervals(i));
1730 if (interval_ct.enforcement_literal().empty()) {
1731 is_active.push_back(std::nullopt);
1732 is_active.push_back(std::nullopt);
1733 } else {
1734 CHECK_EQ(interval_ct.enforcement_literal().size(), 1);
1735 is_active.push_back(interval_ct.enforcement_literal(0));
1736 is_active.push_back(interval_ct.enforcement_literal(0));
1737 }
1738
1739 // Start.
1740 times.push_back(interval_ct.interval().start());
1741 demands.push_back(ct.cumulative().demands(i));
1742
1743 // End.
1744 // I tried 3 alternatives: end, max(end, start+size) and just start +
1745 // size. The most performing one was "start + size" on the multi-mode
1746 // RCPSP.
1747 //
1748 // Note that for fixed size, this do not matter. It is easy enough to
1749 // try any expression by creating a small wrapper class to use instead
1750 // of a LinearExpressionProto for time.
1751 times.push_back(LinearExprSum(interval_ct.interval().start(),
1752 interval_ct.interval().size()));
1753 demands.push_back(NegatedLinearExpression(ct.cumulative().demands(i)));
1754 }
1755
1756 constraints_.emplace_back(new CompiledReservoirConstraint(
1757 std::move(capacity), std::move(is_active), std::move(times),
1758 std::move(demands)));
1759 break;
1760 }
1762 const auto& x_intervals = ct.no_overlap_2d().x_intervals();
1763 const auto& y_intervals = ct.no_overlap_2d().y_intervals();
1764 const int size = x_intervals.size();
1765 if (size <= 1) break;
1766 if (size == 2 ||
1767 size > params_.feasibility_jump_max_expanded_constraint_size()) {
1768 CompiledNoOverlap2dConstraint* no_overlap_2d =
1769 new CompiledNoOverlap2dConstraint(ct, cp_model_);
1770 constraints_.emplace_back(no_overlap_2d);
1771 break;
1772 }
1773
1774 for (int i = 0; i + 1 < size; ++i) {
1775 const ConstraintProto& x_proto_i =
1776 cp_model_.constraints(x_intervals[i]);
1777 const IntervalConstraintProto& x_interval_i = x_proto_i.interval();
1778 const int64_t x_min_start_i = ExprMin(x_interval_i.start(), cp_model_);
1779 const int64_t x_max_end_i = ExprMax(x_interval_i.end(), cp_model_);
1780 const ConstraintProto& y_proto_i =
1781 cp_model_.constraints(y_intervals[i]);
1782 const IntervalConstraintProto& y_interval_i = y_proto_i.interval();
1783 const int64_t y_min_start_i = ExprMin(y_interval_i.start(), cp_model_);
1784 const int64_t y_max_end_i = ExprMax(y_interval_i.end(), cp_model_);
1785 for (int j = i + 1; j < size; ++j) {
1786 const ConstraintProto& x_proto_j =
1787 cp_model_.constraints(x_intervals[j]);
1788 const IntervalConstraintProto& x_interval_j = x_proto_j.interval();
1789 const int64_t x_min_start_j =
1790 ExprMin(x_interval_j.start(), cp_model_);
1791 const int64_t x_max_end_j = ExprMax(x_interval_j.end(), cp_model_);
1792 const ConstraintProto& y_proto_j =
1793 cp_model_.constraints(y_intervals[j]);
1794 const IntervalConstraintProto& y_interval_j = y_proto_j.interval();
1795 const int64_t y_min_start_j =
1796 ExprMin(y_interval_j.start(), cp_model_);
1797 const int64_t y_max_end_j = ExprMax(y_interval_j.end(), cp_model_);
1798 if (x_min_start_i >= x_max_end_j || x_min_start_j >= x_max_end_i ||
1799 y_min_start_i >= y_max_end_j || y_min_start_j >= y_max_end_i) {
1800 continue;
1801 }
1802
1803 const bool has_enforcement =
1804 !x_proto_i.enforcement_literal().empty() ||
1805 !x_proto_j.enforcement_literal().empty() ||
1806 !y_proto_i.enforcement_literal().empty() ||
1807 !y_proto_j.enforcement_literal().empty();
1808 if (has_enforcement) {
1809 constraints_.emplace_back(new CompiledNoOverlap2dWithTwoBoxes<true>(
1810 x_proto_i, y_proto_i, x_proto_j, y_proto_j));
1811 } else {
1812 constraints_.emplace_back(
1813 new CompiledNoOverlap2dWithTwoBoxes<false>(
1814 x_proto_i, y_proto_i, x_proto_j, y_proto_j));
1815 }
1816 }
1817 }
1818 break;
1819 }
1822 constraints_.emplace_back(new CompiledCircuitConstraint(ct));
1823 AddCircuitFlowConstraints(linear_evaluator_, ct);
1824 break;
1825 default:
1826 VLOG(1) << "Not implemented: " << ct.constraint_case();
1827 break;
1828 }
1829}
1830
1831void LsEvaluator::CompileConstraintsAndObjective(
1832 const std::vector<bool>& ignored_constraints,
1833 const std::vector<ConstraintProto>& additional_constraints) {
1834 constraints_.clear();
1835
1836 // The first compiled constraint is always the objective if present.
1837 if (cp_model_.has_objective()) {
1838 const int ct_index = linear_evaluator_.NewConstraint(
1839 cp_model_.objective().domain().empty()
1841 : ReadDomainFromProto(cp_model_.objective()));
1842 DCHECK_EQ(0, ct_index);
1843 for (int i = 0; i < cp_model_.objective().vars_size(); ++i) {
1844 const int var = cp_model_.objective().vars(i);
1845 const int64_t coeff = cp_model_.objective().coeffs(i);
1846 linear_evaluator_.AddTerm(ct_index, var, coeff);
1847 }
1848 }
1849
1850 TimeLimitCheckEveryNCalls checker(1000, time_limit_);
1851 for (int c = 0; c < cp_model_.constraints_size(); ++c) {
1852 if (ignored_constraints[c]) continue;
1853 CompileOneConstraint(cp_model_.constraints(c));
1854 if (checker.LimitReached()) break;
1855 }
1856
1857 for (const ConstraintProto& ct : additional_constraints) {
1858 CompileOneConstraint(ct);
1859 }
1860
1861 // Make sure we have access to the data in an efficient way.
1862 std::vector<int64_t> var_max_variations(cp_model_.variables().size());
1863 for (int var = 0; var < cp_model_.variables().size(); ++var) {
1864 const auto& domain = cp_model_.variables(var).domain();
1865 var_max_variations[var] = domain[domain.size() - 1] - domain[0];
1866 }
1867 linear_evaluator_.PrecomputeCompactView(var_max_variations);
1868}
1869
1870bool LsEvaluator::ReduceObjectiveBounds(int64_t lb, int64_t ub) {
1871 if (!cp_model_.has_objective()) return false;
1872 if (linear_evaluator_.ReduceBounds(/*c=*/0, lb, ub)) {
1874 return true;
1875 }
1876 return false;
1877}
1878
1879void LsEvaluator::ComputeAllViolations(absl::Span<const int64_t> solution) {
1880 // Linear constraints.
1881 linear_evaluator_.ComputeInitialActivities(solution);
1882
1883 // Generic constraints.
1884 for (const auto& ct : constraints_) {
1885 ct->InitializeViolation(solution);
1886 }
1887
1888 RecomputeViolatedList(/*linear_only=*/false);
1889}
1890
1892 absl::Span<const int64_t> solution) {
1893 // Generic constraints.
1894 for (const auto& ct : constraints_) {
1895 ct->InitializeViolation(solution);
1896 }
1897}
1898
1900 int var, int64_t old_value, absl::Span<const int64_t> new_solution) {
1901 for (const int general_ct_index : var_to_constraints_[var]) {
1902 const int c = general_ct_index + linear_evaluator_.num_constraints();
1903 const int64_t v0 = constraints_[general_ct_index]->violation();
1904 constraints_[general_ct_index]->PerformMove(var, old_value, new_solution);
1905 const int64_t violation_delta =
1906 constraints_[general_ct_index]->violation() - v0;
1907 if (violation_delta != 0) {
1908 last_update_violation_changes_.push_back(c);
1909 }
1910 }
1911}
1912
1913void LsEvaluator::UpdateLinearScores(int var, int64_t old_value,
1914 int64_t new_value,
1915 absl::Span<const double> weights,
1916 absl::Span<const int64_t> jump_deltas,
1917 absl::Span<double> jump_scores) {
1918 DCHECK(RefIsPositive(var));
1919 if (old_value == new_value) return;
1920 last_update_violation_changes_.clear();
1921 linear_evaluator_.ClearAffectedVariables();
1922 linear_evaluator_.UpdateVariableAndScores(var, new_value - old_value, weights,
1923 jump_deltas, jump_scores,
1924 &last_update_violation_changes_);
1925}
1926
1928 // Maintain the list of violated constraints.
1929 dtime_ += 1e-8 * last_update_violation_changes_.size();
1930 for (const int c : last_update_violation_changes_) {
1932 }
1933}
1934
1936 int64_t evaluation = 0;
1937
1938 // Process the linear part.
1939 for (int i = 0; i < linear_evaluator_.num_constraints(); ++i) {
1940 evaluation += linear_evaluator_.Violation(i);
1941 DCHECK_GE(linear_evaluator_.Violation(i), 0);
1942 }
1943
1944 // Process the generic constraint part.
1945 for (const auto& ct : constraints_) {
1946 evaluation += ct->violation();
1947 DCHECK_GE(ct->violation(), 0);
1948 }
1949 return evaluation;
1950}
1951
1953 DCHECK(cp_model_.has_objective());
1954 return linear_evaluator_.Activity(/*c=*/0);
1955}
1956
1958 return linear_evaluator_.num_constraints();
1959}
1960
1962 return static_cast<int>(constraints_.size());
1963}
1964
1966 return linear_evaluator_.num_constraints() +
1967 static_cast<int>(constraints_.size());
1968}
1969
1971 int result = 0;
1972 for (int c = 0; c < linear_evaluator_.num_constraints(); ++c) {
1973 if (linear_evaluator_.Violation(c) > 0) {
1974 ++result;
1975 }
1976 }
1977 for (const auto& constraint : constraints_) {
1978 if (constraint->violation() > 0) {
1979 ++result;
1980 }
1981 }
1982 return result;
1983}
1984
1985int64_t LsEvaluator::Violation(int c) const {
1986 if (c < linear_evaluator_.num_constraints()) {
1987 return linear_evaluator_.Violation(c);
1988 } else {
1989 return constraints_[c - linear_evaluator_.num_constraints()]->violation();
1990 }
1991}
1992
1993bool LsEvaluator::IsViolated(int c) const {
1994 if (c < linear_evaluator_.num_constraints()) {
1995 return linear_evaluator_.IsViolated(c);
1996 } else {
1997 return constraints_[c - linear_evaluator_.num_constraints()]->violation() >
1998 0;
1999 }
2000}
2001
2002double LsEvaluator::WeightedViolation(absl::Span<const double> weights) const {
2003 DCHECK_EQ(weights.size(), NumEvaluatorConstraints());
2004 double result = linear_evaluator_.WeightedViolation(weights);
2005
2006 const int num_linear_constraints = linear_evaluator_.num_constraints();
2007 for (int c = 0; c < constraints_.size(); ++c) {
2008 result += static_cast<double>(constraints_[c]->violation()) *
2009 weights[num_linear_constraints + c];
2010 }
2011 return result;
2012}
2013
2015 bool linear_only, absl::Span<const double> weights, int var, int64_t delta,
2016 absl::Span<int64_t> mutable_solution) const {
2017 double result = linear_evaluator_.WeightedViolationDelta(weights, var, delta);
2018 if (linear_only) return result;
2019
2020 // We change the mutable solution here, and restore it after the evaluation.
2021 const int64_t old_value = mutable_solution[var];
2022 mutable_solution[var] += delta;
2023
2024 // We assume linear time delta computation in number of variables.
2025 // TODO(user): refine on a per constraint basis.
2026 dtime_ += var_to_dtime_estimate_[var];
2027
2028 const int num_linear_constraints = linear_evaluator_.num_constraints();
2029 const std::unique_ptr<CompiledConstraint>* data = constraints_.data();
2030 const auto non_linear_weights = weights.subspan(num_linear_constraints);
2031 for (const int ct_index : var_to_constraints_[var]) {
2032 DCHECK_LT(ct_index, constraints_.size());
2033 const int64_t ct_delta =
2034 data[ct_index]->ViolationDelta(var, old_value, mutable_solution);
2035 result += static_cast<double>(ct_delta) * non_linear_weights[ct_index];
2036 }
2037
2038 // Restore.
2039 mutable_solution[var] = old_value;
2040 return result;
2041}
2042
2044 int var) const {
2045 return jump_value_optimal_[var];
2046}
2047
2049 num_violated_constraint_per_var_ignoring_objective_.assign(
2050 cp_model_.variables_size(), 0);
2051 violated_constraints_.clear();
2052 const int num_constraints =
2054 for (int c = 0; c < num_constraints; ++c) {
2056 }
2057}
2058
2059void LsEvaluator::UpdateViolatedList(const int c) {
2060 if (Violation(c) > 0) {
2061 auto [it, inserted] = violated_constraints_.insert(c);
2062 // The constraint is violated. Add if needed.
2063 if (!inserted) return;
2064 if (IsObjectiveConstraint(c)) return;
2065 dtime_ += 1e-8 * ConstraintToVars(c).size();
2066 for (const int v : ConstraintToVars(c)) {
2067 num_violated_constraint_per_var_ignoring_objective_[v] += 1;
2068 }
2069 return;
2070 }
2071 if (violated_constraints_.erase(c) == 1) {
2072 if (IsObjectiveConstraint(c)) return;
2073 dtime_ += 1e-8 * ConstraintToVars(c).size();
2074 for (const int v : ConstraintToVars(c)) {
2075 num_violated_constraint_per_var_ignoring_objective_[v] -= 1;
2076 }
2077 }
2078}
2079
2080int64_t CompiledReservoirConstraint::BuildProfileAndReturnViolation(
2081 absl::Span<const int64_t> solution) {
2082 // Starts by filling the cache and profile_.
2083 capacity_value_ = ExprValue(capacity_, solution);
2084 const int num_events = time_values_.size();
2085 profile_.clear();
2086 for (int i = 0; i < num_events; ++i) {
2087 time_values_[i] = ExprValue(times_[i], solution);
2088 if (is_active_[i] != std::nullopt &&
2089 LiteralValue(*is_active_[i], solution) == 0) {
2090 demand_values_[i] = 0;
2091 } else {
2092 demand_values_[i] = ExprValue(demands_[i], solution);
2093 if (demand_values_[i] != 0) {
2094 profile_.push_back({time_values_[i], demand_values_[i]});
2095 }
2096 }
2097 }
2098
2099 if (profile_.empty()) return 0;
2100 absl::c_sort(profile_);
2101
2102 // Compress the profile for faster incremental evaluation.
2103 {
2104 int p = 0;
2105 for (int i = 1; i < profile_.size(); ++i) {
2106 if (profile_[i].time == profile_[p].time) {
2107 profile_[p].demand += profile_[i].demand;
2108 } else {
2109 profile_[++p] = profile_[i];
2110 }
2111 }
2112 profile_.resize(p + 1);
2113 }
2114
2115 int64_t overload = 0;
2116 int64_t current_load = 0;
2117 int64_t previous_time = std::numeric_limits<int64_t>::min();
2118 for (int i = 0; i < profile_.size(); ++i) {
2119 // At this point, current_load is the load at previous_time.
2120 const int64_t time = profile_[i].time;
2121 if (current_load > capacity_value_) {
2122 overload = CapAdd(overload, CapProd(current_load - capacity_value_,
2123 time - previous_time));
2124 }
2125
2126 current_load += profile_[i].demand;
2127 previous_time = time;
2128 }
2129 return overload;
2130}
2131
2132int64_t CompiledReservoirConstraint::IncrementalViolation(
2133 int var, absl::Span<const int64_t> solution) {
2134 const int64_t capacity = ExprValue(capacity_, solution);
2135 profile_delta_.clear();
2136 CHECK(RefIsPositive(var));
2137 for (const int i : dense_index_to_events_[var_to_dense_index_.at(var)]) {
2138 const int64_t time = ExprValue(times_[i], solution);
2139 int64_t demand = 0;
2140 if (is_active_[i] == std::nullopt ||
2141 LiteralValue(*is_active_[i], solution) == 1) {
2142 demand = ExprValue(demands_[i], solution);
2143 }
2144
2145 if (time == time_values_[i]) {
2146 if (demand != demand_values_[i]) {
2147 // Update the demand at time.
2148 profile_delta_.push_back({time, demand - demand_values_[i]});
2149 }
2150 } else {
2151 // Remove previous.
2152 if (demand_values_[i] != 0) {
2153 profile_delta_.push_back({time_values_[i], -demand_values_[i]});
2154 }
2155 // Add new.
2156 if (demand != 0) {
2157 profile_delta_.push_back({time, demand});
2158 }
2159 }
2160 }
2161
2162 // Abort early if there is no change.
2163 // This might happen because we use max(start + size, end) for the time and
2164 // even if some variable changed there, the time might not have.
2165 if (capacity == capacity_value_ && profile_delta_.empty()) {
2166 return violation_;
2167 }
2168 absl::c_sort(profile_delta_);
2169
2170 // Similar algo, but we scan the two vectors at once.
2171 int64_t overload = 0;
2172 int64_t current_load = 0;
2173 int64_t previous_time = std::numeric_limits<int64_t>::min();
2174
2175 // TODO(user): This code is the hotspot for our local search on cumulative.
2176 // It can probably be slightly improved. We might also be able to abort early
2177 // if we know that capacity is high enough compared to the highest point of
2178 // the profile.
2179 int i = 0;
2180 int j = 0;
2181 const absl::Span<const Event> i_profile(profile_);
2182 const absl::Span<const Event> j_profile(profile_delta_);
2183 while (true) {
2184 int64_t time;
2185 if (i < i_profile.size() && j < j_profile.size()) {
2186 time = std::min(i_profile[i].time, j_profile[j].time);
2187 } else if (i < i_profile.size()) {
2188 time = i_profile[i].time;
2189 } else if (j < j_profile.size()) {
2190 time = j_profile[j].time;
2191 } else {
2192 // End of loop.
2193 break;
2194 }
2195
2196 // Update overload if needed.
2197 // At this point, current_load is the load at previous_time.
2198 if (current_load > capacity) {
2199 overload = CapAdd(overload,
2200 CapProd(current_load - capacity, time - previous_time));
2201 }
2202
2203 // Update i and current load.
2204 while (i < i_profile.size() && i_profile[i].time == time) {
2205 current_load += i_profile[i].demand;
2206 i++;
2207 }
2208
2209 // Update j and current load.
2210 while (j < j_profile.size() && j_profile[j].time == time) {
2211 current_load += j_profile[j].demand;
2212 j++;
2213 }
2214
2215 previous_time = time;
2216 }
2217 return overload;
2218}
2219
2220void CompiledReservoirConstraint::AppendVariablesForEvent(
2221 int i, std::vector<int>* result) const {
2222 if (is_active_[i] != std::nullopt) {
2223 result->push_back(PositiveRef(*is_active_[i]));
2224 }
2225 for (const int var : times_[i].vars()) {
2226 result->push_back(PositiveRef(var));
2227 }
2228 for (const int var : demands_[i].vars()) {
2229 result->push_back(PositiveRef(var));
2230 }
2231}
2232
2233void CompiledReservoirConstraint::InitializeDenseIndexToEvents() {
2234 // We scan the constraint a few times, but this is called once, so we don't
2235 // care too much.
2236 CpModelProto unused;
2237 int num_dense_indices = 0;
2238 for (const int var : UsedVariables(unused)) {
2239 var_to_dense_index_[var] = num_dense_indices++;
2240 }
2241
2242 CompactVectorVector<int, int> event_to_dense_indices;
2243 event_to_dense_indices.reserve(times_.size());
2244 const int num_events = times_.size();
2245 std::vector<int> result;
2246 for (int i = 0; i < num_events; ++i) {
2247 result.clear();
2248 AppendVariablesForEvent(i, &result);
2249
2250 // Remap and add.
2251 for (int& var : result) {
2252 var = var_to_dense_index_.at(var);
2253 }
2255 event_to_dense_indices.Add(result);
2256 }
2257
2258 // Note that because of the capacity (which might be variable) it is important
2259 // to resize this to num_dense_indices.
2260 dense_index_to_events_.ResetFromTranspose(event_to_dense_indices,
2261 num_dense_indices);
2262}
2263
2265 const CpModelProto& /*model_proto*/) const {
2266 std::vector<int> result;
2267 const int num_events = times_.size();
2268 for (int i = 0; i < num_events; ++i) {
2269 AppendVariablesForEvent(i, &result);
2270 }
2271 for (const int var : capacity_.vars()) {
2272 result.push_back(PositiveRef(var));
2273 }
2275 result.shrink_to_fit();
2276 return result;
2277}
2278
2279} // namespace sat
2280} // namespace operations_research
std::pair< iterator, bool > insert(T value)
Definition dense_set.h:56
std::vector< int64_t > FlattenedIntervals() const
bool Contains(int64_t value) const
int64_t Distance(int64_t value) const
static IntegralType CeilOfRatio(IntegralType numerator, IntegralType denominator)
Definition mathutil.h:39
static IntegralType FloorOfRatio(IntegralType numerator, IntegralType denominator)
Definition mathutil.h:53
void Set(IntegerType index)
Definition bitset.h:878
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
void PerformMove(int var, int64_t old_value, absl::Span< const int64_t > new_solution) override
Updates the violation with the new value.
int64_t ComputeViolation(absl::Span< const int64_t > solution) override
int64_t ViolationDelta(int var, int64_t old_value, absl::Span< const int64_t > solution_with_new_value) override
Returns the delta if var changes from old_value to solution[var].
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_.
int64_t violation() const
The cached violation of this constraint.
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
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 --—
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
std::vector< int > UsedVariables(const CpModelProto &model_proto) const final
bool has_routes() const
.operations_research.sat.RoutesConstraintProto routes = 23;
::int32_t enforcement_literal(int index) const
const ::operations_research::sat::IntervalConstraintProto & interval() const
const ::operations_research::sat::RoutesConstraintProto & routes() const
const ::operations_research::sat::CircuitConstraintProto & circuit() const
const ::operations_research::sat::NoOverlap2DConstraintProto & no_overlap_2d() const
const ::operations_research::sat::ConstraintProto & constraints(int index) const
const ::operations_research::sat::LinearExpressionProto & end() const
const ::operations_research::sat::LinearExpressionProto & start() const
int vars_size() const
repeated int32 vars = 1;
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)
void AddLinearExpression(int ct_index, const LinearExpressionProto &expr, int64_t multiplier)
void PrecomputeCompactView(absl::Span< const int64_t > var_max_variation)
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)
double WeightedViolation(absl::Span< const double > weights) const
void ComputeAllNonLinearViolations(absl::Span< const int64_t > solution)
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.
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
double WeightedViolationDelta(bool linear_only, absl::Span< const double > weights, int var, int64_t delta, absl::Span< int64_t > mutable_solution) const
int x_intervals_size() const
repeated int32 x_intervals = 1;
time_limit
Definition solve.cc:22
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition stl_util.h:55
void STLClearObject(T *obj)
Definition stl_util.h:120
void AddCircuitFlowConstraints(LinearIncrementalEvaluator &linear_evaluator, const ConstraintProto &ct_proto)
int64_t OverlapOfTwoIntervals(const ConstraintProto &interval1, const ConstraintProto &interval2, absl::Span< const int64_t > solution)
--— CompiledNoOverlap2dConstraint --—
std::vector< int > UsedVariables(const ConstraintProto &ct)
std::vector< int > UsedIntervals(const ConstraintProto &ct)
Returns the sorted list of interval used by a constraint.
int64_t NoOverlapMinRepairDistance(const ConstraintProto &interval1, const ConstraintProto &interval2, absl::Span< const int64_t > solution)
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Reads a Domain from the domain field of a proto.
int NegatedRef(int ref)
Small utility functions to deal with negative variable/literal references.
In SWIG mode, we don't want anything besides these top-level includes.
int64_t CapAdd(int64_t x, int64_t y)
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
int64_t CapSub(int64_t x, int64_t y)
ClosedInterval::Iterator end(ClosedInterval interval)
int64_t CapProd(int64_t x, int64_t y)
int64_t Max() const
Returns the max of the domain.
Definition model.cc:346
int64_t Min() const
Returns the min of the domain.
Definition model.cc:340