forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_presolve.cc
5024 lines (4548 loc) · 186 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-2018 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 <cstdlib>
#include <deque>
#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/random/random.h"
#include "absl/strings/str_join.h"
#include "ortools/base/hash.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/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_objective.h"
#include "ortools/sat/cp_model_utils.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"
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 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 = kint32min;
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 == 1) {
context_->UpdateRuleStats("TODO bool_xor: one active literal");
} else if (new_size == 2) {
context_->UpdateRuleStats("TODO bool_xor: two active literals");
}
if (num_true_literals % 2 == 1) {
CHECK_NE(true_literal, kint32min);
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;
}
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");
}
return changed;
}
bool CpModelPresolver::PresolveAtMostOne(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
CHECK(!HasEnforcementLiteral(*ct));
// Fix to false any duplicate literals.
std::sort(ct->mutable_at_most_one()->mutable_literals()->begin(),
ct->mutable_at_most_one()->mutable_literals()->end());
int previous = kint32max;
for (const int literal : ct->at_most_one().literals()) {
if (literal == previous) {
if (!context_->SetLiteralToFalse(literal)) return true;
context_->UpdateRuleStats("at_most_one: duplicate literals");
}
previous = literal;
}
bool changed = false;
context_->tmp_literals.clear();
for (const int literal : ct->at_most_one().literals()) {
if (context_->LiteralIsTrue(literal)) {
context_->UpdateRuleStats("at_most_one: satisfied");
for (const int other : ct->at_most_one().literals()) {
if (other != literal) {
if (!context_->SetLiteralToFalse(other)) return true;
}
}
return RemoveConstraint(ct);
}
if (context_->LiteralIsFalse(literal)) {
changed = true;
continue;
}
context_->tmp_literals.push_back(literal);
}
if (context_->tmp_literals.empty()) {
context_->UpdateRuleStats("at_most_one: all false");
return RemoveConstraint(ct);
}
if (changed) {
ct->mutable_at_most_one()->mutable_literals()->Clear();
for (const int lit : context_->tmp_literals) {
ct->mutable_at_most_one()->add_literals(lit);
}
context_->UpdateRuleStats("at_most_one: removed literals");
}
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 infered_min = kint64min;
int64 infered_max = kint64min;
bool contains_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{0});
}
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(kint64max);
}
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.
if (context_->VariableIsUniqueAndRemovable(target_ref)) {
const Domain& target_domain = context_->DomainOf(target_ref);
if (infered_domain.IntersectionWith(Domain(kint64min, 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(kint64min, 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(kint64min);
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 target_max = context_->MaxOf(target_ref);
for (const int ref : ct->int_max().vars()) {
if (!HasEnforcementLiteral(*ct)) {
if (!context_->IntersectDomainWith(ref, Domain(kint64min, 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);
}
return modified;
}
bool CpModelPresolver::PresolveLinMin(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
// Convert to lin_max and presolve lin_max.
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);
}
bool CpModelPresolver::PresolveLinMax(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (ct->lin_max().exprs().empty()) {
context_->UpdateRuleStats("lin_max: no exprs");
return MarkConstraintAsFalse(ct);
}
// TODO(user): Remove duplicate expressions. This might be expensive.
// Pass 1, Compute the infered min of the target.
int64 infered_min = context_->MinOf(ct->lin_max().target());
for (const LinearExpressionProto& expr : ct->lin_max().exprs()) {
// TODO(user): Check if the expressions contain target.
// TODO(user): Check if the negated expression is already present and
// reduce inferred domain if so.
infered_min = std::max(infered_min, context_->MinOf(expr));
}
// Pass 2, Filter the expressions which are smaller than inferred min.
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) >= infered_min) {
*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);
return true;
}
return false;
}
bool CpModelPresolver::PresolveIntAbs(ConstraintProto* ct) {
CHECK_EQ(ct->enforcement_literal_size(), 0);
if (context_->ModelIsUnsat()) return false;
const int target_ref = ct->int_max().target();
const int var = PositiveRef(ct->int_max().vars(0));
// Propagate from the variable domain to the target variable.
const Domain var_domain = context_->DomainOf(var);
const Domain new_target_domain = var_domain.UnionWith(var_domain.Negation())
.IntersectionWith({0, kint64max});
if (!context_->DomainOf(target_ref).IsIncludedIn(new_target_domain)) {
if (!context_->IntersectDomainWith(target_ref, new_target_domain)) {
return true;
}
context_->UpdateRuleStats("int_abs: propagate domain x to abs(x)");
}
// Propagate from target domain to variable.
const Domain target_domain = context_->DomainOf(target_ref);
const Domain new_var_domain =
target_domain.UnionWith(target_domain.Negation());
if (!context_->DomainOf(var).IsIncludedIn(new_var_domain)) {
if (!context_->IntersectDomainWith(var, new_var_domain)) {
return true;
}
context_->UpdateRuleStats("int_abs: propagate domain abs(x) to x");
}
if (context_->MinOf(var) >= 0 && !context_->IsFixed(var)) {
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_vars(target_ref);
arg->add_coeffs(1);
arg->add_vars(var);
arg->add_coeffs(-1);
arg->add_domain(0);
arg->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
if (context_->MaxOf(var) <= 0 && !context_->IsFixed(var)) {
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_vars(target_ref);
arg->add_coeffs(1);
arg->add_vars(var);
arg->add_coeffs(1);
arg->add_domain(0);
arg->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
// Remove the abs constraint if the target is removable or fixed, as domains
// have been propagated.
if (context_->VariableIsUniqueAndRemovable(target_ref) ||
context_->IsFixed(target_ref)) {
if (!context_->IsFixed(target_ref)) {
context_->MarkVariableAsRemoved(target_ref);
*context_->mapping_model->add_constraints() = *ct;
}
context_->UpdateRuleStats("int_abs: remove constraint");
return RemoveConstraint(ct);
}
if (context_->StoreAbsRelation(target_ref, var)) {
context_->UpdateRuleStats("int_abs: store abs(x) == y");
}
return false;
}
bool CpModelPresolver::PresolveIntMin(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
const auto copy = ct->int_min();
ct->mutable_int_max()->set_target(NegatedRef(copy.target()));
for (const int ref : copy.vars()) {
ct->mutable_int_max()->add_vars(NegatedRef(ref));
}
return PresolveIntMax(ct);
}
bool CpModelPresolver::PresolveIntProd(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
if (HasEnforcementLiteral(*ct)) return false;
bool changed = false;
// Replace any affine relation without offset.
// TODO(user): Also remove constant rhs variables.
int64 constant = 1;
for (int i = 0; i < ct->int_prod().vars().size(); ++i) {
const int ref = ct->int_prod().vars(i);
const AffineRelation::Relation& r = context_->GetAffineRelation(ref);
if (r.representative != ref && r.offset == 0) {
changed = true;
ct->mutable_int_prod()->set_vars(i, r.representative);
constant *= r.coeff;
}
}
// TODO(user): Probably better to add a fixed variable to the product
// instead in this case. But we do need to support product with more than
// two variables properly for that.
//
// TODO(user): We might do that too early since the other presolve step below
// might simplify the constraint in such a way that there is no need to create
// a new variable!
if (constant != 1) {
context_->UpdateRuleStats("int_prod: extracted product by constant.");
const int old_target = ct->int_prod().target();
const int new_target = context_->working_model->variables_size();
IntegerVariableProto* var_proto = context_->working_model->add_variables();
FillDomainInProto(
context_->DomainOf(old_target).InverseMultiplicationBy(constant),
var_proto);
context_->InitializeNewDomains();
if (context_->ModelIsUnsat()) return false;
ct->mutable_int_prod()->set_target(new_target);
if (context_->IsFixed(new_target)) {
// We need to fix old_target too.
if (!context_->IntersectDomainWith(
old_target,
context_->DomainOf(new_target).MultiplicationBy(constant))) {
return false;
}
} else {
if (!context_->StoreAffineRelation(old_target, new_target, constant, 0)) {
// We cannot store the affine relation because the old target seems
// to already be in affine relation with another variable. This is rare
// and we need to add a new constraint in that case.
ConstraintProto* new_ct = context_->working_model->add_constraints();
LinearConstraintProto* lin = new_ct->mutable_linear();
lin->add_vars(old_target);
lin->add_coeffs(1);
lin->add_vars(new_target);
lin->add_coeffs(-constant);
lin->add_domain(0);
lin->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
}
}
}
// Restrict the target domain if possible.
Domain implied(1);
for (const int ref : ct->int_prod().vars()) {
implied = implied.ContinuousMultiplicationBy(context_->DomainOf(ref));
}
bool modified = false;
if (!context_->IntersectDomainWith(ct->int_prod().target(), implied,
&modified)) {
return false;
}
if (modified) {
context_->UpdateRuleStats("int_prod: reduced target domain.");
}
if (ct->int_prod().vars_size() == 2) {
int a = ct->int_prod().vars(0);
int b = ct->int_prod().vars(1);
const int product = ct->int_prod().target();
if (context_->IsFixed(b)) std::swap(a, b);
if (context_->IsFixed(a)) {
if (b != product) {
ConstraintProto* const lin = context_->working_model->add_constraints();
lin->mutable_linear()->add_vars(b);
lin->mutable_linear()->add_coeffs(context_->MinOf(a));
lin->mutable_linear()->add_vars(product);
lin->mutable_linear()->add_coeffs(-1);
lin->mutable_linear()->add_domain(0);
lin->mutable_linear()->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
context_->UpdateRuleStats("int_prod: linearize product by constant.");
return RemoveConstraint(ct);
} else if (context_->MinOf(a) != 1) {
bool domain_modified = false;
if (!context_->IntersectDomainWith(product, Domain(0, 0),
&domain_modified)) {
return false;
}
context_->UpdateRuleStats("int_prod: fix variable to zero.");
return RemoveConstraint(ct);
} else {
context_->UpdateRuleStats("int_prod: remove identity.");
return RemoveConstraint(ct);
}
} else if (a == b && a == product) { // x = x * x, only true for {0, 1}.
if (!context_->IntersectDomainWith(product, Domain(0, 1))) {
return false;
}
context_->UpdateRuleStats("int_prod: fix variable to zero or one.");
return RemoveConstraint(ct);
}
}
// For now, we only presolve the case where all variables are Booleans.
const int target_ref = ct->int_prod().target();
if (!RefIsPositive(target_ref)) return changed;
for (const int var : ct->int_prod().vars()) {
if (!RefIsPositive(var)) return changed;
if (context_->MinOf(var) < 0) return changed;
if (context_->MaxOf(var) > 1) return changed;
}
// This is a bool constraint!
if (!context_->IntersectDomainWith(target_ref, Domain(0, 1))) {
return false;
}
context_->UpdateRuleStats("int_prod: all Boolean.");
{
ConstraintProto* new_ct = context_->working_model->add_constraints();
new_ct->add_enforcement_literal(target_ref);
auto* arg = new_ct->mutable_bool_and();
for (const int var : ct->int_prod().vars()) {
arg->add_literals(var);
}
}
{
ConstraintProto* new_ct = context_->working_model->add_constraints();
auto* arg = new_ct->mutable_bool_or();
arg->add_literals(target_ref);
for (const int var : ct->int_prod().vars()) {
arg->add_literals(NegatedRef(var));
}
}
context_->UpdateNewConstraintsVariableUsage();
return RemoveConstraint(ct);
}
bool CpModelPresolver::PresolveIntDiv(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return false;
// For now, we only presolve the case where the divisor is constant.
const int target = ct->int_div().target();
const int ref_x = ct->int_div().vars(0);
const int ref_div = ct->int_div().vars(1);
if (!RefIsPositive(target) || !RefIsPositive(ref_x) ||
!RefIsPositive(ref_div) || context_->DomainIsEmpty(ref_div) ||
!context_->IsFixed(ref_div)) {
return false;
}
const int64 divisor = context_->MinOf(ref_div);
if (divisor == 1) {
LinearConstraintProto* const lin =
context_->working_model->add_constraints()->mutable_linear();
lin->add_vars(ref_x);
lin->add_coeffs(1);
lin->add_vars(target);
lin->add_coeffs(-1);
lin->add_domain(0);
lin->add_domain(0);
context_->UpdateNewConstraintsVariableUsage();
context_->UpdateRuleStats("int_div: rewrite to equality");
return RemoveConstraint(ct);
}
bool domain_modified = false;
if (context_->IntersectDomainWith(
target, context_->DomainOf(ref_x).DivisionBy(divisor),
&domain_modified)) {
if (domain_modified) {
context_->UpdateRuleStats(
"int_div: updated domain of target in target = X / cte");
}
} else {
// Model is unsat.
return false;
}
// Linearize if everything is positive.
// TODO(user,user): Deal with other cases where there is no change of
// sign.We can also deal with target = cte, div variable.
if (context_->MinOf(target) >= 0 && context_->MinOf(ref_x) >= 0 &&
divisor > 1) {
LinearConstraintProto* const lin =
context_->working_model->add_constraints()->mutable_linear();
lin->add_vars(ref_x);
lin->add_coeffs(1);
lin->add_vars(target);
lin->add_coeffs(-divisor);
lin->add_domain(0);
lin->add_domain(divisor - 1);
context_->UpdateNewConstraintsVariableUsage();
context_->UpdateRuleStats(
"int_div: linearize positive division with a constant divisor");
return RemoveConstraint(ct);
}
// TODO(user): reduce the domain of X by introducing an
// InverseDivisionOfSortedDisjointIntervals().
return false;
}
bool CpModelPresolver::ExploitEquivalenceRelations(int c, ConstraintProto* ct) {
bool changed = false;
// Optim: Special case for the linear constraint. We just remap the
// enforcement literals, the normal variables will be replaced by their
// representative in CanonicalizeLinear().
if (ct->constraint_case() == ConstraintProto::ConstraintCase::kLinear) {
for (int& ref : *ct->mutable_enforcement_literal()) {
const int rep = this->context_->GetLiteralRepresentative(ref);
if (rep != ref) {
changed = true;
ref = rep;
}
}
return changed;
}
// Optim: This extra loop is a lot faster than reparsing the variable from the
// proto when there is nothing to do, which is quite often.
bool work_to_do = false;
for (const int var : context_->ConstraintToVars(c)) {
const AffineRelation::Relation r = context_->GetAffineRelation(var);
if (r.representative != var) {
work_to_do = true;
break;
}
}
if (!work_to_do) return false;
// Remap equal and negated variables to their representative.
ApplyToAllVariableIndices(
[&changed, this](int* ref) {
const int rep = context_->GetVariableRepresentative(*ref);
if (rep != *ref) {
changed = true;
*ref = rep;
}
},
ct);
// Remap literal and negated literal to their representative.
ApplyToAllLiteralIndices(
[&changed, this](int* ref) {
const int rep = this->context_->GetLiteralRepresentative(*ref);
if (rep != *ref) {
changed = true;
*ref = rep;
}
},
ct);
return changed;
}
void CpModelPresolver::DivideLinearByGcd(ConstraintProto* ct) {
if (context_->ModelIsUnsat()) return;
// Compute the GCD of all coefficients.
int64 gcd = 0;
const int num_vars = ct->linear().vars().size();
for (int i = 0; i < num_vars; ++i) {
const int64 magnitude = std::abs(ct->linear().coeffs(i));
gcd = MathUtil::GCD64(gcd, magnitude);
if (gcd == 1) break;
}
if (gcd > 1) {
context_->UpdateRuleStats("linear: divide by GCD");
for (int i = 0; i < num_vars; ++i) {
ct->mutable_linear()->set_coeffs(i, ct->linear().coeffs(i) / gcd);
}
const Domain rhs = ReadDomainFromProto(ct->linear());
FillDomainInProto(rhs.InverseMultiplicationBy(gcd), ct->mutable_linear());
if (ct->linear().domain_size() == 0) {
return (void)MarkConstraintAsFalse(ct);
}
}
}
bool CpModelPresolver::CanonicalizeLinear(ConstraintProto* ct) {
if (ct->constraint_case() != ConstraintProto::ConstraintCase::kLinear ||
context_->ModelIsUnsat()) {
return false;
}
// First regroup the terms on the same variables and sum the fixed ones.
//
// TODO(user): move terms in context to reuse its memory? Add a quick pass
// to skip most of the work below if the constraint is already in canonical
// form (strictly increasing var, no-fixed var, gcd = 1).
tmp_terms_.clear();
int64 sum_of_fixed_terms = 0;
bool remapped = false;
const int num_vars = ct->linear().vars().size();
DCHECK_EQ(num_vars, ct->linear().coeffs().size());
for (int i = 0; i < num_vars; ++i) {
const int ref = ct->linear().vars(i);
const int var = PositiveRef(ref);
const int64 coeff =
RefIsPositive(ref) ? ct->linear().coeffs(i) : -ct->linear().coeffs(i);
if (coeff == 0) continue;
if (context_->IsFixed(var)) {
sum_of_fixed_terms += coeff * context_->MinOf(var);
continue;
}
// TODO(user): Avoid the quadratic loop for the corner case of many
// enforcement literal (this should be pretty rare though).
bool removed = false;
for (const int enf : ct->enforcement_literal()) {
if (var == PositiveRef(enf)) {
if (RefIsPositive(enf)) {
// If the constraint is enforced, we can assume the variable is at 1.
sum_of_fixed_terms += coeff;
} else {
// We can assume the variable is at zero.
}
removed = true;
break;
}