forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_loader.cc
1822 lines (1631 loc) · 69 KB
/
cp_model_loader.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_loader.h"
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "ortools/base/int_type.h"
#include "ortools/base/int_type_indexed_vector.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/stl_util.h"
#include "ortools/sat/all_different.h"
#include "ortools/sat/circuit.h"
#include "ortools/sat/cp_constraints.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/cumulative.h"
#include "ortools/sat/diffn.h"
#include "ortools/sat/disjunctive.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_expr.h"
#include "ortools/sat/intervals.h"
#include "ortools/sat/pb_constraint.h"
#include "ortools/sat/precedences.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/table.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace sat {
namespace {
template <typename Values>
std::vector<int64> ValuesFromProto(const Values& values) {
return std::vector<int64>(values.begin(), values.end());
}
void ComputeLinearBounds(const LinearConstraintProto& proto,
CpModelMapping* mapping, IntegerTrail* integer_trail,
int64* sum_min, int64* sum_max) {
*sum_min = 0;
*sum_max = 0;
for (int i = 0; i < proto.vars_size(); ++i) {
const int64 coeff = proto.coeffs(i);
const IntegerVariable var = mapping->Integer(proto.vars(i));
const int64 lb = integer_trail->LowerBound(var).value();
const int64 ub = integer_trail->UpperBound(var).value();
if (coeff >= 0) {
(*sum_min) += coeff * lb;
(*sum_max) += coeff * ub;
} else {
(*sum_min) += coeff * ub;
(*sum_max) += coeff * lb;
}
}
}
// We check if the constraint is a sum(ax * xi) == value.
bool ConstraintIsEq(const LinearConstraintProto& proto) {
return proto.domain_size() == 2 && proto.domain(0) == proto.domain(1);
}
// We check if the constraint is a sum(ax * xi) != value.
bool ConstraintIsNEq(const LinearConstraintProto& proto,
CpModelMapping* mapping, IntegerTrail* integer_trail,
int64* single_value) {
int64 sum_min = 0;
int64 sum_max = 0;
ComputeLinearBounds(proto, mapping, integer_trail, &sum_min, &sum_max);
const Domain complement =
Domain(sum_min, sum_max)
.IntersectionWith(ReadDomainFromProto(proto).Complement());
if (complement.IsEmpty()) return false;
const int64 value = complement.Min();
if (complement.Size() == 1) {
if (single_value != nullptr) {
*single_value = value;
}
return true;
}
return false;
}
} // namespace
void CpModelMapping::CreateVariables(const CpModelProto& model_proto,
bool view_all_booleans_as_integers,
Model* m) {
const int num_proto_variables = model_proto.variables_size();
// All [0, 1] variables always have a corresponding Boolean, even if it is
// fixed to 0 (domain == [0,0]) or fixed to 1 (domain == [1,1]).
{
auto* sat_solver = m->GetOrCreate<SatSolver>();
CHECK_EQ(sat_solver->NumVariables(), 0);
BooleanVariable new_var(0);
std::vector<BooleanVariable> false_variables;
std::vector<BooleanVariable> true_variables;
booleans_.resize(num_proto_variables, kNoBooleanVariable);
reverse_boolean_map_.resize(num_proto_variables, -1);
for (int i = 0; i < num_proto_variables; ++i) {
const auto& domain = model_proto.variables(i).domain();
if (domain.size() != 2) continue;
if (domain[0] >= 0 && domain[1] <= 1) {
booleans_[i] = new_var;
reverse_boolean_map_[new_var] = i;
if (domain[1] == 0) {
false_variables.push_back(new_var);
} else if (domain[0] == 1) {
true_variables.push_back(new_var);
}
++new_var;
}
}
sat_solver->SetNumVariables(new_var.value());
for (const BooleanVariable var : true_variables) {
m->Add(ClauseConstraint({sat::Literal(var, true)}));
}
for (const BooleanVariable var : false_variables) {
m->Add(ClauseConstraint({sat::Literal(var, false)}));
}
}
// Compute the list of positive variable reference for which we need to
// create an IntegerVariable.
std::vector<int> var_to_instantiate_as_integer;
if (view_all_booleans_as_integers) {
var_to_instantiate_as_integer.resize(num_proto_variables);
for (int i = 0; i < num_proto_variables; ++i) {
var_to_instantiate_as_integer[i] = i;
}
} else {
// Compute the integer variable references used by the model.
absl::flat_hash_set<int> used_variables;
IndexReferences refs;
for (int c = 0; c < model_proto.constraints_size(); ++c) {
const ConstraintProto& ct = model_proto.constraints(c);
refs = GetReferencesUsedByConstraint(ct);
for (const int ref : refs.variables) {
used_variables.insert(PositiveRef(ref));
}
}
// Add the objectives and search heuristics variables that needs to be
// referenceable as integer even if they are only used as Booleans.
if (model_proto.has_objective()) {
for (const int obj_var : model_proto.objective().vars()) {
used_variables.insert(PositiveRef(obj_var));
}
}
for (const DecisionStrategyProto& strategy :
model_proto.search_strategy()) {
for (const int var : strategy.variables()) {
used_variables.insert(PositiveRef(var));
}
}
// Make sure any unused variable, that is not already a Boolean is
// considered "used".
for (int i = 0; i < num_proto_variables; ++i) {
if (booleans_[i] == kNoBooleanVariable) {
used_variables.insert(i);
}
}
// We want the variable in the problem order.
var_to_instantiate_as_integer.assign(used_variables.begin(),
used_variables.end());
gtl::STLSortAndRemoveDuplicates(&var_to_instantiate_as_integer);
}
integers_.resize(num_proto_variables, kNoIntegerVariable);
auto* integer_trail = m->GetOrCreate<IntegerTrail>();
integer_trail->ReserveSpaceForNumVariables(
var_to_instantiate_as_integer.size());
reverse_integer_map_.resize(2 * var_to_instantiate_as_integer.size(), -1);
for (const int i : var_to_instantiate_as_integer) {
const auto& var_proto = model_proto.variables(i);
integers_[i] =
integer_trail->AddIntegerVariable(ReadDomainFromProto(var_proto));
DCHECK_LT(integers_[i], reverse_integer_map_.size());
reverse_integer_map_[integers_[i]] = i;
}
auto* encoder = m->GetOrCreate<IntegerEncoder>();
// Link any variable that has both views.
for (int i = 0; i < num_proto_variables; ++i) {
if (integers_[i] == kNoIntegerVariable) continue;
if (booleans_[i] == kNoBooleanVariable) continue;
// Associate with corresponding integer variable.
encoder->AssociateToIntegerEqualValue(sat::Literal(booleans_[i], true),
integers_[i], IntegerValue(1));
}
// Create the interval variables.
intervals_.resize(model_proto.constraints_size(), kNoIntervalVariable);
for (int c = 0; c < model_proto.constraints_size(); ++c) {
const ConstraintProto& ct = model_proto.constraints(c);
if (ct.constraint_case() != ConstraintProto::ConstraintCase::kInterval) {
continue;
}
if (HasEnforcementLiteral(ct)) {
const sat::Literal enforcement_literal =
Literal(ct.enforcement_literal(0));
// TODO(user): Fix the constant variable situation. An optional interval
// with constant start/end or size cannot share the same constant
// variable if it is used in non-optional situation.
intervals_[c] = m->Add(NewOptionalInterval(
Integer(ct.interval().start()), Integer(ct.interval().end()),
Integer(ct.interval().size()), enforcement_literal));
} else {
intervals_[c] = m->Add(NewInterval(Integer(ct.interval().start()),
Integer(ct.interval().end()),
Integer(ct.interval().size())));
}
already_loaded_ct_.insert(&ct);
}
}
// The logic assumes that the linear constraints have been presolved, so that
// equality with a domain bound have been converted to <= or >= and so that we
// never have any trivial inequalities.
//
// TODO(user): Regroup/presolve two encoding like b => x > 2 and the same
// Boolean b => x > 5. These shouldn't happen if we merge linear constraints.
void CpModelMapping::ExtractEncoding(const CpModelProto& model_proto,
Model* m) {
auto* encoder = m->GetOrCreate<IntegerEncoder>();
auto* integer_trail = m->GetOrCreate<IntegerTrail>();
auto* sat_solver = m->GetOrCreate<SatSolver>();
// TODO(user): Debug what makes it unsat at this point.
if (sat_solver->IsModelUnsat()) return;
// Detection of literal equivalent to (i_var == value). We collect all the
// half-reified constraint lit => equality or lit => inequality for a given
// variable, and we will later sort them to detect equivalence.
struct EqualityDetectionHelper {
const ConstraintProto* ct;
sat::Literal literal;
int64 value;
bool is_equality; // false if != instead.
bool operator<(const EqualityDetectionHelper& o) const {
if (literal.Variable() == o.literal.Variable()) {
if (value == o.value) return is_equality && !o.is_equality;
return value < o.value;
}
return literal.Variable() < o.literal.Variable();
}
};
std::vector<std::vector<EqualityDetectionHelper>> var_to_equalities(
model_proto.variables_size());
// TODO(user): We will re-add the same implied bounds during probing, so
// it might not be necessary to do that here. Also, it might be too early
// if some of the literal view used in the LP are created later, but that
// should be fixable via calls to implied_bounds->NotifyNewIntegerView().
auto* implied_bounds = m->GetOrCreate<ImpliedBounds>();
// Detection of literal equivalent to (i_var >= bound). We also collect
// all the half-refied part and we will sort the vector for detection of the
// equivalence.
struct InequalityDetectionHelper {
const ConstraintProto* ct;
sat::Literal literal;
IntegerLiteral i_lit;
bool operator<(const InequalityDetectionHelper& o) const {
if (literal.Variable() == o.literal.Variable()) {
return i_lit.var < o.i_lit.var;
}
return literal.Variable() < o.literal.Variable();
}
};
std::vector<InequalityDetectionHelper> inequalities;
// Loop over all contraints and fill var_to_equalities and inequalities.
for (const ConstraintProto& ct : model_proto.constraints()) {
if (ct.constraint_case() != ConstraintProto::ConstraintCase::kLinear) {
continue;
}
if (ct.enforcement_literal().size() != 1) continue;
if (ct.linear().vars_size() != 1) continue;
// ct is a linear constraint with one term and one enforcement literal.
const sat::Literal enforcement_literal = Literal(ct.enforcement_literal(0));
const int ref = ct.linear().vars(0);
const int var = PositiveRef(ref);
const Domain domain = ReadDomainFromProto(model_proto.variables(var));
const Domain domain_if_enforced =
ReadDomainFromProto(ct.linear())
.InverseMultiplicationBy(ct.linear().coeffs(0) *
(RefIsPositive(ref) ? 1 : -1));
// Detect enforcement_literal => (var >= value or var <= value).
if (domain_if_enforced.NumIntervals() == 1) {
if (domain_if_enforced.Max() >= domain.Max() &&
domain_if_enforced.Min() > domain.Min()) {
inequalities.push_back(
{&ct, enforcement_literal,
IntegerLiteral::GreaterOrEqual(
Integer(var), IntegerValue(domain_if_enforced.Min()))});
implied_bounds->Add(enforcement_literal, inequalities.back().i_lit);
} else if (domain_if_enforced.Min() <= domain.Min() &&
domain_if_enforced.Max() < domain.Max()) {
inequalities.push_back(
{&ct, enforcement_literal,
IntegerLiteral::LowerOrEqual(
Integer(var), IntegerValue(domain_if_enforced.Max()))});
implied_bounds->Add(enforcement_literal, inequalities.back().i_lit);
}
}
// Detect enforcement_literal => (var == value or var != value).
//
// Note that for domain with 2 values like [0, 1], we will detect both ==
// 0 and != 1. Similarly, for a domain in [min, max], we should both
// detect (== min) and (<= min), and both detect (== max) and (>= max).
{
const Domain inter = domain.IntersectionWith(domain_if_enforced);
if (!inter.IsEmpty() && inter.Min() == inter.Max()) {
var_to_equalities[var].push_back(
{&ct, enforcement_literal, inter.Min(), true});
if (domain.Contains(inter.Min())) {
variables_to_encoded_values_[var].insert(inter.Min());
}
}
}
{
const Domain inter =
domain.IntersectionWith(domain_if_enforced.Complement());
if (!inter.IsEmpty() && inter.Min() == inter.Max()) {
var_to_equalities[var].push_back(
{&ct, enforcement_literal, inter.Min(), false});
if (domain.Contains(inter.Min())) {
variables_to_encoded_values_[var].insert(inter.Min());
}
}
}
}
// Detect Literal <=> X >= value
int num_inequalities = 0;
std::sort(inequalities.begin(), inequalities.end());
for (int i = 0; i + 1 < inequalities.size(); i++) {
if (inequalities[i].literal != inequalities[i + 1].literal.Negated()) {
continue;
}
// TODO(user): In these cases, we could fix the enforcement literal right
// away or ignore the constraint. Note that it will be done later anyway
// though.
if (integer_trail->IntegerLiteralIsTrue(inequalities[i].i_lit) ||
integer_trail->IntegerLiteralIsFalse(inequalities[i].i_lit)) {
continue;
}
if (integer_trail->IntegerLiteralIsTrue(inequalities[i + 1].i_lit) ||
integer_trail->IntegerLiteralIsFalse(inequalities[i + 1].i_lit)) {
continue;
}
const auto pair_a = encoder->Canonicalize(inequalities[i].i_lit);
const auto pair_b = encoder->Canonicalize(inequalities[i + 1].i_lit);
if (pair_a.first == pair_b.second) {
++num_inequalities;
encoder->AssociateToIntegerLiteral(inequalities[i].literal,
inequalities[i].i_lit);
already_loaded_ct_.insert(inequalities[i].ct);
already_loaded_ct_.insert(inequalities[i + 1].ct);
}
}
// Encode the half-inequalities.
int num_half_inequalities = 0;
for (const auto inequality : inequalities) {
if (ConstraintIsAlreadyLoaded(inequality.ct)) continue;
m->Add(
Implication(inequality.literal,
encoder->GetOrCreateAssociatedLiteral(inequality.i_lit)));
if (sat_solver->IsModelUnsat()) return;
++num_half_inequalities;
already_loaded_ct_.insert(inequality.ct);
is_half_encoding_ct_.insert(inequality.ct);
}
if (!inequalities.empty()) {
VLOG(1) << num_inequalities << " literals associated to VAR >= value, and "
<< num_half_inequalities << " half-associations.";
}
// Detect Literal <=> X == value and associate them in the IntegerEncoder.
//
// TODO(user): Fully encode variable that are almost fully encoded?
int num_constraints = 0;
int num_equalities = 0;
int num_half_equalities = 0;
int num_fully_encoded = 0;
int num_partially_encoded = 0;
for (int i = 0; i < var_to_equalities.size(); ++i) {
std::vector<EqualityDetectionHelper>& encoding = var_to_equalities[i];
std::sort(encoding.begin(), encoding.end());
if (encoding.empty()) continue;
num_constraints += encoding.size();
absl::flat_hash_set<int64> values;
for (int j = 0; j + 1 < encoding.size(); j++) {
if ((encoding[j].value != encoding[j + 1].value) ||
(encoding[j].literal != encoding[j + 1].literal.Negated()) ||
(encoding[j].is_equality != true) ||
(encoding[j + 1].is_equality != false)) {
continue;
}
++num_equalities;
encoder->AssociateToIntegerEqualValue(encoding[j].literal, integers_[i],
IntegerValue(encoding[j].value));
already_loaded_ct_.insert(encoding[j].ct);
already_loaded_ct_.insert(encoding[j + 1].ct);
values.insert(encoding[j].value);
}
// TODO(user): Try to remove it. Normally we caught UNSAT above, but
// tests are very flaky (it only happens in parallel). Keeping it there for
// the time being.
if (sat_solver->IsModelUnsat()) return;
// Encode the half-equalities.
//
// TODO(user): delay this after PropagateEncodingFromEquivalenceRelations()?
// Otherwise we might create new Boolean variables for no reason. Note
// however, that in the presolve, we should only use the "representative" in
// linear constraints, so we should be fine.
for (const auto equality : encoding) {
if (ConstraintIsAlreadyLoaded(equality.ct)) continue;
const class Literal eq = encoder->GetOrCreateLiteralAssociatedToEquality(
integers_[i], IntegerValue(equality.value));
if (equality.is_equality) {
m->Add(Implication(equality.literal, eq));
} else {
m->Add(Implication(equality.literal, eq.Negated()));
}
++num_half_equalities;
already_loaded_ct_.insert(equality.ct);
is_half_encoding_ct_.insert(equality.ct);
}
// Update stats.
if (VLOG_IS_ON(1)) {
if (encoder->VariableIsFullyEncoded(integers_[i])) {
++num_fully_encoded;
} else {
++num_partially_encoded;
}
}
}
if (num_constraints > 0) {
VLOG(1) << num_equalities << " literals associated to VAR == value, and "
<< num_half_equalities << " half-associations.";
}
if (num_fully_encoded > 0) {
VLOG(1) << "num_fully_encoded_variables: " << num_fully_encoded;
}
if (num_partially_encoded > 0) {
VLOG(1) << "num_partially_encoded_variables: " << num_partially_encoded;
}
}
void CpModelMapping::PropagateEncodingFromEquivalenceRelations(
const CpModelProto& model_proto, Model* m) {
auto* encoder = m->GetOrCreate<IntegerEncoder>();
auto* sat_solver = m->GetOrCreate<SatSolver>();
// Loop over all contraints and find affine ones.
int64 num_associations = 0;
int64 num_set_to_false = 0;
for (const ConstraintProto& ct : model_proto.constraints()) {
if (!ct.enforcement_literal().empty()) continue;
if (ct.constraint_case() != ConstraintProto::kLinear) continue;
if (ct.linear().vars_size() != 2) continue;
if (!ConstraintIsEq(ct.linear())) continue;
const IntegerValue rhs(ct.linear().domain(0));
// Make sure the coefficient are positive.
IntegerVariable var1 = Integer(ct.linear().vars(0));
IntegerVariable var2 = Integer(ct.linear().vars(1));
IntegerValue coeff1(ct.linear().coeffs(0));
IntegerValue coeff2(ct.linear().coeffs(1));
if (coeff1 < 0) {
var1 = NegationOf(var1);
coeff1 = -coeff1;
}
if (coeff2 < 0) {
var2 = NegationOf(var2);
coeff2 = -coeff2;
}
// TODO(user): This is not supposed to happen, but apparently it did on
// once on routing_GCM_0001_sat.fzn. Investigate and fix.
if (coeff1 == 0 || coeff2 == 0) continue;
// We first map the >= literals.
// It is important to do that first, since otherwise mapping a == literal
// might creates the underlying >= and <= literals.
for (int i = 0; i < 2; ++i) {
for (const auto value_literal :
encoder->PartialGreaterThanEncoding(var1)) {
const IntegerValue value1 = value_literal.first;
const IntegerValue bound2 = FloorRatio(rhs - value1 * coeff1, coeff2);
++num_associations;
encoder->AssociateToIntegerLiteral(
value_literal.second, IntegerLiteral::LowerOrEqual(var2, bound2));
}
std::swap(var1, var2);
std::swap(coeff1, coeff2);
}
// Same for the == literals.
//
// TODO(user): This is similar to LoadEquivalenceAC() for unreified
// constraints, but when the later is called, more encoding might have taken
// place.
for (int i = 0; i < 2; ++i) {
for (const auto value_literal : encoder->PartialDomainEncoding(var1)) {
const IntegerValue value1 = value_literal.value;
const IntegerValue intermediate = rhs - value1 * coeff1;
if (intermediate % coeff2 != 0) {
// Using this function deals properly with UNSAT.
++num_set_to_false;
sat_solver->AddUnitClause(value_literal.literal.Negated());
continue;
}
++num_associations;
encoder->AssociateToIntegerEqualValue(value_literal.literal, var2,
intermediate / coeff2);
}
std::swap(var1, var2);
std::swap(coeff1, coeff2);
}
}
if (num_associations > 0) {
VLOG(1) << "Num associations from equivalences = " << num_associations;
}
if (num_set_to_false > 0) {
VLOG(1) << "Num literals set to false from equivalences = "
<< num_set_to_false;
}
}
void CpModelMapping::DetectOptionalVariables(const CpModelProto& model_proto,
Model* m) {
const SatParameters& parameters = *(m->GetOrCreate<SatParameters>());
if (!parameters.use_optional_variables()) return;
if (parameters.enumerate_all_solutions()) return;
// The variables from the objective cannot be marked as optional!
const int num_proto_variables = model_proto.variables_size();
std::vector<bool> already_seen(num_proto_variables, false);
if (model_proto.has_objective()) {
for (const int ref : model_proto.objective().vars()) {
already_seen[PositiveRef(ref)] = true;
}
}
// Compute for each variables the intersection of the enforcement literals
// of the constraints in which they appear.
//
// TODO(user): This deals with the simplest cases, but we could try to
// detect literals that implies all the constaints in which a variable
// appear to false. This can be done with a LCA computation in the tree of
// Boolean implication (once the presolve remove cycles). Not sure if we can
// properly exploit that afterwards though. Do some research!
std::vector<std::vector<int>> enforcement_intersection(num_proto_variables);
std::set<int> literals_set;
for (int c = 0; c < model_proto.constraints_size(); ++c) {
const ConstraintProto& ct = model_proto.constraints(c);
if (ct.enforcement_literal().empty()) {
for (const int var : UsedVariables(ct)) {
already_seen[var] = true;
enforcement_intersection[var].clear();
}
} else {
literals_set.clear();
literals_set.insert(ct.enforcement_literal().begin(),
ct.enforcement_literal().end());
for (const int var : UsedVariables(ct)) {
if (!already_seen[var]) {
enforcement_intersection[var].assign(ct.enforcement_literal().begin(),
ct.enforcement_literal().end());
} else {
// Take the intersection.
std::vector<int>& vector_ref = enforcement_intersection[var];
int new_size = 0;
for (const int literal : vector_ref) {
if (gtl::ContainsKey(literals_set, literal)) {
vector_ref[new_size++] = literal;
}
}
vector_ref.resize(new_size);
}
already_seen[var] = true;
}
}
}
// Auto-detect optional variables.
int num_optionals = 0;
auto* integer_trail = m->GetOrCreate<IntegerTrail>();
for (int var = 0; var < num_proto_variables; ++var) {
const IntegerVariableProto& var_proto = model_proto.variables(var);
const int64 min = var_proto.domain(0);
const int64 max = var_proto.domain(var_proto.domain().size() - 1);
if (min == max) continue;
if (min == 0 && max == 1) continue;
if (enforcement_intersection[var].empty()) continue;
++num_optionals;
integer_trail->MarkIntegerVariableAsOptional(
Integer(var), Literal(enforcement_intersection[var].front()));
}
VLOG(2) << "Auto-detected " << num_optionals << " optional variables.";
}
// ============================================================================
// A class that detects when variables should be fully encoded by computing a
// fixed point. It also fully encodes such variables.
// ============================================================================
class FullEncodingFixedPointComputer {
public:
FullEncodingFixedPointComputer(const CpModelProto& model_proto, Model* model)
: model_proto_(model_proto),
parameters_(*(model->GetOrCreate<SatParameters>())),
model_(model),
mapping_(model->GetOrCreate<CpModelMapping>()),
integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
integer_trail_(model->GetOrCreate<IntegerTrail>()) {}
void ComputeFixedPoint();
private:
DEFINE_INT_TYPE(ConstraintIndex, int32);
// Constraint ct is interested by (full-encoding) state of variable.
void Register(ConstraintIndex ct_index, int variable) {
variable = PositiveRef(variable);
constraint_is_registered_[ct_index] = true;
if (variable_watchers_.size() <= variable) {
variable_watchers_.resize(variable + 1);
variable_was_added_in_to_propagate_.resize(variable + 1);
}
variable_watchers_[variable].push_back(ct_index);
}
void AddVariableToPropagationQueue(int variable) {
variable = PositiveRef(variable);
if (variable_was_added_in_to_propagate_.size() <= variable) {
variable_watchers_.resize(variable + 1);
variable_was_added_in_to_propagate_.resize(variable + 1);
}
if (!variable_was_added_in_to_propagate_[variable]) {
variable_was_added_in_to_propagate_[variable] = true;
variables_to_propagate_.push_back(variable);
}
}
// Note that we always consider a fixed variable to be fully encoded here.
const bool IsFullyEncoded(int v) {
const IntegerVariable variable = mapping_->Integer(v);
if (v == kNoIntegerVariable) return false;
return integer_trail_->IsFixed(variable) ||
integer_encoder_->VariableIsFullyEncoded(variable);
}
const bool VariableIsFixed(int v) {
const IntegerVariable variable = mapping_->Integer(v);
if (v == kNoIntegerVariable) return false;
return integer_trail_->IsFixed(variable);
}
void FullyEncode(int v) {
v = PositiveRef(v);
const IntegerVariable variable = mapping_->Integer(v);
if (v == kNoIntegerVariable) return;
if (!integer_trail_->IsFixed(variable)) {
model_->Add(FullyEncodeVariable(variable));
}
AddVariableToPropagationQueue(v);
}
bool ProcessConstraint(ConstraintIndex ct_index);
bool ProcessElement(ConstraintIndex ct_index);
bool ProcessTable(ConstraintIndex ct_index);
bool ProcessAutomaton(ConstraintIndex ct_index);
bool ProcessLinear(ConstraintIndex ct_index);
const CpModelProto& model_proto_;
const SatParameters& parameters_;
Model* model_;
CpModelMapping* mapping_;
IntegerEncoder* integer_encoder_;
IntegerTrail* integer_trail_;
std::vector<bool> variable_was_added_in_to_propagate_;
std::vector<int> variables_to_propagate_;
std::vector<std::vector<ConstraintIndex>> variable_watchers_;
gtl::ITIVector<ConstraintIndex, bool> constraint_is_finished_;
gtl::ITIVector<ConstraintIndex, bool> constraint_is_registered_;
absl::flat_hash_map<int, absl::flat_hash_set<int>>
variables_to_equal_or_diff_variables_;
};
// We only add to the propagation queue variable that are fully encoded.
// Note that if a variable was already added once, we never add it again.
void FullEncodingFixedPointComputer::ComputeFixedPoint() {
const int num_constraints = model_proto_.constraints_size();
const int num_vars = model_proto_.variables_size();
constraint_is_finished_.assign(num_constraints, false);
constraint_is_registered_.assign(num_constraints, false);
// Process all constraint once.
for (ConstraintIndex ct_index(0); ct_index < num_constraints; ++ct_index) {
constraint_is_finished_[ct_index] = ProcessConstraint(ct_index);
}
// We run a heuristics to decide if we want to fully encode a variable or not.
// We decide to fully encode a variable if:
// - a variable appears in enough a1 * x1 + a2 + x2 ==/!= value and the
// domain is small.
// - the number of values that appears in b => x ==/!= value that are not
// the bounds of the variables is more that half the size of the domain.
// . - the size of the domain is > 2
int num_variables_fully_encoded_by_heuristics = 0;
for (int var = 0; var < num_vars; ++var) {
if (!mapping_->IsInteger(var) || IsFullyEncoded(var)) continue;
const IntegerVariableProto& int_var_proto = model_proto_.variables(var);
const Domain domain = ReadDomainFromProto(int_var_proto);
int64 domain_size = domain.Size();
int64 num_diff_or_equal_var_constraints = 0;
int64 num_potential_encoded_values_without_bounds = 0;
if (domain_size <= 2) continue;
const absl::flat_hash_set<int64>& value_set =
mapping_->PotentialEncodedValues(var);
for (const int value : value_set) {
if (value > domain.Min() && value < domain.Max() &&
domain.Contains(value)) {
num_potential_encoded_values_without_bounds++;
}
}
const auto& it = variables_to_equal_or_diff_variables_.find(var);
if (it != variables_to_equal_or_diff_variables_.end()) {
num_diff_or_equal_var_constraints = it->second.size();
}
if (num_potential_encoded_values_without_bounds >= domain_size / 2 ||
(num_diff_or_equal_var_constraints >= domain_size / 2 &&
domain_size < 16)) {
VLOG(3) << model_proto_.variables(var).ShortDebugString()
<< " is encoded with "
<< num_potential_encoded_values_without_bounds
<< " unary constraints, and " << num_diff_or_equal_var_constraints
<< " binary constraints on a domain of size " << domain_size;
FullyEncode(var);
num_variables_fully_encoded_by_heuristics++;
}
}
if (num_variables_fully_encoded_by_heuristics > 0) {
VLOG(2) << num_variables_fully_encoded_by_heuristics
<< " variables fully encoded after model introspection.";
}
// Make sure all fully encoded variables of interest are in the queue.
for (int v = 0; v < variable_watchers_.size(); v++) {
if (!variable_watchers_[v].empty() && IsFullyEncoded(v)) {
AddVariableToPropagationQueue(v);
}
}
// Loop until no additional variable can be fully encoded.
while (!variables_to_propagate_.empty()) {
const int variable = variables_to_propagate_.back();
variables_to_propagate_.pop_back();
for (const ConstraintIndex ct_index : variable_watchers_[variable]) {
if (constraint_is_finished_[ct_index]) continue;
constraint_is_finished_[ct_index] = ProcessConstraint(ct_index);
}
}
}
// Returns true if the constraint has finished encoding what it wants.
bool FullEncodingFixedPointComputer::ProcessConstraint(
ConstraintIndex ct_index) {
const ConstraintProto& ct = model_proto_.constraints(ct_index.value());
switch (ct.constraint_case()) {
case ConstraintProto::ConstraintProto::kElement:
return ProcessElement(ct_index);
case ConstraintProto::ConstraintProto::kTable:
return ProcessTable(ct_index);
case ConstraintProto::ConstraintProto::kAutomaton:
return ProcessAutomaton(ct_index);
case ConstraintProto::ConstraintProto::kLinear:
return ProcessLinear(ct_index);
default:
return true;
}
}
bool FullEncodingFixedPointComputer::ProcessElement(ConstraintIndex ct_index) {
const ConstraintProto& ct = model_proto_.constraints(ct_index.value());
// Index must always be full encoded.
FullyEncode(ct.element().index());
const int target = ct.element().target();
// If target is fixed, do not encode variables.
if (VariableIsFixed(target)) return true;
// If target is a constant or fully encoded, variables must be fully encoded.
if (IsFullyEncoded(target)) {
for (const int v : ct.element().vars()) FullyEncode(v);
}
// If all non-target variables are fully encoded, target must be too.
bool all_variables_are_fully_encoded = true;
for (const int v : ct.element().vars()) {
if (v == target) continue;
if (!IsFullyEncoded(v)) {
all_variables_are_fully_encoded = false;
break;
}
}
if (all_variables_are_fully_encoded) {
if (!IsFullyEncoded(target)) FullyEncode(target);
return true;
}
// If some variables are not fully encoded, register on those.
if (constraint_is_registered_[ct_index]) {
for (const int v : ct.element().vars()) Register(ct_index, v);
Register(ct_index, target);
}
return false;
}
bool FullEncodingFixedPointComputer::ProcessTable(ConstraintIndex ct_index) {
const ConstraintProto& ct = model_proto_.constraints(ct_index.value());
if (ct.table().negated()) return true;
for (const int variable : ct.table().vars()) {
FullyEncode(variable);
}
return true;
}
bool FullEncodingFixedPointComputer::ProcessAutomaton(
ConstraintIndex ct_index) {
const ConstraintProto& ct = model_proto_.constraints(ct_index.value());
for (const int variable : ct.automaton().vars()) {
FullyEncode(variable);
}
return true;
}
bool FullEncodingFixedPointComputer::ProcessLinear(ConstraintIndex ct_index) {
// We are only interested in linear equations of the form:
// [b =>] a1 * x1 + a2 * x2 ==|!= value
const ConstraintProto& ct = model_proto_.constraints(ct_index.value());
if (parameters_.boolean_encoding_level() == 0 ||
ct.linear().vars_size() != 2) {
return true;
}
if (!ConstraintIsEq(ct.linear()) &&
!ConstraintIsNEq(ct.linear(), mapping_, integer_trail_, nullptr)) {
return true;
}
const int var0 = ct.linear().vars(0);
const int var1 = ct.linear().vars(1);
if (!IsFullyEncoded(var0)) {
variables_to_equal_or_diff_variables_[var0].insert(var1);
}
if (!IsFullyEncoded(var1)) {
variables_to_equal_or_diff_variables_[var1].insert(var0);
}
return true;
}
void MaybeFullyEncodeMoreVariables(const CpModelProto& model_proto, Model* m) {
FullEncodingFixedPointComputer fixpoint(model_proto, m);
fixpoint.ComputeFixedPoint();
}
// ============================================================================
// Constraint loading functions.
// ============================================================================
void LoadBoolOrConstraint(const ConstraintProto& ct, Model* m) {
auto* mapping = m->GetOrCreate<CpModelMapping>();
std::vector<Literal> literals = mapping->Literals(ct.bool_or().literals());
for (const int ref : ct.enforcement_literal()) {
literals.push_back(mapping->Literal(ref).Negated());
}
m->Add(ClauseConstraint(literals));
}
void LoadBoolAndConstraint(const ConstraintProto& ct, Model* m) {
auto* mapping = m->GetOrCreate<CpModelMapping>();
std::vector<Literal> literals;
for (const int ref : ct.enforcement_literal()) {
literals.push_back(mapping->Literal(ref).Negated());
}
auto* sat_solver = m->GetOrCreate<SatSolver>();
for (const Literal literal : mapping->Literals(ct.bool_and().literals())) {
literals.push_back(literal);
sat_solver->AddProblemClause(literals);
literals.pop_back();
}
}
void LoadAtMostOneConstraint(const ConstraintProto& ct, Model* m) {
auto* mapping = m->GetOrCreate<CpModelMapping>();
CHECK(!HasEnforcementLiteral(ct)) << "Not supported.";
m->Add(AtMostOneConstraint(mapping->Literals(ct.at_most_one().literals())));
}
void LoadBoolXorConstraint(const ConstraintProto& ct, Model* m) {
auto* mapping = m->GetOrCreate<CpModelMapping>();
CHECK(!HasEnforcementLiteral(ct)) << "Not supported.";
m->Add(LiteralXorIs(mapping->Literals(ct.bool_xor().literals()), true));
}
namespace {
// Boolean encoding of:
// enforcement_literal => coeff1 * var1 + coeff2 * var2 == rhs;
void LoadEquivalenceAC(const std::vector<Literal> enforcement_literal,
IntegerValue coeff1, IntegerVariable var1,
IntegerValue coeff2, IntegerVariable var2,
const IntegerValue rhs, Model* m) {
auto* encoder = m->GetOrCreate<IntegerEncoder>();
CHECK(encoder->VariableIsFullyEncoded(var1));
CHECK(encoder->VariableIsFullyEncoded(var2));
absl::flat_hash_map<IntegerValue, Literal> term1_value_to_literal;
for (const auto value_literal : encoder->FullDomainEncoding(var1)) {
term1_value_to_literal[coeff1 * value_literal.value] =
value_literal.literal;
}
for (const auto value_literal : encoder->FullDomainEncoding(var2)) {
const IntegerValue target = rhs - value_literal.value * coeff2;
if (!gtl::ContainsKey(term1_value_to_literal, target)) {
m->Add(EnforcedClause(enforcement_literal,