forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_presolve.cc
7319 lines (6629 loc) · 273 KB
/
cp_model_presolve.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-2021 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/cp_model_presolve.h"
#include <sys/stat.h>
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash.h"
#include "absl/random/random.h"
#include "absl/strings/str_join.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/port/proto_utils.h"
#include "ortools/sat/circuit.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_checker.h"
#include "ortools/sat/cp_model_expand.h"
#include "ortools/sat/cp_model_loader.h"
#include "ortools/sat/cp_model_mapping.h"
#include "ortools/sat/cp_model_objective.h"
#include "ortools/sat/cp_model_symmetries.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/diffn_util.h"
#include "ortools/sat/presolve_util.h"
#include "ortools/sat/probing.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/simplification.h"
#include "ortools/sat/var_domination.h"
namespace operations_research {
namespace sat {
bool CpModelPresolver::RemoveConstraint(ConstraintProto* ct) {
ct->Clear();
return true;
}
void CpModelPresolver::RemoveEmptyConstraints() {
// Remove all empty constraints. Note that we need to remap the interval
// references.
std::vector<int> interval_mapping(context_->working_model->constraints_size(),
-1);
int new_num_constraints = 0;
const int old_num_non_empty_constraints =
context_->working_model->constraints_size();
for (int c = 0; c < old_num_non_empty_constraints; ++c) {
const auto type = context_->working_model->constraints(c).constraint_case();
if (type == ConstraintProto::ConstraintCase::CONSTRAINT_NOT_SET) continue;
if (type == ConstraintProto::ConstraintCase::kInterval) {
interval_mapping[c] = new_num_constraints;
}
context_->working_model->mutable_constraints(new_num_constraints++)
->Swap(context_->working_model->mutable_constraints(c));
}
context_->working_model->mutable_constraints()->DeleteSubrange(
new_num_constraints, old_num_non_empty_constraints - new_num_constraints);
for (ConstraintProto& ct_ref :
*context_->working_model->mutable_constraints()) {
ApplyToAllIntervalIndices(
[&interval_mapping](int* ref) {
*ref = interval_mapping[*ref];
CHECK_NE(-1, *ref);
},
&ct_ref);
}
}
bool CpModelPresolver::PresolveEnforcementLiteral(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (!HasEnforcementLiteral(*ct)) return false;
int new_size = 0;
const int old_size = ct->enforcement_literal().size();
for (const int literal : ct->enforcement_literal()) {
if (context_->LiteralIsTrue(literal)) {
// We can remove a literal at true.
context_->UpdateRuleStats("true enforcement literal");
continue;
}
if (context_->LiteralIsFalse(literal)) {
context_->UpdateRuleStats("false enforcement literal");
return RemoveConstraint(ct);
}
if (context_->VariableIsUniqueAndRemovable(literal)) {
// We can simply set it to false and ignore the constraint in this case.
context_->UpdateRuleStats("enforcement literal not used");
CHECK(context_->SetLiteralToFalse(literal));
return RemoveConstraint(ct);
}
// If the literal only appear in the objective, we might be able to fix it
// to false. TODO(user): generalize if the literal always appear with the
// same polarity.
if (context_->VariableWithCostIsUniqueAndRemovable(literal)) {
const int64_t obj_coeff =
gtl::FindOrDie(context_->ObjectiveMap(), PositiveRef(literal));
if (RefIsPositive(literal) == (obj_coeff > 0)) {
// It is just more advantageous to set it to false!
context_->UpdateRuleStats("enforcement literal with unique direction");
CHECK(context_->SetLiteralToFalse(literal));
return RemoveConstraint(ct);
}
}
ct->set_enforcement_literal(new_size++, literal);
}
ct->mutable_enforcement_literal()->Truncate(new_size);
return new_size != old_size;
}
bool CpModelPresolver::PresolveBoolXor(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (HasEnforcementLiteral(*ct)) return false;
int new_size = 0;
bool changed = false;
int num_true_literals = 0;
int true_literal = std::numeric_limits<int32_t>::min();
for (const int literal : ct->bool_xor().literals()) {
// TODO(user): More generally, if a variable appear in only bool xor
// constraints, we can simply eliminate it using linear algebra on Z/2Z.
// This should solve in polynomial time the parity-learning*.fzn problems
// for instance. This seems low priority, but it is also easy to do. Even
// better would be to have a dedicated propagator with all bool_xor
// constraints that do the necessary linear algebra.
if (context_->VariableIsUniqueAndRemovable(literal)) {
context_->UpdateRuleStats("TODO bool_xor: remove constraint");
}
if (context_->LiteralIsFalse(literal)) {
context_->UpdateRuleStats("bool_xor: remove false literal");
changed = true;
continue;
} else if (context_->LiteralIsTrue(literal)) {
true_literal = literal; // Keep if we need to put one back.
num_true_literals++;
continue;
}
ct->mutable_bool_xor()->set_literals(new_size++, literal);
}
if (new_size == 0) {
if (num_true_literals % 2 == 0) {
return context_->NotifyThatModelIsUnsat("bool_xor: always false");
} else {
context_->UpdateRuleStats("bool_xor: always true");
return RemoveConstraint(ct);
}
} else if (new_size == 1) { // We can fix the only active literal.
if (num_true_literals % 2 == 0) {
if (!context_->SetLiteralToTrue(ct->bool_xor().literals(0))) {
return context_->NotifyThatModelIsUnsat(
"bool_xor: cannot fix last literal");
}
} else {
if (!context_->SetLiteralToFalse(ct->bool_xor().literals(0))) {
return context_->NotifyThatModelIsUnsat(
"bool_xor: cannot fix last literal");
}
}
context_->UpdateRuleStats("bool_xor: one active literal");
return RemoveConstraint(ct);
} else if (new_size == 2) { // We can simplify the bool_xor.
const int a = ct->bool_xor().literals(0);
const int b = ct->bool_xor().literals(1);
if (num_true_literals % 2 == 0) { // a == not(b).
context_->StoreBooleanEqualityRelation(a, NegatedRef(b));
} else { // a == b.
context_->StoreBooleanEqualityRelation(a, b);
}
context_->UpdateNewConstraintsVariableUsage();
context_->UpdateRuleStats("bool_xor: two active literals");
return RemoveConstraint(ct);
}
if (num_true_literals % 2 == 1) {
CHECK_NE(true_literal, std::numeric_limits<int32_t>::min());
ct->mutable_bool_xor()->set_literals(new_size++, true_literal);
}
if (num_true_literals > 1) {
context_->UpdateRuleStats("bool_xor: remove even number of true literals");
changed = true;
}
ct->mutable_bool_xor()->mutable_literals()->Truncate(new_size);
return changed;
}
bool CpModelPresolver::PresolveBoolOr(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
// Move the enforcement literal inside the clause if any. Note that we do not
// mark this as a change since the literal in the constraint are the same.
if (HasEnforcementLiteral(*ct)) {
context_->UpdateRuleStats("bool_or: removed enforcement literal");
for (const int literal : ct->enforcement_literal()) {
ct->mutable_bool_or()->add_literals(NegatedRef(literal));
}
ct->clear_enforcement_literal();
}
// Inspects the literals and deal with fixed ones.
bool changed = false;
context_->tmp_literals.clear();
context_->tmp_literal_set.clear();
for (const int literal : ct->bool_or().literals()) {
if (context_->LiteralIsFalse(literal)) {
changed = true;
continue;
}
if (context_->LiteralIsTrue(literal)) {
context_->UpdateRuleStats("bool_or: always true");
return RemoveConstraint(ct);
}
// We can just set the variable to true in this case since it is not
// used in any other constraint (note that we artificially bump the
// objective var usage by 1).
if (context_->VariableIsUniqueAndRemovable(literal)) {
context_->UpdateRuleStats("bool_or: singleton");
if (!context_->SetLiteralToTrue(literal)) return true;
return RemoveConstraint(ct);
}
if (context_->tmp_literal_set.contains(NegatedRef(literal))) {
context_->UpdateRuleStats("bool_or: always true");
return RemoveConstraint(ct);
}
if (context_->tmp_literal_set.contains(literal)) {
changed = true;
} else {
context_->tmp_literal_set.insert(literal);
context_->tmp_literals.push_back(literal);
}
}
context_->tmp_literal_set.clear();
if (context_->tmp_literals.empty()) {
context_->UpdateRuleStats("bool_or: empty");
return context_->NotifyThatModelIsUnsat();
}
if (context_->tmp_literals.size() == 1) {
context_->UpdateRuleStats("bool_or: only one literal");
if (!context_->SetLiteralToTrue(context_->tmp_literals[0])) return true;
return RemoveConstraint(ct);
}
if (context_->tmp_literals.size() == 2) {
// For consistency, we move all "implication" into half-reified bool_and.
// TODO(user): merge by enforcement literal and detect implication cycles.
context_->UpdateRuleStats("bool_or: implications");
ct->add_enforcement_literal(NegatedRef(context_->tmp_literals[0]));
ct->mutable_bool_and()->add_literals(context_->tmp_literals[1]);
return changed;
}
if (changed) {
context_->UpdateRuleStats("bool_or: fixed literals");
ct->mutable_bool_or()->mutable_literals()->Clear();
for (const int lit : context_->tmp_literals) {
ct->mutable_bool_or()->add_literals(lit);
}
}
return changed;
}
// Note this constraint does not update the constraint graph. Therefore, it
// assumes that the constraint being marked as false is the constraint being
// presolved.
ABSL_MUST_USE_RESULT bool CpModelPresolver::MarkConstraintAsFalse(
ConstraintProto* ct) {
if (HasEnforcementLiteral(*ct)) {
// Change the constraint to a bool_or.
ct->mutable_bool_or()->clear_literals();
for (const int lit : ct->enforcement_literal()) {
ct->mutable_bool_or()->add_literals(NegatedRef(lit));
}
ct->clear_enforcement_literal();
PresolveBoolOr(ct);
return true;
} else {
return context_->NotifyThatModelIsUnsat();
}
}
bool CpModelPresolver::PresolveBoolAnd(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (!HasEnforcementLiteral(*ct)) {
context_->UpdateRuleStats("bool_and: non-reified.");
for (const int literal : ct->bool_and().literals()) {
if (!context_->SetLiteralToTrue(literal)) return true;
}
return RemoveConstraint(ct);
}
bool changed = false;
context_->tmp_literals.clear();
for (const int literal : ct->bool_and().literals()) {
if (context_->LiteralIsFalse(literal)) {
context_->UpdateRuleStats("bool_and: always false");
return MarkConstraintAsFalse(ct);
}
if (context_->LiteralIsTrue(literal)) {
changed = true;
continue;
}
if (context_->VariableIsUniqueAndRemovable(literal)) {
changed = true;
if (!context_->SetLiteralToTrue(literal)) return true;
continue;
}
context_->tmp_literals.push_back(literal);
}
// Note that this is not the same behavior as a bool_or:
// - bool_or means "at least one", so it is false if empty.
// - bool_and means "all literals inside true", so it is true if empty.
if (context_->tmp_literals.empty()) return RemoveConstraint(ct);
if (changed) {
ct->mutable_bool_and()->mutable_literals()->Clear();
for (const int lit : context_->tmp_literals) {
ct->mutable_bool_and()->add_literals(lit);
}
context_->UpdateRuleStats("bool_and: fixed literals");
}
// If a variable can move freely in one direction except for this constraint,
// we can make it an equality.
//
// TODO(user): also consider literal on the other side of the =>.
if (ct->enforcement_literal().size() == 1 &&
ct->bool_and().literals().size() == 1) {
const int enforcement = ct->enforcement_literal(0);
if (context_->VariableWithCostIsUniqueAndRemovable(enforcement)) {
int var = PositiveRef(enforcement);
int64_t obj_coeff = gtl::FindOrDie(context_->ObjectiveMap(), var);
if (!RefIsPositive(enforcement)) obj_coeff = -obj_coeff;
// The other case where the constraint is redundant is treated elsewhere.
if (obj_coeff < 0) {
context_->UpdateRuleStats("bool_and: dual equality.");
context_->StoreBooleanEqualityRelation(enforcement,
ct->bool_and().literals(0));
}
}
}
return changed;
}
bool CpModelPresolver::PresolveAtMostOrExactlyOne(ConstraintProto* ct) {
bool is_at_most_one = ct->constraint_case() == ConstraintProto::kAtMostOne;
const std::string name = is_at_most_one ? "at_most_one: " : "exactly_one: ";
auto* literals = is_at_most_one
? ct->mutable_at_most_one()->mutable_literals()
: ct->mutable_exactly_one()->mutable_literals();
// Deal with duplicate variable reference.
context_->tmp_literal_set.clear();
for (const int literal : *literals) {
if (context_->tmp_literal_set.contains(literal)) {
if (!context_->SetLiteralToFalse(literal)) return true;
context_->UpdateRuleStats(absl::StrCat(name, "duplicate literals"));
}
if (context_->tmp_literal_set.contains(NegatedRef(literal))) {
int num_positive = 0;
int num_negative = 0;
for (const int other : *literals) {
if (PositiveRef(other) != PositiveRef(literal)) {
if (!context_->SetLiteralToFalse(other)) return true;
context_->UpdateRuleStats(absl::StrCat(name, "x and not(x)"));
} else {
if (other == literal) {
++num_positive;
} else {
++num_negative;
}
}
}
// This is tricky for the case where the at most one reduce to (lit,
// not(lit), not(lit)) for instance.
if (num_positive > 1 && !context_->SetLiteralToFalse(literal)) {
return true;
}
if (num_negative > 1 && !context_->SetLiteralToTrue(literal)) {
return true;
}
return RemoveConstraint(ct);
}
context_->tmp_literal_set.insert(literal);
}
// Remove fixed variables.
bool changed = false;
bool transform_to_at_most_one = false;
context_->tmp_literals.clear();
for (const int literal : *literals) {
if (context_->LiteralIsTrue(literal)) {
context_->UpdateRuleStats(absl::StrCat(name, "satisfied"));
for (const int other : *literals) {
if (other != literal) {
if (!context_->SetLiteralToFalse(other)) return true;
}
}
return RemoveConstraint(ct);
}
if (context_->LiteralIsFalse(literal)) {
changed = true;
continue;
}
// A singleton variable in an at most one can just be set to zero.
//
// In an exactly one, it can be left to the postsolve to decide, and the
// rest of the constraint can be transformed to an at most one.
bool is_removable = context_->VariableIsUniqueAndRemovable(literal);
if (is_at_most_one && !is_removable &&
context_->VariableWithCostIsUniqueAndRemovable(literal)) {
const auto it = context_->ObjectiveMap().find(PositiveRef(literal));
CHECK(it != context_->ObjectiveMap().end());
const int64_t coeff = it->second;
// Fixing it to zero need to go in the correct direction.
is_removable = (coeff > 0) == RefIsPositive(literal);
}
if (is_removable) {
if (is_at_most_one) {
context_->UpdateRuleStats("at_most_one: singleton");
if (!context_->SetLiteralToFalse(literal)) return false;
changed = true;
continue;
} else {
changed = true;
is_at_most_one = true;
transform_to_at_most_one = true;
*(context_->mapping_model->add_constraints()) = *ct;
context_->UpdateRuleStats("exactly_one: singleton");
context_->MarkVariableAsRemoved(PositiveRef(literal));
continue;
}
}
context_->tmp_literals.push_back(literal);
}
if (!is_at_most_one && !transform_to_at_most_one &&
context_->ExploitExactlyOneInObjective(context_->tmp_literals)) {
context_->UpdateRuleStats("exactly_one: simplified objective");
}
if (transform_to_at_most_one) {
CHECK(changed);
ct->Clear();
literals = ct->mutable_at_most_one()->mutable_literals();
}
if (changed) {
literals->Clear();
for (const int lit : context_->tmp_literals) {
literals->Add(lit);
}
context_->UpdateRuleStats(absl::StrCat(name, "removed literals"));
}
return changed;
}
bool CpModelPresolver::PresolveAtMostOne(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
CHECK(!HasEnforcementLiteral(*ct));
const bool changed = PresolveAtMostOrExactlyOne(ct);
if (ct->constraint_case() != ConstraintProto::kAtMostOne) return changed;
// Size zero: ok.
const auto& literals = ct->at_most_one().literals();
if (literals.empty()) {
context_->UpdateRuleStats("at_most_one: empty or all false");
return RemoveConstraint(ct);
}
// Size one: always satisfied.
if (literals.size() == 1) {
context_->UpdateRuleStats("at_most_one: size one");
return RemoveConstraint(ct);
}
return changed;
}
bool CpModelPresolver::PresolveExactlyOne(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
CHECK(!HasEnforcementLiteral(*ct));
const bool changed = PresolveAtMostOrExactlyOne(ct);
if (ct->constraint_case() != ConstraintProto::kExactlyOne) return changed;
// Size zero: UNSAT.
const auto& literals = ct->exactly_one().literals();
if (literals.empty()) {
return context_->NotifyThatModelIsUnsat("exactly_one: empty or all false");
}
// Size one: fix variable.
if (literals.size() == 1) {
context_->UpdateRuleStats("exactly_one: size one");
if (!context_->SetLiteralToTrue(literals[0])) return false;
return RemoveConstraint(ct);
}
// Size two: Equivalence.
if (literals.size() == 2) {
context_->UpdateRuleStats("exactly_one: size two");
context_->StoreBooleanEqualityRelation(literals[0],
NegatedRef(literals[1]));
return RemoveConstraint(ct);
}
return changed;
}
bool CpModelPresolver::PresolveIntMax(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (ct->int_max().vars().empty()) {
context_->UpdateRuleStats("int_max: no variables!");
return MarkConstraintAsFalse(ct);
}
const int target_ref = ct->int_max().target();
// Pass 1, compute the infered min of the target, and remove duplicates.
int64_t infered_min = std::numeric_limits<int64_t>::min();
int64_t infered_max = std::numeric_limits<int64_t>::min();
bool contains_target_ref = false;
bool contains_negated_target_ref = false;
std::set<int> used_ref;
int new_size = 0;
for (const int ref : ct->int_max().vars()) {
if (ref == target_ref) contains_target_ref = true;
if (gtl::ContainsKey(used_ref, ref)) continue;
if (gtl::ContainsKey(used_ref, NegatedRef(ref)) ||
ref == NegatedRef(target_ref)) {
infered_min = std::max(infered_min, int64_t{0});
}
if (ref == NegatedRef(target_ref)) {
// x must be non-negative.
// It can be positive if they are other terms, otherwise it must be zero.
// TODO(user): more presolve in this case?
contains_negated_target_ref = true;
context_->UpdateRuleStats("int_max: x = max(-x, ...)");
if (!context_->IntersectDomainWith(
target_ref, {0, std::numeric_limits<int64_t>::max()})) {
return false;
}
}
used_ref.insert(ref);
ct->mutable_int_max()->set_vars(new_size++, ref);
infered_min = std::max(infered_min, context_->MinOf(ref));
infered_max = std::max(infered_max, context_->MaxOf(ref));
}
if (new_size < ct->int_max().vars_size()) {
context_->UpdateRuleStats("int_max: removed dup");
}
ct->mutable_int_max()->mutable_vars()->Truncate(new_size);
if (contains_target_ref) {
context_->UpdateRuleStats("int_max: x = max(x, ...)");
for (const int ref : ct->int_max().vars()) {
if (ref == target_ref) continue;
ConstraintProto* new_ct = context_->working_model->add_constraints();
*new_ct->mutable_enforcement_literal() = ct->enforcement_literal();
auto* arg = new_ct->mutable_linear();
arg->add_vars(target_ref);
arg->add_coeffs(1);
arg->add_vars(ref);
arg->add_coeffs(-1);
arg->add_domain(0);
arg->add_domain(std::numeric_limits<int64_t>::max());
}
return RemoveConstraint(ct);
}
// Compute the infered target_domain.
Domain infered_domain;
for (const int ref : ct->int_max().vars()) {
infered_domain = infered_domain.UnionWith(
context_->DomainOf(ref).IntersectionWith({infered_min, infered_max}));
}
// Update the target domain.
bool domain_reduced = false;
if (!HasEnforcementLiteral(*ct)) {
if (!context_->IntersectDomainWith(target_ref, infered_domain,
&domain_reduced)) {
return true;
}
}
// If the target is only used here and if
// infered_domain ∩ [kint64min, target_ub] ⊂ target_domain
// then the constraint is really max(...) <= target_ub and we can simplify it.
//
// This is not as easy if x = max(-x, ...) so we skip this case.
if (context_->VariableIsUniqueAndRemovable(target_ref) &&
!contains_negated_target_ref) {
const Domain& target_domain = context_->DomainOf(target_ref);
if (infered_domain
.IntersectionWith(Domain(std::numeric_limits<int64_t>::min(),
target_domain.Max()))
.IsIncludedIn(target_domain)) {
if (infered_domain.Max() <= target_domain.Max()) {
// The constraint is always satisfiable.
context_->UpdateRuleStats("int_max: always true");
} else if (ct->enforcement_literal().empty()) {
// The constraint just restrict the upper bound of its variable.
for (const int ref : ct->int_max().vars()) {
context_->UpdateRuleStats("int_max: lower than constant");
if (!context_->IntersectDomainWith(
ref, Domain(std::numeric_limits<int64_t>::min(),
target_domain.Max()))) {
return false;
}
}
} else {
// We simply transform this into n reified constraints
// enforcement => [var_i <= target_domain.Max()].
context_->UpdateRuleStats("int_max: reified lower than constant");
for (const int ref : ct->int_max().vars()) {
ConstraintProto* new_ct = context_->working_model->add_constraints();
*(new_ct->mutable_enforcement_literal()) = ct->enforcement_literal();
ct->mutable_linear()->add_vars(ref);
ct->mutable_linear()->add_coeffs(1);
ct->mutable_linear()->add_domain(std::numeric_limits<int64_t>::min());
ct->mutable_linear()->add_domain(target_domain.Max());
}
}
// In all cases we delete the original constraint.
context_->MarkVariableAsRemoved(target_ref);
*(context_->mapping_model->add_constraints()) = *ct;
return RemoveConstraint(ct);
}
}
// Pass 2, update the argument domains. Filter them eventually.
new_size = 0;
const int size = ct->int_max().vars_size();
const int64_t target_max = context_->MaxOf(target_ref);
for (const int ref : ct->int_max().vars()) {
if (!HasEnforcementLiteral(*ct)) {
if (!context_->IntersectDomainWith(
ref, Domain(std::numeric_limits<int64_t>::min(), target_max),
&domain_reduced)) {
return true;
}
}
if (context_->MaxOf(ref) >= infered_min) {
ct->mutable_int_max()->set_vars(new_size++, ref);
}
}
if (domain_reduced) {
context_->UpdateRuleStats("int_max: reduced domains");
}
bool modified = false;
if (new_size < size) {
context_->UpdateRuleStats("int_max: removed variables");
ct->mutable_int_max()->mutable_vars()->Truncate(new_size);
modified = true;
}
if (new_size == 0) {
context_->UpdateRuleStats("int_max: no variables!");
return MarkConstraintAsFalse(ct);
}
if (new_size == 1) {
// Convert to an equality. Note that we create a new constraint otherwise it
// might not be processed again.
context_->UpdateRuleStats("int_max: converted to equality");
ConstraintProto* new_ct = context_->working_model->add_constraints();
*new_ct = *ct; // copy name and potential reification.
auto* arg = new_ct->mutable_linear();
arg->add_vars(target_ref);
arg->add_coeffs(1);
arg->add_vars(ct->int_max().vars(0));
arg->add_coeffs(-1);
arg->add_domain(0);
arg->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
// TODO(user): Just port all the presolve above to the lin max presolve, so
// we can just convert it and not do anything else.
if (ct->constraint_case() == ConstraintProto::kIntMax) {
const bool convert_result = ConvertIntMax(ct);
return modified || convert_result;
}
return modified;
}
// Convert to lin_max and presolve lin_max.
bool CpModelPresolver::PresolveLinMin(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
const auto copy = ct->lin_min();
SetToNegatedLinearExpression(copy.target(),
ct->mutable_lin_max()->mutable_target());
for (const LinearExpressionProto& expr : copy.exprs()) {
LinearExpressionProto* const new_expr = ct->mutable_lin_max()->add_exprs();
SetToNegatedLinearExpression(expr, new_expr);
}
return PresolveLinMax(ct);
}
// We convert it to a "linear" max which allows to replace affine relation and
// remove the need to keep them in the model.
//
// TODO(user): Move to expand. We also need to convert all the int_max presolve
// (like the absolute value) that we don't have yet in the lin_max format.
bool CpModelPresolver::ConvertIntMax(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
const auto copy = ct->int_max();
ct->mutable_lin_max()->mutable_target()->add_vars(copy.target());
ct->mutable_lin_max()->mutable_target()->add_coeffs(1);
for (const int ref : copy.vars()) {
LinearExpressionProto* expr = ct->mutable_lin_max()->add_exprs();
expr->add_vars(ref);
expr->add_coeffs(1);
}
context_->UpdateRuleStats("int_max: converted to lin_max");
return PresolveLinMax(ct);
}
// TODO(user): Add all the missing presolve from PresolveIntMax().
bool CpModelPresolver::PresolveLinMax(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
// Canonicalize all involved expression.
//
// TODO(user): If we start to have many constraints like this, we should
// use reflexion (see cp_model_util) to do that generically.
bool changed = CanonicalizeLinearExpression(
*ct, ct->mutable_lin_max()->mutable_target());
for (LinearExpressionProto& exp : *(ct->mutable_lin_max()->mutable_exprs())) {
changed |= CanonicalizeLinearExpression(*ct, &exp);
}
// Compute the infered min/max of the target.
// Update target domain (if it is not a complex expression).
const LinearExpressionProto& target = ct->lin_max().target();
{
int64_t infered_min = context_->MinOf(target);
int64_t infered_max = std::numeric_limits<int64_t>::min();
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
infered_min = std::max(infered_min, context_->MinOf(expr));
infered_max = std::max(infered_max, context_->MaxOf(expr));
}
if (target.vars().empty()) {
if (!Domain(infered_min, infered_max).Contains(target.offset())) {
context_->UpdateRuleStats("lin_max: infeasible");
return MarkConstraintAsFalse(ct);
}
}
if (!HasEnforcementLiteral(*ct) && target.vars().size() <= 1) { // Affine
Domain rhs_domain;
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
rhs_domain = rhs_domain.UnionWith(
context_->DomainSuperSetOf(expr).IntersectionWith(
{infered_min, infered_max}));
}
bool reduced = false;
if (!context_->IntersectDomainWith(target, rhs_domain, &reduced)) {
return true;
}
if (reduced) {
context_->UpdateRuleStats("lin_max: target domain reduced");
}
}
}
// Filter the expressions which are smaller than target_min.
const int64_t target_min = context_->MinOf(target);
const int64_t target_max = context_->MaxOf(target);
{
int new_size = 0;
for (int i = 0; i < ct->lin_max().exprs_size(); ++i) {
const LinearExpressionProto& expr = ct->lin_max().exprs(i);
if (context_->MaxOf(expr) < target_min) continue;
*ct->mutable_lin_max()->mutable_exprs(new_size) = expr;
new_size++;
}
if (new_size < ct->lin_max().exprs_size()) {
context_->UpdateRuleStats("lin_max: removed exprs");
ct->mutable_lin_max()->mutable_exprs()->DeleteSubrange(
new_size, ct->lin_max().exprs_size() - new_size);
changed = true;
}
}
if (ct->lin_max().exprs().empty()) {
context_->UpdateRuleStats("lin_max: no exprs");
return MarkConstraintAsFalse(ct);
}
if (ct->lin_max().exprs().size() == 1) {
// Convert to an equality. Note that we create a new constraint otherwise it
// might not be processed again.
context_->UpdateRuleStats("lin_max: converted to equality");
ConstraintProto* new_ct = context_->working_model->add_constraints();
*new_ct = *ct; // copy name and potential reification.
auto* arg = new_ct->mutable_linear();
const LinearExpressionProto& a = ct->lin_max().target();
const LinearExpressionProto& b = ct->lin_max().exprs(0);
for (int i = 0; i < a.vars().size(); ++i) {
arg->add_vars(a.vars(i));
arg->add_coeffs(a.coeffs(i));
}
for (int i = 0; i < b.vars().size(); ++i) {
arg->add_vars(b.vars(i));
arg->add_coeffs(-b.coeffs(i));
}
arg->add_domain(b.offset() - a.offset());
arg->add_domain(b.offset() - a.offset());
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
// Cut everything above the max if possible.
// If one of the linear expression has many term and is above the max, we
// abort early since none of the other rule can be applied.
{
bool abort = false;
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
const int64_t value_min = context_->MinOf(expr);
bool modified = false;
if (!context_->IntersectDomainWith(expr, Domain(value_min, target_max),
&modified)) {
return true;
}
if (modified) {
context_->UpdateRuleStats("lin_max: reduced expression domain.");
}
const int64_t value_max = context_->MaxOf(expr);
if (value_max > target_max) {
context_->UpdateRuleStats("TODO lin_max: linear expression above max.");
abort = true;
}
}
if (abort) return changed;
}
// Deal with fixed target case.
if (target_min == target_max) {
bool all_booleans = true;
std::vector<int> literals;
const int64_t fixed_target = target_min;
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
const int64_t value_min = context_->MinOf(expr);
const int64_t value_max = context_->MaxOf(expr);
CHECK_LE(value_max, fixed_target) << "Presolved above";
if (value_max < fixed_target) continue;
if (value_min == value_max && value_max == fixed_target) {
context_->UpdateRuleStats("lin_max: always satisfied");
return RemoveConstraint(ct);
}
if (context_->ExpressionIsAffineBoolean(expr)) {
CHECK_EQ(value_max, fixed_target);
literals.push_back(context_->LiteralForExpressionMax(expr));
} else {
all_booleans = false;
}
}
if (all_booleans) {
if (literals.empty()) {
return MarkConstraintAsFalse(ct);
}
// At least one true;
context_->UpdateRuleStats("lin_max: fixed target and all booleans");
for (const int lit : literals) {
ct->mutable_bool_or()->add_literals(lit);
}
return true;
}
return changed;
}
// If everything is Boolean and affine, do not use a lin max!
if (context_->ExpressionIsAffineBoolean(target)) {
const int target_ref = context_->LiteralForExpressionMax(target);
bool abort = false;
bool min_is_reachable = false;
std::vector<int> min_literals;
std::vector<int> literals_above_min;
std::vector<int> max_literals;
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
const int64_t value_min = context_->MinOf(expr);
const int64_t value_max = context_->MaxOf(expr);
// This shouldn't happen, but it document the fact.
if (value_min > target_min) {
context_->UpdateRuleStats("lin_max: fix target");
if (!context_->SetLiteralToTrue(target_ref)) return true;
abort = true;
break;
}
// expr is fixed.
if (value_min == value_max) {
if (value_min == target_min) min_is_reachable = true;
continue;
}
if (!context_->ExpressionIsAffineBoolean(expr)) {
abort = true;
break;
}
const int ref = context_->LiteralForExpressionMax(expr);
CHECK_LE(value_min, target_min);
if (value_min == target_min) {
min_literals.push_back(NegatedRef(ref));
}
CHECK_LE(value_max, target_max);
if (value_max == target_max) {
max_literals.push_back(ref);
literals_above_min.push_back(ref);
} else if (value_max > target_min) {
literals_above_min.push_back(ref);
} else if (value_max == target_min) {
min_literals.push_back(ref);
}
}
if (!abort) {
context_->UpdateRuleStats("lin_max: all Booleans.");
// target_ref => at_least_one(max_literals);
ConstraintProto* clause = context_->working_model->add_constraints();
clause->add_enforcement_literal(target_ref);
clause->mutable_bool_or();
for (const int lit : max_literals) {
clause->mutable_bool_or()->add_literals(lit);
}
// not(target_ref) => not(lit) for lit in literals_above_min
for (const int lit : literals_above_min) {
context_->AddImplication(lit, target_ref);
}
if (!min_is_reachable) {
// not(target_ref) => at_least_one(min_literals).
ConstraintProto* clause = context_->working_model->add_constraints();
clause->add_enforcement_literal(NegatedRef(target_ref));
clause->mutable_bool_or();
for (const int lit : min_literals) {
clause->mutable_bool_or()->add_literals(lit);
}
}
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
}