This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
forked from rte-france/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcp_model_presolve.cc
4584 lines (4154 loc) · 167 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 <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/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_loader.h"
#include "ortools/sat/cp_model_objective.h"
#include "ortools/sat/cp_model_utils.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 {
int PresolveContext::NewIntVar(const Domain& domain) {
IntegerVariableProto* const var = working_model->add_variables();
FillDomainInProto(domain, var);
InitializeNewDomains();
return working_model->variables_size() - 1;
}
int PresolveContext::NewBoolVar() { return NewIntVar(Domain(0, 1)); }
int PresolveContext::GetOrCreateConstantVar(int64 cst) {
if (!gtl::ContainsKey(constant_to_ref, cst)) {
constant_to_ref[cst] = working_model->variables_size();
IntegerVariableProto* const var_proto = working_model->add_variables();
var_proto->add_domain(cst);
var_proto->add_domain(cst);
InitializeNewDomains();
}
return constant_to_ref[cst];
}
// a => b.
void PresolveContext::AddImplication(int a, int b) {
ConstraintProto* const ct = working_model->add_constraints();
ct->add_enforcement_literal(a);
ct->mutable_bool_and()->add_literals(b);
}
// b => x in [lb, ub].
void PresolveContext::AddImplyInDomain(int b, int x, const Domain& domain) {
ConstraintProto* const imply = working_model->add_constraints();
imply->add_enforcement_literal(b);
imply->mutable_linear()->add_vars(x);
imply->mutable_linear()->add_coeffs(1);
FillDomainInProto(domain, imply->mutable_linear());
}
bool PresolveContext::DomainIsEmpty(int ref) const {
return domains[PositiveRef(ref)].IsEmpty();
}
bool PresolveContext::IsFixed(int ref) const {
CHECK(!DomainIsEmpty(ref));
return domains[PositiveRef(ref)].Min() == domains[PositiveRef(ref)].Max();
}
bool PresolveContext::LiteralIsTrue(int lit) const {
if (!IsFixed(lit)) return false;
if (RefIsPositive(lit)) {
return domains[lit].Min() == 1ll;
} else {
return domains[PositiveRef(lit)].Max() == 0ll;
}
}
bool PresolveContext::LiteralIsFalse(int lit) const {
if (!IsFixed(lit)) return false;
if (RefIsPositive(lit)) {
return domains[lit].Max() == 0ll;
} else {
return domains[PositiveRef(lit)].Min() == 1ll;
}
}
int64 PresolveContext::MinOf(int ref) const {
CHECK(!DomainIsEmpty(ref));
return RefIsPositive(ref) ? domains[PositiveRef(ref)].Min()
: -domains[PositiveRef(ref)].Max();
}
int64 PresolveContext::MaxOf(int ref) const {
CHECK(!DomainIsEmpty(ref));
return RefIsPositive(ref) ? domains[PositiveRef(ref)].Max()
: -domains[PositiveRef(ref)].Min();
}
// TODO(user): In some case, we could still remove var when it has some variable
// in affine relation with it, but we need to be careful that none are used.
bool PresolveContext::VariableIsUniqueAndRemovable(int ref) const {
return var_to_constraints[PositiveRef(ref)].size() == 1 &&
affine_relations.ClassSize(PositiveRef(ref)) == 1 &&
!keep_all_feasible_solutions;
}
Domain PresolveContext::DomainOf(int ref) const {
Domain result;
if (RefIsPositive(ref)) {
result = domains[ref];
} else {
result = domains[PositiveRef(ref)].Negation();
}
return result;
}
bool PresolveContext::DomainContains(int ref, int64 value) const {
if (!RefIsPositive(ref)) {
return domains[PositiveRef(ref)].Contains(-value);
}
return domains[ref].Contains(value);
}
ABSL_MUST_USE_RESULT bool PresolveContext::IntersectDomainWith(
int ref, const Domain& domain, bool* domain_modified) {
DCHECK(!DomainIsEmpty(ref));
const int var = PositiveRef(ref);
if (RefIsPositive(ref)) {
if (domains[var].IsIncludedIn(domain)) {
return true;
}
domains[var] = domains[var].IntersectionWith(domain);
} else {
const Domain temp = domain.Negation();
if (domains[var].IsIncludedIn(temp)) {
return true;
}
domains[var] = domains[var].IntersectionWith(temp);
}
if (domain_modified != nullptr) {
*domain_modified = true;
}
modified_domains.Set(var);
if (domains[var].IsEmpty()) {
is_unsat = true;
return false;
}
return true;
}
ABSL_MUST_USE_RESULT bool PresolveContext::SetLiteralToFalse(int lit) {
const int var = PositiveRef(lit);
const int64 value = RefIsPositive(lit) ? 0ll : 1ll;
return IntersectDomainWith(var, Domain(value));
}
ABSL_MUST_USE_RESULT bool PresolveContext::SetLiteralToTrue(int lit) {
return SetLiteralToFalse(NegatedRef(lit));
}
void PresolveContext::UpdateRuleStats(const std::string& name) {
stats_by_rule_name[name]++;
}
void PresolveContext::AddVariableUsage(int c) {
const ConstraintProto& ct = working_model->constraints(c);
constraint_to_vars[c] = UsedVariables(working_model->constraints(c));
constraint_to_intervals[c] = UsedIntervals(ct);
for (const int v : constraint_to_vars[c]) var_to_constraints[v].insert(c);
for (const int i : constraint_to_intervals[c]) interval_usage[i]++;
}
void PresolveContext::UpdateConstraintVariableUsage(int c) {
CHECK_EQ(constraint_to_vars.size(), working_model->constraints_size());
// Remove old usage.
for (const int v : constraint_to_vars[c]) var_to_constraints[v].erase(c);
for (const int i : constraint_to_intervals[c]) interval_usage[i]--;
AddVariableUsage(c);
}
void PresolveContext::UpdateNewConstraintsVariableUsage() {
const int old_size = constraint_to_vars.size();
const int new_size = working_model->constraints_size();
CHECK_LE(old_size, new_size);
constraint_to_vars.resize(new_size);
constraint_to_intervals.resize(new_size);
interval_usage.resize(new_size);
for (int c = old_size; c < new_size; ++c) {
AddVariableUsage(c);
}
}
bool PresolveContext::ConstraintVariableUsageIsConsistent() {
if (is_unsat) return false;
if (constraint_to_vars.size() != working_model->constraints_size()) {
LOG(INFO) << "Wrong constraint_to_vars size!";
return false;
}
for (int c = 0; c < constraint_to_vars.size(); ++c) {
if (constraint_to_vars[c] != UsedVariables(working_model->constraints(c))) {
LOG(INFO) << "Wrong variables usage for constraint: \n"
<< ProtobufDebugString(working_model->constraints(c));
return false;
}
}
return true;
}
void PresolveContext::ExploitFixedDomain(int var) {
CHECK(IsFixed(var));
const int min = MinOf(var);
if (gtl::ContainsKey(constant_to_ref, min)) {
const int representative = constant_to_ref[min];
if (representative != var) {
affine_relations.TryAdd(var, representative, 1, 0);
var_equiv_relations.TryAdd(var, representative, 1, 0);
}
} else {
constant_to_ref[min] = var;
}
}
void PresolveContext::StoreAffineRelation(const ConstraintProto& ct, int ref_x,
int ref_y, int64 coeff,
int64 offset) {
int x = PositiveRef(ref_x);
int y = PositiveRef(ref_y);
if (is_unsat) return;
if (IsFixed(x) || IsFixed(y)) return;
int64 c = RefIsPositive(ref_x) == RefIsPositive(ref_y) ? coeff : -coeff;
int64 o = RefIsPositive(ref_x) ? offset : -offset;
const int rep_x = affine_relations.Get(x).representative;
const int rep_y = affine_relations.Get(y).representative;
// If a Boolean variable (one with domain [0, 1]) appear in this affine
// equivalence class, then we want its representative to be Boolean. Note
// that this is always possible because a Boolean variable can never be
// equal to a multiple of another if std::abs(coeff) is greater than 1 and
// if it is not fixed to zero. This is important because it allows to simply
// use the same representative for any referenced literals.
bool allow_rep_x = MinOf(rep_x) == 0 && MaxOf(rep_x) == 1;
bool allow_rep_y = MinOf(rep_y) == 0 && MaxOf(rep_y) == 1;
if (!allow_rep_x && !allow_rep_y) {
// If none are Boolean, we can use any representative.
allow_rep_x = true;
allow_rep_y = true;
}
// TODO(user): can we force the rep and remove GetAffineRelation()?
bool added = affine_relations.TryAdd(x, y, c, o, allow_rep_x, allow_rep_y);
if ((c == 1 || c == -1) && o == 0) {
added |= var_equiv_relations.TryAdd(x, y, c, o, allow_rep_x, allow_rep_y);
}
if (added) {
// The domain didn't change, but this notification allows to re-process
// any constraint containing these variables.
modified_domains.Set(x);
modified_domains.Set(y);
affine_constraints.insert(&ct);
}
}
void PresolveContext::StoreBooleanEqualityRelation(int ref_a, int ref_b) {
if (ref_a == ref_b) return;
if (ref_a == NegatedRef(ref_b)) {
is_unsat = true;
return;
}
bool added = false;
if (RefIsPositive(ref_a) == RefIsPositive(ref_b)) {
added |=
affine_relations.TryAdd(PositiveRef(ref_a), PositiveRef(ref_b), 1, 0);
added |= var_equiv_relations.TryAdd(PositiveRef(ref_a), PositiveRef(ref_b),
1, 0);
} else {
added |=
affine_relations.TryAdd(PositiveRef(ref_a), PositiveRef(ref_b), -1, 1);
}
if (!added) return;
modified_domains.Set(PositiveRef(ref_a));
modified_domains.Set(PositiveRef(ref_b));
// For now, we do need to add the relation ref_a == ref_b so we have a
// proper variable usage count and propagation between ref_a and ref_b.
//
// TODO(user): This looks unclean. We should probably handle the affine
// relation together without the need of keep all the constraints that
// define them around.
ConstraintProto* ct = working_model->add_constraints();
auto* arg = ct->mutable_linear();
arg->add_vars(PositiveRef(ref_a));
arg->add_vars(PositiveRef(ref_b));
if (RefIsPositive(ref_a) == RefIsPositive(ref_b)) {
// a = b
arg->add_coeffs(1);
arg->add_coeffs(-1);
arg->add_domain(0);
arg->add_domain(0);
} else {
// a = 1 - b
arg->add_coeffs(1);
arg->add_coeffs(1);
arg->add_domain(1);
arg->add_domain(1);
}
affine_constraints.insert(ct);
UpdateNewConstraintsVariableUsage();
}
// This makes sure that the affine relation only uses one of the
// representative from the var_equiv_relations.
AffineRelation::Relation PresolveContext::GetAffineRelation(int ref) {
AffineRelation::Relation r = affine_relations.Get(PositiveRef(ref));
AffineRelation::Relation o = var_equiv_relations.Get(r.representative);
r.representative = o.representative;
if (o.coeff == -1) r.coeff = -r.coeff;
if (!RefIsPositive(ref)) {
r.coeff *= -1;
r.offset *= -1;
}
return r;
}
// Create the internal structure for any new variables in working_model.
void PresolveContext::InitializeNewDomains() {
for (int i = domains.size(); i < working_model->variables_size(); ++i) {
Domain domain = ReadDomainFromProto(working_model->variables(i));
if (domain.IsEmpty()) {
is_unsat = true;
return;
}
domains.push_back(domain);
if (IsFixed(i)) ExploitFixedDomain(i);
}
modified_domains.Resize(domains.size());
var_to_constraints.resize(domains.size());
}
int PresolveContext::GetOrCreateVarValueEncoding(int ref, int64 value) {
// TODO(user,user): use affine relation here.
const int var = PositiveRef(ref);
const int64 s_value = RefIsPositive(ref) ? value : -value;
if (!domains[var].Contains(s_value)) {
return GetOrCreateConstantVar(0);
}
std::pair<int, int64> key{var, s_value};
if (encoding.contains(key)) return encoding[key];
if (domains[var].Size() == 1) {
const int true_literal = GetOrCreateConstantVar(1);
encoding[key] = true_literal;
return true_literal;
}
if (domains[var].Size() == 2) {
const int64 var_min = MinOf(var);
const int64 var_max = MaxOf(var);
if (var_min == 0 && var_max == 1) {
encoding[std::make_pair(var, 0)] = NegatedRef(var);
encoding[std::make_pair(var, 1)] = var;
} else {
const int literal = NewBoolVar();
encoding[std::make_pair(var, var_min)] = NegatedRef(literal);
encoding[std::make_pair(var, var_max)] = literal;
ConstraintProto* const ct = working_model->add_constraints();
LinearConstraintProto* const lin = ct->mutable_linear();
lin->add_vars(var);
lin->add_coeffs(1);
lin->add_vars(literal);
lin->add_coeffs(var_min - var_max);
lin->add_domain(var_min);
lin->add_domain(var_min);
StoreAffineRelation(*ct, var, literal, var_max - var_min, var_min);
}
return gtl::FindOrDieNoPrint(encoding, key);
}
const int literal = NewBoolVar();
AddImplyInDomain(literal, var, Domain(s_value));
AddImplyInDomain(NegatedRef(literal), var, Domain(s_value).Complement());
encoding[key] = literal;
return literal;
}
bool CpModelPresolver::RemoveConstraint(ConstraintProto* ct) {
ct->Clear();
return true;
}
void CpModelPresolver::SyncDomainAndRemoveEmptyConstraints() {
// 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_constraints = context_.working_model->constraints_size();
for (int c = 0; c < old_num_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_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);
}
for (int i = 0; i < context_.working_model->variables_size(); ++i) {
FillDomainInProto(context_.DomainOf(i),
context_.working_model->mutable_variables(i));
}
}
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);
}
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 artifically 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)) {
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();
// Recognized abs() encoding.
if (ct->int_max().vars_size() == 2 &&
NegatedRef(ct->int_max().vars(0)) == ct->int_max().vars(1)) {
const int var = PositiveRef(ct->int_max().vars(0));
// abs(x) == constant -> reduce domain.
if (context_.IsFixed(target_ref)) {
const int64 target_value = context_.MaxOf(target_ref);
if (target_value < 0) {
return context_.NotifyThatModelIsUnsat();
}
const Domain reduced_domain =
Domain::FromValues({-target_value, target_value});
if (!context_.IntersectDomainWith(var, reduced_domain)) {
return true;
}
context_.UpdateRuleStats(
"int_max: propagate domain of abs(x) == constant");
return RemoveConstraint(ct);
}
if (context_.MinOf(target_ref) < 0) {
context_.UpdateRuleStats("int_max: propagate abs(x) >= 0");
if (!context_.IntersectDomainWith(target_ref, {0, kint64max})) {
return true;
}
}
}
// 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_.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);
return RemoveConstraint(ct);
}
return modified;
}
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.
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;
}
}
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);
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();
context_.StoreAffineRelation(*new_ct, old_target, new_target, constant, 0);
}
// 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_.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 {