forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_presolve.cc
7940 lines (7178 loc) · 298 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/base/attributes.h"
#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;
}
// Remove all empty constraints. Note that we need to remap the interval
// references.
//
// Now that they have served their purpose, we also remove dummy constraints,
// otherwise that causes issue because our model are invalid in tests.
void CpModelPresolver::RemoveEmptyConstraints() {
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::kDummyConstraint) 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 =
context_->ObjectiveMap().at(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 (a == b) {
if (num_true_literals % 2 == 0) {
return context_->NotifyThatModelIsUnsat("bool_xor: always false");
} else {
context_->UpdateRuleStats("bool_xor: always true");
return RemoveConstraint(ct);
}
}
if (a == NegatedRef(b)) {
if (num_true_literals % 2 == 1) {
return context_->NotifyThatModelIsUnsat("bool_xor: always false");
} else {
context_->UpdateRuleStats("bool_xor: always true");
return RemoveConstraint(ct);
}
}
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 = context_->ObjectiveMap().at(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 false;
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 false;
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 false;
}
if (num_negative > 1 && !context_->SetLiteralToTrue(literal)) {
return false;
}
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 false;
}
}
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::CanonicalizeLinMax(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);
}
return changed;
}
bool CpModelPresolver::PresolveLinMax(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
// 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);
bool changed = false;
{
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);
}
}
return changed;
}
// This presolve expect that the constraint only contains affine expressions.
bool CpModelPresolver::PresolveIntAbs(ConstraintProto* ct) {
CHECK_EQ(ct->enforcement_literal_size(), 0);
if (context_->ModelIsUnsat()) return false;
const LinearExpressionProto& target_expr = ct->lin_max().target();
const LinearExpressionProto& expr = ct->lin_max().exprs(0);
DCHECK_EQ(expr.vars_size(), 1);
// Propagate domain from the expression to the target.
{
const Domain expr_domain = context_->DomainSuperSetOf(expr);
const Domain new_target_domain =
expr_domain.UnionWith(expr_domain.Negation())
.IntersectionWith({0, std::numeric_limits<int64_t>::max()});
bool target_domain_modified = false;
if (!context_->IntersectDomainWith(target_expr, new_target_domain,
&target_domain_modified)) {
return false;
}
if (expr_domain.IsFixed()) {
context_->UpdateRuleStats("int_abs: fixed expression");
return RemoveConstraint(ct);
}
if (target_domain_modified) {
context_->UpdateRuleStats("int_abs: propagate domain from x to abs(x)");
}
}
// Propagate from target domain to variable.
{
const Domain target_domain =
context_->DomainSuperSetOf(target_expr)
.IntersectionWith(Domain(0, std::numeric_limits<int64_t>::max()));
const Domain new_expr_domain =
target_domain.UnionWith(target_domain.Negation());
bool expr_domain_modified = false;
if (!context_->IntersectDomainWith(expr, new_expr_domain,
&expr_domain_modified)) {
return true;
}
// This is the only reason why we don't support fully generic linear
// expression.
if (context_->IsFixed(target_expr)) {
context_->UpdateRuleStats("int_abs: fixed target");
return RemoveConstraint(ct);
}
if (expr_domain_modified) {
context_->UpdateRuleStats("int_abs: propagate domain from abs(x) to x");
}
}
// Convert to equality if the sign of expr is fixed.
if (context_->MinOf(expr) >= 0) {
context_->UpdateRuleStats("int_abs: converted to equality");
ConstraintProto* new_ct = context_->working_model->add_constraints();
new_ct->set_name(ct->name());
auto* arg = new_ct->mutable_linear();
arg->add_domain(0);
arg->add_domain(0);
AddLinearExpressionToLinearConstraint(target_expr, 1, arg);
AddLinearExpressionToLinearConstraint(expr, -1, arg);
if (!CanonicalizeLinear(new_ct)) return false;
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
if (context_->MaxOf(expr) <= 0) {
context_->UpdateRuleStats("int_abs: converted to equality");
ConstraintProto* new_ct = context_->working_model->add_constraints();
new_ct->set_name(ct->name());
auto* arg = new_ct->mutable_linear();
arg->add_domain(0);
arg->add_domain(0);
AddLinearExpressionToLinearConstraint(target_expr, 1, arg);
AddLinearExpressionToLinearConstraint(expr, 1, arg);
if (!CanonicalizeLinear(new_ct)) return false;
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
// Remove the abs constraint if the target is removable and if domains have
// been propagated without loss.
// For now, we known that there is no loss if the target is a single ref.
// Since all the expression are affine, in this case we are fine.
if (ExpressionContainsSingleRef(target_expr) &&
context_->VariableIsUniqueAndRemovable(target_expr.vars(0))) {
context_->MarkVariableAsRemoved(target_expr.vars(0));
*context_->mapping_model->add_constraints() = *ct;
context_->UpdateRuleStats("int_abs: unused target");
return RemoveConstraint(ct);
}
// Store the x == abs(y) relation if expr and target_expr can be cast into a
// ref.
// TODO(user): Support general affine expression in for expr in the Store
// method call.
{
if (ExpressionContainsSingleRef(target_expr) &&
ExpressionContainsSingleRef(expr)) {
const int target_ref = GetSingleRefFromExpression(target_expr);
const int expr_ref = GetSingleRefFromExpression(expr);
if (context_->StoreAbsRelation(target_ref, expr_ref)) {
context_->UpdateRuleStats("int_abs: store abs(x) == y");
}
}
}
return false;
}
bool CpModelPresolver::PresolveIntProd(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (HasEnforcementLiteral(*ct)) return false;
LinearArgumentProto* proto = ct->mutable_int_prod();
bool changed = CanonicalizeLinearExpression(*ct, proto->mutable_target());
for (LinearExpressionProto& exp : *(proto->mutable_exprs())) {
changed |= CanonicalizeLinearExpression(*ct, &exp);
}
// Remove constant expressions.
int64_t constant_factor = 1;
int new_size = 0;
for (int i = 0; i < ct->int_prod().exprs().size(); ++i) {
LinearExpressionProto expr = ct->int_prod().exprs(i);
if (context_->IsFixed(expr)) {
context_->UpdateRuleStats("int_prod: removed constant expressions.");
changed = true;
constant_factor = CapProd(constant_factor, context_->FixedValue(expr));
continue;
} else {
const int64_t coeff = expr.coeffs(0);
const int64_t offset = expr.offset();
const int64_t gcd =
MathUtil::GCD64(static_cast<uint64_t>(std::abs(coeff)),
static_cast<uint64_t>(std::abs(offset)));
if (gcd != 1) {
constant_factor = CapProd(constant_factor, gcd);
expr.set_coeffs(0, coeff / gcd);
expr.set_offset(offset / gcd);
}
}
*proto->mutable_exprs(new_size++) = expr;
}
proto->mutable_exprs()->erase(proto->mutable_exprs()->begin() + new_size,
proto->mutable_exprs()->end());
if (ct->int_prod().exprs().empty()) {
if (!context_->IntersectDomainWith(ct->int_prod().target(),
Domain(constant_factor))) {
return false;
}
context_->UpdateRuleStats("int_prod: constant product");
return RemoveConstraint(ct);
}
if (constant_factor == 0) {
context_->UpdateRuleStats("int_prod: multiplication by zero");
if (!context_->IntersectDomainWith(ct->int_prod().target(), Domain(0))) {
return false;
}
return RemoveConstraint(ct);
}
// In this case, the only possible value that fit in the domains is zero.
// We will check for UNSAT if zero is not achievable by the rhs below.
if (constant_factor == std::numeric_limits<int64_t>::min() ||
constant_factor == std::numeric_limits<int64_t>::max()) {
context_->UpdateRuleStats("int_prod: overflow if non zero");
if (!context_->IntersectDomainWith(ct->int_prod().target(), Domain(0))) {
return false;
}
constant_factor = 1;
}
// Replace by linear!
if (ct->int_prod().exprs().size() == 1) {
LinearConstraintProto* const lin =
context_->working_model->add_constraints()->mutable_linear();
lin->add_domain(0);
lin->add_domain(0);