-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
constraint_violation.cc
2256 lines (2035 loc) · 81.2 KB
/
constraint_violation.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/constraint_violation.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/stl_util.h"
#include "ortools/graph/strongly_connected_components.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/util.h"
#include "ortools/util/dense_set.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace sat {
namespace {
int64_t ExprValue(const LinearExpressionProto& expr,
absl::Span<const int64_t> solution) {
int64_t result = expr.offset();
for (int i = 0; i < expr.vars_size(); ++i) {
result += solution[expr.vars(i)] * expr.coeffs(i);
}
return result;
}
LinearExpressionProto ExprDiff(const LinearExpressionProto& a,
const LinearExpressionProto& b) {
LinearExpressionProto result;
result.set_offset(a.offset() - b.offset());
result.mutable_vars()->Reserve(a.vars().size() + b.vars().size());
result.mutable_coeffs()->Reserve(a.vars().size() + b.vars().size());
for (int i = 0; i < a.vars().size(); ++i) {
result.add_vars(a.vars(i));
result.add_coeffs(a.coeffs(i));
}
for (int i = 0; i < b.vars().size(); ++i) {
result.add_vars(b.vars(i));
result.add_coeffs(-b.coeffs(i));
}
return result;
}
LinearExpressionProto LinearExprSum(LinearExpressionProto a,
LinearExpressionProto b) {
LinearExpressionProto result;
result.set_offset(a.offset() + b.offset());
result.mutable_vars()->Reserve(a.vars().size() + b.vars().size());
result.mutable_coeffs()->Reserve(a.vars().size() + b.vars().size());
for (const LinearExpressionProto& p : {a, b}) {
for (int i = 0; i < p.vars().size(); ++i) {
result.add_vars(p.vars(i));
result.add_coeffs(p.coeffs(i));
}
}
return result;
}
LinearExpressionProto NegatedLinearExpression(LinearExpressionProto a) {
LinearExpressionProto result = a;
result.set_offset(-a.offset());
for (int64_t& coeff : *result.mutable_coeffs()) {
coeff = -coeff;
}
return result;
}
int64_t ExprMin(const LinearExpressionProto& expr, const CpModelProto& model) {
int64_t result = expr.offset();
for (int i = 0; i < expr.vars_size(); ++i) {
const IntegerVariableProto& var_proto = model.variables(expr.vars(i));
if (expr.coeffs(i) > 0) {
result += expr.coeffs(i) * var_proto.domain(0);
} else {
result += expr.coeffs(i) * var_proto.domain(var_proto.domain_size() - 1);
}
}
return result;
}
int64_t ExprMax(const LinearExpressionProto& expr, const CpModelProto& model) {
int64_t result = expr.offset();
for (int i = 0; i < expr.vars_size(); ++i) {
const IntegerVariableProto& var_proto = model.variables(expr.vars(i));
if (expr.coeffs(i) > 0) {
result += expr.coeffs(i) * var_proto.domain(var_proto.domain_size() - 1);
} else {
result += expr.coeffs(i) * var_proto.domain(0);
}
}
return result;
}
bool LiteralValue(int lit, absl::Span<const int64_t> solution) {
if (RefIsPositive(lit)) {
return solution[lit] != 0;
} else {
return solution[PositiveRef(lit)] == 0;
}
}
} // namespace
// ---- LinearIncrementalEvaluator -----
int LinearIncrementalEvaluator::NewConstraint(Domain domain) {
DCHECK(creation_phase_);
domains_.push_back(domain);
offsets_.push_back(0);
activities_.push_back(0);
num_false_enforcement_.push_back(0);
distances_.push_back(0);
is_violated_.push_back(false);
return num_constraints_++;
}
void LinearIncrementalEvaluator::AddEnforcementLiteral(int ct_index, int lit) {
DCHECK(creation_phase_);
const int var = PositiveRef(lit);
if (literal_entries_.size() <= var) {
literal_entries_.resize(var + 1);
}
literal_entries_[var].push_back(
{.ct_index = ct_index, .positive = RefIsPositive(lit)});
}
void LinearIncrementalEvaluator::AddLiteral(int ct_index, int lit,
int64_t coeff) {
DCHECK(creation_phase_);
if (RefIsPositive(lit)) {
AddTerm(ct_index, lit, coeff, 0);
} else {
AddTerm(ct_index, PositiveRef(lit), -coeff, coeff);
}
}
void LinearIncrementalEvaluator::AddTerm(int ct_index, int var, int64_t coeff,
int64_t offset) {
DCHECK(creation_phase_);
DCHECK_GE(var, 0);
if (coeff == 0) return;
if (var_entries_.size() <= var) {
var_entries_.resize(var + 1);
}
if (!var_entries_[var].empty() &&
var_entries_[var].back().ct_index == ct_index) {
var_entries_[var].back().coefficient += coeff;
if (var_entries_[var].back().coefficient == 0) {
var_entries_[var].pop_back();
}
} else {
var_entries_[var].push_back({.ct_index = ct_index, .coefficient = coeff});
}
AddOffset(ct_index, offset);
DCHECK(VarIsConsistent(var));
}
void LinearIncrementalEvaluator::AddOffset(int ct_index, int64_t offset) {
DCHECK(creation_phase_);
offsets_[ct_index] += offset;
}
void LinearIncrementalEvaluator::AddLinearExpression(
int ct_index, const LinearExpressionProto& expr, int64_t multiplier) {
DCHECK(creation_phase_);
AddOffset(ct_index, expr.offset() * multiplier);
for (int i = 0; i < expr.vars_size(); ++i) {
if (expr.coeffs(i) * multiplier == 0) continue;
AddTerm(ct_index, expr.vars(i), expr.coeffs(i) * multiplier);
}
}
bool LinearIncrementalEvaluator::VarIsConsistent(int var) const {
if (var_entries_.size() <= var) return true;
absl::flat_hash_set<int> visited;
for (const Entry& entry : var_entries_[var]) {
if (!visited.insert(entry.ct_index).second) return false;
}
return true;
}
void LinearIncrementalEvaluator::ComputeInitialActivities(
absl::Span<const int64_t> solution) {
DCHECK(!creation_phase_);
// Resets the activity as the offset and the number of false enforcement to 0.
activities_ = offsets_;
in_last_affected_variables_.resize(columns_.size(), false);
num_false_enforcement_.assign(num_constraints_, 0);
// Update these numbers for all columns.
const int num_vars = columns_.size();
for (int var = 0; var < num_vars; ++var) {
const SpanData& data = columns_[var];
const int64_t value = solution[var];
if (value == 0 && data.num_pos_literal > 0) {
const int* ct_indices = &ct_buffer_[data.start];
for (int k = 0; k < data.num_pos_literal; ++k) {
num_false_enforcement_[ct_indices[k]]++;
}
}
if (value == 1 && data.num_neg_literal > 0) {
const int* ct_indices = &ct_buffer_[data.start + data.num_pos_literal];
for (int k = 0; k < data.num_neg_literal; ++k) {
num_false_enforcement_[ct_indices[k]]++;
}
}
if (value != 0 && data.num_linear_entries > 0) {
const int* ct_indices =
&ct_buffer_[data.start + data.num_pos_literal + data.num_neg_literal];
const int64_t* coeffs = &coeff_buffer_[data.linear_start];
for (int k = 0; k < data.num_linear_entries; ++k) {
activities_[ct_indices[k]] += coeffs[k] * value;
}
}
}
// Cache violations (not counting enforcement).
for (int c = 0; c < num_constraints_; ++c) {
distances_[c] = domains_[c].Distance(activities_[c]);
is_violated_[c] = Violation(c) > 0;
}
}
void LinearIncrementalEvaluator::ClearAffectedVariables() {
if (10 * last_affected_variables_.size() < columns_.size()) {
// Sparse.
in_last_affected_variables_.resize(columns_.size(), false);
for (const int var : last_affected_variables_) {
in_last_affected_variables_[var] = false;
}
} else {
// Dense.
in_last_affected_variables_.assign(columns_.size(), false);
}
last_affected_variables_.clear();
DCHECK(std::all_of(in_last_affected_variables_.begin(),
in_last_affected_variables_.end(),
[](bool b) { return !b; }));
}
// Tricky: Here we re-use in_last_affected_variables_ to resest
// var_to_score_change. And in particular we need to list all variable whose
// score changed here. Not just the one for which we have a decrease.
void LinearIncrementalEvaluator::UpdateScoreOnWeightUpdate(
int c, absl::Span<const int64_t> jump_deltas,
absl::Span<double> var_to_score_change) {
if (c >= rows_.size()) return;
DCHECK_EQ(num_false_enforcement_[c], 0);
const SpanData& data = rows_[c];
// Update enforcement part. Because we only update weight of currently
// infeasible constraint, all change are 0 -> 1 transition and change by the
// same amount, which is the current distance.
const double enforcement_change = static_cast<double>(-distances_[c]);
if (enforcement_change != 0.0) {
int i = data.start;
const int end = data.num_pos_literal + data.num_neg_literal;
num_ops_ += end;
for (int k = 0; k < end; ++k, ++i) {
const int var = row_var_buffer_[i];
if (!in_last_affected_variables_[var]) {
var_to_score_change[var] = enforcement_change;
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
} else {
var_to_score_change[var] += enforcement_change;
}
}
}
// Update linear part.
if (data.num_linear_entries > 0) {
const int* row_vars = &row_var_buffer_[data.start + data.num_pos_literal +
data.num_neg_literal];
const int64_t* row_coeffs = &row_coeff_buffer_[data.linear_start];
num_ops_ += 2 * data.num_linear_entries;
// Computing general Domain distance is slow.
// TODO(user): optimize even more for one sided constraints.
// Note(user): I tried to factor the two usage of this, but it is slower.
const Domain& rhs = domains_[c];
const int64_t rhs_min = rhs.Min();
const int64_t rhs_max = rhs.Max();
const bool is_simple = rhs.NumIntervals() == 2;
const auto violation = [&rhs, rhs_min, rhs_max, is_simple](int64_t v) {
if (v >= rhs_max) {
return v - rhs_max;
} else if (v <= rhs_min) {
return rhs_min - v;
} else {
return is_simple ? int64_t{0} : rhs.Distance(v);
}
};
const int64_t old_distance = distances_[c];
const int64_t activity = activities_[c];
for (int k = 0; k < data.num_linear_entries; ++k) {
const int var = row_vars[k];
const int64_t coeff = row_coeffs[k];
const int64_t diff =
violation(activity + coeff * jump_deltas[var]) - old_distance;
if (!in_last_affected_variables_[var]) {
var_to_score_change[var] = static_cast<double>(diff);
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
} else {
var_to_score_change[var] += static_cast<double>(diff);
}
}
}
}
void LinearIncrementalEvaluator::UpdateScoreOnNewlyEnforced(
int c, double weight, absl::Span<const int64_t> jump_deltas,
absl::Span<double> jump_scores) {
const SpanData& data = rows_[c];
// Everyone else had a zero cost transition that now become enforced ->
// unenforced. So they all have better score.
const double weight_time_violation =
weight * static_cast<double>(distances_[c]);
if (weight_time_violation > 0.0) {
int i = data.start;
const int end = data.num_pos_literal + data.num_neg_literal;
num_ops_ += end;
for (int k = 0; k < end; ++k, ++i) {
const int var = row_var_buffer_[i];
jump_scores[var] -= weight_time_violation;
if (!in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
// Update linear part! It was zero and is now a diff.
{
int i = data.start + data.num_pos_literal + data.num_neg_literal;
int j = data.linear_start;
num_ops_ += 2 * data.num_linear_entries;
const int64_t old_distance = distances_[c];
for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
const int var = row_var_buffer_[i];
const int64_t coeff = row_coeff_buffer_[j];
const int64_t new_distance =
domains_[c].Distance(activities_[c] + coeff * jump_deltas[var]);
jump_scores[var] +=
weight * static_cast<double>(new_distance - old_distance);
if (!in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
}
void LinearIncrementalEvaluator::UpdateScoreOnNewlyUnenforced(
int c, double weight, absl::Span<const int64_t> jump_deltas,
absl::Span<double> jump_scores) {
const SpanData& data = rows_[c];
// Everyone else had a enforced -> unenforced transition that now become zero.
// So they all have worst score, and we don't need to update
// last_affected_variables_.
const double weight_time_violation =
weight * static_cast<double>(distances_[c]);
if (weight_time_violation > 0.0) {
int i = data.start;
const int end = data.num_pos_literal + data.num_neg_literal;
num_ops_ += end;
for (int k = 0; k < end; ++k, ++i) {
const int var = row_var_buffer_[i];
jump_scores[var] += weight_time_violation;
}
}
// Update linear part! It had a diff and is now zero.
{
int i = data.start + data.num_pos_literal + data.num_neg_literal;
int j = data.linear_start;
num_ops_ += 2 * data.num_linear_entries;
const int64_t old_distance = distances_[c];
for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
const int var = row_var_buffer_[i];
const int64_t coeff = row_coeff_buffer_[j];
const int64_t new_distance =
domains_[c].Distance(activities_[c] + coeff * jump_deltas[var]);
jump_scores[var] -=
weight * static_cast<double>(new_distance - old_distance);
if (!in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
}
// We just need to modify the old/new transition that decrease the number of
// enforcement literal at false.
void LinearIncrementalEvaluator::UpdateScoreOfEnforcementIncrease(
int c, double score_change, absl::Span<const int64_t> jump_deltas,
absl::Span<double> jump_scores) {
if (score_change == 0.0) return;
const SpanData& data = rows_[c];
int i = data.start;
num_ops_ += data.num_pos_literal;
for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
const int var = row_var_buffer_[i];
if (jump_deltas[var] == 1) {
jump_scores[var] += score_change;
if (score_change < 0.0 && !in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
num_ops_ += data.num_neg_literal;
for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
const int var = row_var_buffer_[i];
if (jump_deltas[var] == -1) {
jump_scores[var] += score_change;
if (score_change < 0.0 && !in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
}
void LinearIncrementalEvaluator::UpdateScoreOnActivityChange(
int c, double weight, int64_t activity_delta,
absl::Span<const int64_t> jump_deltas, absl::Span<double> jump_scores) {
if (activity_delta == 0) return;
const SpanData& data = rows_[c];
// In some cases, we can know that the score of all the involved variable
// will not change. This is the case if whatever 1 variable change the
// violation delta before/after is the same.
//
// TODO(user): Maintain more precise bounds.
// - We could easily compute on each ComputeInitialActivities() the
// maximum increase/decrease per variable, and take the max as each
// variable changes?
// - Know if a constraint is only <= or >= !
const int64_t old_activity = activities_[c];
const int64_t new_activity = old_activity + activity_delta;
int64_t min_range;
int64_t max_range;
if (new_activity > old_activity) {
min_range = old_activity - row_max_variations_[c];
max_range = new_activity + row_max_variations_[c];
} else {
min_range = new_activity - row_max_variations_[c];
max_range = old_activity + row_max_variations_[c];
}
// If the violation delta was zero and will still always be zero, we can skip.
if (Domain(min_range, max_range).IsIncludedIn(domains_[c])) return;
// Enforcement is always enforced -> un-enforced.
// So it was -weight_time_distance and is now -weight_time_new_distance.
const double delta =
-weight *
static_cast<double>(domains_[c].Distance(new_activity) - distances_[c]);
if (delta != 0.0) {
int i = data.start;
const int end = data.num_pos_literal + data.num_neg_literal;
num_ops_ += end;
for (int k = 0; k < end; ++k, ++i) {
const int var = row_var_buffer_[i];
jump_scores[var] += delta;
if (delta < 0.0 && !in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
// If we are infeasible and no move can correct it, both old_b - old_a and
// new_b - new_a will have the same value. We only needed to update the
// violation of the enforced literal.
if (min_range >= domains_[c].Max() || max_range <= domains_[c].Min()) return;
// Update linear part.
if (data.num_linear_entries > 0) {
const int* row_vars = &row_var_buffer_[data.start + data.num_pos_literal +
data.num_neg_literal];
const int64_t* row_coeffs = &row_coeff_buffer_[data.linear_start];
num_ops_ += 2 * data.num_linear_entries;
// Computing general Domain distance is slow.
// TODO(user): optimize even more for one sided constraints.
// Note(user): I tried to factor the two usage of this, but it is slower.
const Domain& rhs = domains_[c];
const int64_t rhs_min = rhs.Min();
const int64_t rhs_max = rhs.Max();
const bool is_simple = rhs.NumIntervals() == 2;
const auto violation = [&rhs, rhs_min, rhs_max, is_simple](int64_t v) {
if (v >= rhs_max) {
return v - rhs_max;
} else if (v <= rhs_min) {
return rhs_min - v;
} else {
return is_simple ? int64_t{0} : rhs.Distance(v);
}
};
const int64_t old_a_minus_new_a =
distances_[c] - domains_[c].Distance(new_activity);
for (int k = 0; k < data.num_linear_entries; ++k) {
const int var = row_vars[k];
const int64_t impact = row_coeffs[k] * jump_deltas[var];
const int64_t old_b = violation(old_activity + impact);
const int64_t new_b = violation(new_activity + impact);
// The old score was:
// weight * static_cast<double>(old_b - old_a);
// the new score is
// weight * static_cast<double>(new_b - new_a); so the diff is:
// weight * static_cast<double>(new_b - new_a - old_b + old_a)
const int64_t diff = old_a_minus_new_a + new_b - old_b;
// TODO(user): If a variable is at its lower (resp. upper) bound, then
// we know that the score will always move in the same direction, so we
// might skip the last_affected_variables_ update.
jump_scores[var] += weight * static_cast<double>(diff);
if (!in_last_affected_variables_[var]) {
in_last_affected_variables_[var] = true;
last_affected_variables_.push_back(var);
}
}
}
}
// Note that the code assumes that a column has no duplicates ct indices.
void LinearIncrementalEvaluator::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_violation) {
DCHECK(!creation_phase_);
DCHECK_NE(delta, 0);
if (var >= columns_.size()) return;
const SpanData& data = columns_[var];
int i = data.start;
num_ops_ += data.num_pos_literal;
for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
const int c = ct_buffer_[i];
const int64_t v0 = Violation(c);
if (delta == 1) {
num_false_enforcement_[c]--;
DCHECK_GE(num_false_enforcement_[c], 0);
if (num_false_enforcement_[c] == 0) {
UpdateScoreOnNewlyEnforced(c, weights[c], jump_deltas, jump_scores);
} else if (num_false_enforcement_[c] == 1) {
const double enforcement_change =
weights[c] * static_cast<double>(distances_[c]);
UpdateScoreOfEnforcementIncrease(c, enforcement_change, jump_deltas,
jump_scores);
}
} else {
num_false_enforcement_[c]++;
if (num_false_enforcement_[c] == 1) {
UpdateScoreOnNewlyUnenforced(c, weights[c], jump_deltas, jump_scores);
} else if (num_false_enforcement_[c] == 2) {
const double enforcement_change =
weights[c] * static_cast<double>(distances_[c]);
UpdateScoreOfEnforcementIncrease(c, -enforcement_change, jump_deltas,
jump_scores);
}
}
const int64_t v1 = Violation(c);
is_violated_[c] = v1 > 0;
if (v1 != v0) {
constraints_with_changed_violation->push_back(c);
}
}
num_ops_ += data.num_neg_literal;
for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
const int c = ct_buffer_[i];
const int64_t v0 = Violation(c);
if (delta == -1) {
num_false_enforcement_[c]--;
DCHECK_GE(num_false_enforcement_[c], 0);
if (num_false_enforcement_[c] == 0) {
UpdateScoreOnNewlyEnforced(c, weights[c], jump_deltas, jump_scores);
} else if (num_false_enforcement_[c] == 1) {
const double enforcement_change =
weights[c] * static_cast<double>(distances_[c]);
UpdateScoreOfEnforcementIncrease(c, enforcement_change, jump_deltas,
jump_scores);
}
} else {
num_false_enforcement_[c]++;
if (num_false_enforcement_[c] == 1) {
UpdateScoreOnNewlyUnenforced(c, weights[c], jump_deltas, jump_scores);
} else if (num_false_enforcement_[c] == 2) {
const double enforcement_change =
weights[c] * static_cast<double>(distances_[c]);
UpdateScoreOfEnforcementIncrease(c, -enforcement_change, jump_deltas,
jump_scores);
}
}
const int64_t v1 = Violation(c);
is_violated_[c] = v1 > 0;
if (v1 != v0) {
constraints_with_changed_violation->push_back(c);
}
}
int j = data.linear_start;
num_ops_ += 2 * data.num_linear_entries;
for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
const int c = ct_buffer_[i];
const int64_t v0 = Violation(c);
const int64_t coeff = coeff_buffer_[j];
if (num_false_enforcement_[c] == 1) {
// Only the 1 -> 0 are impacted.
// This is the same as the 1->2 transition, but the old 1->0 needs to
// be changed from - weight * distance to - weight * new_distance.
const int64_t new_distance =
domains_[c].Distance(activities_[c] + coeff * delta);
if (new_distance != distances_[c]) {
UpdateScoreOfEnforcementIncrease(
c, -weights[c] * static_cast<double>(distances_[c] - new_distance),
jump_deltas, jump_scores);
}
} else if (num_false_enforcement_[c] == 0) {
UpdateScoreOnActivityChange(c, weights[c], coeff * delta, jump_deltas,
jump_scores);
}
activities_[c] += coeff * delta;
distances_[c] = domains_[c].Distance(activities_[c]);
const int64_t v1 = Violation(c);
is_violated_[c] = v1 > 0;
if (v1 != v0) {
constraints_with_changed_violation->push_back(c);
}
}
}
int64_t LinearIncrementalEvaluator::Activity(int c) const {
return activities_[c];
}
int64_t LinearIncrementalEvaluator::Violation(int c) const {
return num_false_enforcement_[c] > 0 ? 0 : distances_[c];
}
bool LinearIncrementalEvaluator::IsViolated(int c) const {
DCHECK_EQ(is_violated_[c], Violation(c) > 0);
return is_violated_[c];
}
bool LinearIncrementalEvaluator::ReduceBounds(int c, int64_t lb, int64_t ub) {
if (domains_[c].Min() >= lb && domains_[c].Max() <= ub) return false;
domains_[c] = domains_[c].IntersectionWith(Domain(lb, ub));
distances_[c] = domains_[c].Distance(activities_[c]);
return true;
}
double LinearIncrementalEvaluator::WeightedViolation(
absl::Span<const double> weights) const {
double result = 0.0;
DCHECK_GE(weights.size(), num_constraints_);
for (int c = 0; c < num_constraints_; ++c) {
if (num_false_enforcement_[c] > 0) continue;
result += weights[c] * static_cast<double>(distances_[c]);
}
return result;
}
// Most of the time is spent in this function.
//
// TODO(user): We can safely abort early if we know that delta will be >= 0.
// TODO(user): Maybe we can compute an absolute value instead of removing
// old_distance.
double LinearIncrementalEvaluator::WeightedViolationDelta(
absl::Span<const double> weights, int var, int64_t delta) const {
DCHECK_NE(delta, 0);
if (var >= columns_.size()) return 0.0;
const SpanData& data = columns_[var];
int i = data.start;
double result = 0.0;
num_ops_ += data.num_pos_literal;
for (int k = 0; k < data.num_pos_literal; ++k, ++i) {
const int c = ct_buffer_[i];
if (num_false_enforcement_[c] == 0) {
// Since delta != 0, we are sure this is an enforced -> unenforced change.
DCHECK_EQ(delta, -1);
result -= weights[c] * static_cast<double>(distances_[c]);
} else {
if (delta == 1 && num_false_enforcement_[c] == 1) {
result += weights[c] * static_cast<double>(distances_[c]);
}
}
}
num_ops_ += data.num_neg_literal;
for (int k = 0; k < data.num_neg_literal; ++k, ++i) {
const int c = ct_buffer_[i];
if (num_false_enforcement_[c] == 0) {
// Since delta != 0, we are sure this is an enforced -> unenforced change.
DCHECK_EQ(delta, 1);
result -= weights[c] * static_cast<double>(distances_[c]);
} else {
if (delta == -1 && num_false_enforcement_[c] == 1) {
result += weights[c] * static_cast<double>(distances_[c]);
}
}
}
int j = data.linear_start;
num_ops_ += 2 * data.num_linear_entries;
for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
const int c = ct_buffer_[i];
if (num_false_enforcement_[c] > 0) continue;
const int64_t coeff = coeff_buffer_[j];
const int64_t old_distance = distances_[c];
const int64_t new_distance =
domains_[c].Distance(activities_[c] + coeff * delta);
result += weights[c] * static_cast<double>(new_distance - old_distance);
}
return result;
}
bool LinearIncrementalEvaluator::AppearsInViolatedConstraints(int var) const {
if (var >= columns_.size()) return false;
for (const int c : VarToConstraints(var)) {
if (Violation(c) > 0) return true;
}
return false;
}
std::vector<int64_t> LinearIncrementalEvaluator::SlopeBreakpoints(
int var, int64_t current_value, const Domain& var_domain) const {
std::vector<int64_t> result = var_domain.FlattenedIntervals();
if (var_domain.Size() <= 2 || var >= columns_.size()) return result;
const SpanData& data = columns_[var];
int i = data.start + data.num_pos_literal + data.num_neg_literal;
int j = data.linear_start;
for (int k = 0; k < data.num_linear_entries; ++k, ++i, ++j) {
const int c = ct_buffer_[i];
if (num_false_enforcement_[c] > 0) continue;
// We only consider min / max.
// There is a change when we cross the slack.
// TODO(user): Deal with holes?
const int64_t coeff = coeff_buffer_[j];
const int64_t activity = activities_[c] - current_value * coeff;
const int64_t slack_min = CapSub(domains_[c].Min(), activity);
const int64_t slack_max = CapSub(domains_[c].Max(), activity);
if (slack_min != std::numeric_limits<int64_t>::min()) {
const int64_t ceil_bp = CeilOfRatio(slack_min, coeff);
if (ceil_bp != result.back() && var_domain.Contains(ceil_bp)) {
result.push_back(ceil_bp);
}
const int64_t floor_bp = FloorOfRatio(slack_min, coeff);
if (floor_bp != result.back() && var_domain.Contains(floor_bp)) {
result.push_back(floor_bp);
}
}
if (slack_min != slack_max &&
slack_max != std::numeric_limits<int64_t>::min()) {
const int64_t ceil_bp = CeilOfRatio(slack_max, coeff);
if (ceil_bp != result.back() && var_domain.Contains(ceil_bp)) {
result.push_back(ceil_bp);
}
const int64_t floor_bp = FloorOfRatio(slack_max, coeff);
if (floor_bp != result.back() && var_domain.Contains(floor_bp)) {
result.push_back(floor_bp);
}
}
}
gtl::STLSortAndRemoveDuplicates(&result);
return result;
}
void LinearIncrementalEvaluator::PrecomputeCompactView(
absl::Span<const int64_t> var_max_variation) {
creation_phase_ = false;
if (num_constraints_ == 0) return;
// Compute the total size.
// Note that at this point the constraint indices are not "encoded" yet.
int total_size = 0;
int total_linear_size = 0;
tmp_row_sizes_.assign(num_constraints_, 0);
tmp_row_num_positive_literals_.assign(num_constraints_, 0);
tmp_row_num_negative_literals_.assign(num_constraints_, 0);
tmp_row_num_linear_entries_.assign(num_constraints_, 0);
for (const auto& column : literal_entries_) {
total_size += column.size();
for (const auto [c, is_positive] : column) {
tmp_row_sizes_[c]++;
if (is_positive) {
tmp_row_num_positive_literals_[c]++;
} else {
tmp_row_num_negative_literals_[c]++;
}
}
}
row_max_variations_.assign(num_constraints_, 0);
for (int var = 0; var < var_entries_.size(); ++var) {
const int64_t range = var_max_variation[var];
const auto& column = var_entries_[var];
total_size += column.size();
total_linear_size += column.size();
for (const auto [c, coeff] : column) {
tmp_row_sizes_[c]++;
tmp_row_num_linear_entries_[c]++;
row_max_variations_[c] =
std::max(row_max_variations_[c], range * std::abs(coeff));
}
}
// Compactify for faster WeightedViolationDelta().
ct_buffer_.reserve(total_size);
coeff_buffer_.reserve(total_linear_size);
columns_.resize(std::max(literal_entries_.size(), var_entries_.size()));
for (int var = 0; var < columns_.size(); ++var) {
columns_[var].start = static_cast<int>(ct_buffer_.size());
columns_[var].linear_start = static_cast<int>(coeff_buffer_.size());
if (var < literal_entries_.size()) {
for (const auto [c, is_positive] : literal_entries_[var]) {
if (is_positive) {
columns_[var].num_pos_literal++;
ct_buffer_.push_back(c);
}
}
for (const auto [c, is_positive] : literal_entries_[var]) {
if (!is_positive) {
columns_[var].num_neg_literal++;
ct_buffer_.push_back(c);
}
}
}
if (var < var_entries_.size()) {
for (const auto [c, coeff] : var_entries_[var]) {
columns_[var].num_linear_entries++;
ct_buffer_.push_back(c);
coeff_buffer_.push_back(coeff);
}
}
}
// We do not need var_entries_ or literal_entries_ anymore.
//
// TODO(user): We could delete them before. But at the time of this
// optimization, I didn't want to change the behavior of the algorithm at all.
gtl::STLClearObject(&var_entries_);
gtl::STLClearObject(&literal_entries_);
// Initialize the SpanData.
// Transform tmp_row_sizes_ to starts in the row_var_buffer_.
// Transform tmp_row_num_linear_entries_ to starts in the row_coeff_buffer_.
int offset = 0;
int linear_offset = 0;
rows_.resize(num_constraints_);
for (int c = 0; c < num_constraints_; ++c) {
rows_[c].num_pos_literal = tmp_row_num_positive_literals_[c];
rows_[c].num_neg_literal = tmp_row_num_negative_literals_[c];
rows_[c].num_linear_entries = tmp_row_num_linear_entries_[c];
rows_[c].start = offset;
offset += tmp_row_sizes_[c];
tmp_row_sizes_[c] = rows_[c].start;
rows_[c].linear_start = linear_offset;
linear_offset += tmp_row_num_linear_entries_[c];
tmp_row_num_linear_entries_[c] = rows_[c].linear_start;
}
DCHECK_EQ(offset, total_size);
DCHECK_EQ(linear_offset, total_linear_size);
// Copy data.
row_var_buffer_.resize(total_size);
row_coeff_buffer_.resize(total_linear_size);
for (int var = 0; var < columns_.size(); ++var) {
const SpanData& data = columns_[var];
int i = data.start;
for (int k = 0; k < data.num_pos_literal; ++i, ++k) {
const int c = ct_buffer_[i];
row_var_buffer_[tmp_row_sizes_[c]++] = var;
}
}
for (int var = 0; var < columns_.size(); ++var) {
const SpanData& data = columns_[var];
int i = data.start + data.num_pos_literal;
for (int k = 0; k < data.num_neg_literal; ++i, ++k) {
const int c = ct_buffer_[i];
row_var_buffer_[tmp_row_sizes_[c]++] = var;
}
}
for (int var = 0; var < columns_.size(); ++var) {
const SpanData& data = columns_[var];
int i = data.start + data.num_pos_literal + data.num_neg_literal;
int j = data.linear_start;
for (int k = 0; k < data.num_linear_entries; ++i, ++j, ++k) {
const int c = ct_buffer_[i];
row_var_buffer_[tmp_row_sizes_[c]++] = var;
row_coeff_buffer_[tmp_row_num_linear_entries_[c]++] = coeff_buffer_[j];
}
}
cached_deltas_.assign(columns_.size(), 0);
cached_scores_.assign(columns_.size(), 0);
last_affected_variables_.ClearAndReserve(columns_.size());
}
bool LinearIncrementalEvaluator::ViolationChangeIsConvex(int var) const {
for (const int c : VarToConstraints(var)) {
if (domains_[c].NumIntervals() > 2) return false;
}
return true;
}
// ----- CompiledConstraint -----
void CompiledConstraint::InitializeViolation(
absl::Span<const int64_t> solution) {
violation_ = ComputeViolation(solution);
}
void CompiledConstraint::PerformMove(
int var, int64_t old_value,
absl::Span<const int64_t> solution_with_new_value) {
violation_ += ViolationDelta(var, old_value, solution_with_new_value);
}
int64_t CompiledConstraint::ViolationDelta(int, int64_t,
absl::Span<const int64_t> solution) {
return ComputeViolation(solution) - violation_;
}
// ----- CompiledConstraintWithProto -----
CompiledConstraintWithProto::CompiledConstraintWithProto(
const ConstraintProto& ct_proto)
: ct_proto_(ct_proto) {}
std::vector<int> CompiledConstraintWithProto::UsedVariables(
const CpModelProto& model_proto) const {
std::vector<int> result = sat::UsedVariables(ct_proto_);
for (const int i_var : UsedIntervals(ct_proto_)) {
const ConstraintProto& interval_proto = model_proto.constraints(i_var);
for (const int var : sat::UsedVariables(interval_proto)) {
result.push_back(var);
}
}
gtl::STLSortAndRemoveDuplicates(&result);
result.shrink_to_fit();
return result;
}
// ----- CompiledBoolXorConstraint -----
CompiledBoolXorConstraint::CompiledBoolXorConstraint(