forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_expand.cc
1502 lines (1346 loc) · 55.3 KB
/
cp_model_expand.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/cp_model_expand.h"
#include <cstdint>
#include <limits>
#include <map>
#include "absl/container/flat_hash_map.h"
#include "ortools/base/hash.h"
#include "ortools/base/map_util.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_utils.h"
#include "ortools/sat/presolve_context.h"
#include "ortools/sat/util.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
namespace operations_research {
namespace sat {
namespace {
void ExpandReservoir(ConstraintProto* ct, PresolveContext* context) {
if (ct->reservoir().min_level() > ct->reservoir().max_level()) {
VLOG(1) << "Empty level domain in reservoir constraint.";
return (void)context->NotifyThatModelIsUnsat();
}
const ReservoirConstraintProto& reservoir = ct->reservoir();
const int num_events = reservoir.times_size();
const int true_literal = context->GetOrCreateConstantVar(1);
const auto is_active_literal = [&reservoir, true_literal](int index) {
if (reservoir.actives_size() == 0) return true_literal;
return reservoir.actives(index);
};
int num_positives = 0;
int num_negatives = 0;
for (const int64_t demand : reservoir.demands()) {
if (demand > 0) {
num_positives++;
} else if (demand < 0) {
num_negatives++;
}
}
if (num_positives > 0 && num_negatives > 0) {
// Creates Boolean variables equivalent to (start[i] <= start[j]) i != j
for (int i = 0; i < num_events - 1; ++i) {
const int active_i = is_active_literal(i);
if (context->LiteralIsFalse(active_i)) continue;
const int time_i = reservoir.times(i);
for (int j = i + 1; j < num_events; ++j) {
const int active_j = is_active_literal(j);
if (context->LiteralIsFalse(active_j)) continue;
const int time_j = reservoir.times(j);
const int i_lesseq_j = context->GetOrCreateReifiedPrecedenceLiteral(
time_i, time_j, active_i, active_j);
context->working_model->mutable_variables(i_lesseq_j)
->set_name(absl::StrCat(i, " before ", j));
const int j_lesseq_i = context->GetOrCreateReifiedPrecedenceLiteral(
time_j, time_i, active_j, active_i);
context->working_model->mutable_variables(j_lesseq_i)
->set_name(absl::StrCat(j, " before ", i));
}
}
// Constrains the running level to be consistent at all times.
// For this we only add a constraint at the time a given demand
// take place. We also have a constraint for time zero if needed
// (added below).
for (int i = 0; i < num_events; ++i) {
const int active_i = is_active_literal(i);
if (context->LiteralIsFalse(active_i)) continue;
const int time_i = reservoir.times(i);
// Accumulates demands of all predecessors.
ConstraintProto* const level = context->working_model->add_constraints();
level->add_enforcement_literal(active_i);
// Add contributions from previous events.
for (int j = 0; j < num_events; ++j) {
if (i == j) continue;
const int active_j = is_active_literal(j);
if (context->LiteralIsFalse(active_j)) continue;
const int time_j = reservoir.times(j);
level->mutable_linear()->add_vars(
context->GetOrCreateReifiedPrecedenceLiteral(time_j, time_i,
active_j, active_i));
level->mutable_linear()->add_coeffs(reservoir.demands(j));
}
// Accounts for own demand in the domain of the sum.
const int64_t demand_i = reservoir.demands(i);
level->mutable_linear()->add_domain(
CapSub(reservoir.min_level(), demand_i));
level->mutable_linear()->add_domain(
CapSub(reservoir.max_level(), demand_i));
}
} else {
// If all demands have the same sign, we do not care about the order, just
// the sum.
auto* const sum =
context->working_model->add_constraints()->mutable_linear();
for (int i = 0; i < num_events; ++i) {
sum->add_vars(is_active_literal(i));
sum->add_coeffs(reservoir.demands(i));
}
sum->add_domain(reservoir.min_level());
sum->add_domain(reservoir.max_level());
}
ct->Clear();
context->UpdateRuleStats("reservoir: expanded");
}
// This is not an "expansion" per say, but just a mandatory presolve step to
// satisfy preconditions assumed by the rest of the code.
void ExpandIntDiv(ConstraintProto* ct, PresolveContext* context) {
const int divisor = ct->int_div().vars(1);
if (!context->IntersectDomainWith(divisor, Domain(0).Complement())) {
return (void)context->NotifyThatModelIsUnsat();
}
}
void ExpandIntMod(ConstraintProto* ct, PresolveContext* context) {
const IntegerArgumentProto& int_mod = ct->int_mod();
const int var = int_mod.vars(0);
const int mod_var = int_mod.vars(1);
const int target_var = int_mod.target();
const int64_t mod_lb = context->MinOf(mod_var);
CHECK_GE(mod_lb, 1);
const int64_t mod_ub = context->MaxOf(mod_var);
const int64_t var_lb = context->MinOf(var);
const int64_t var_ub = context->MaxOf(var);
// Compute domains of var / mod_var.
// TODO(user): implement Domain.ContinuousDivisionBy(domain).
const int div_var =
context->NewIntVar(Domain(var_lb / mod_ub, var_ub / mod_lb));
auto add_enforcement_literal_if_needed = [&]() {
if (ct->enforcement_literal_size() == 0) return;
const int literal = ct->enforcement_literal(0);
ConstraintProto* const last = context->working_model->mutable_constraints(
context->working_model->constraints_size() - 1);
last->add_enforcement_literal(literal);
};
// div = var / mod.
IntegerArgumentProto* const div_proto =
context->working_model->add_constraints()->mutable_int_div();
div_proto->set_target(div_var);
div_proto->add_vars(var);
div_proto->add_vars(mod_var);
add_enforcement_literal_if_needed();
// Checks if mod is constant.
if (mod_lb == mod_ub) {
// var - div_var * mod = target.
LinearConstraintProto* const lin =
context->working_model->add_constraints()->mutable_linear();
lin->add_vars(int_mod.vars(0));
lin->add_coeffs(1);
lin->add_vars(div_var);
lin->add_coeffs(-mod_lb);
lin->add_vars(target_var);
lin->add_coeffs(-1);
lin->add_domain(0);
lin->add_domain(0);
add_enforcement_literal_if_needed();
} else {
// Create prod_var = div_var * mod.
const int prod_var = context->NewIntVar(
context->DomainOf(div_var).ContinuousMultiplicationBy(
context->DomainOf(mod_var)));
IntegerArgumentProto* const int_prod =
context->working_model->add_constraints()->mutable_int_prod();
int_prod->set_target(prod_var);
int_prod->add_vars(div_var);
int_prod->add_vars(mod_var);
add_enforcement_literal_if_needed();
// var - prod_var = target.
LinearConstraintProto* const lin =
context->working_model->add_constraints()->mutable_linear();
lin->add_vars(var);
lin->add_coeffs(1);
lin->add_vars(prod_var);
lin->add_coeffs(-1);
lin->add_vars(target_var);
lin->add_coeffs(-1);
lin->add_domain(0);
lin->add_domain(0);
add_enforcement_literal_if_needed();
}
ct->Clear();
context->UpdateRuleStats("int_mod: expanded");
}
void ExpandIntProdWithBoolean(int bool_ref, int int_ref, int product_ref,
PresolveContext* context) {
ConstraintProto* const one = context->working_model->add_constraints();
one->add_enforcement_literal(bool_ref);
one->mutable_linear()->add_vars(int_ref);
one->mutable_linear()->add_coeffs(1);
one->mutable_linear()->add_vars(product_ref);
one->mutable_linear()->add_coeffs(-1);
one->mutable_linear()->add_domain(0);
one->mutable_linear()->add_domain(0);
ConstraintProto* const zero = context->working_model->add_constraints();
zero->add_enforcement_literal(NegatedRef(bool_ref));
zero->mutable_linear()->add_vars(product_ref);
zero->mutable_linear()->add_coeffs(1);
zero->mutable_linear()->add_domain(0);
zero->mutable_linear()->add_domain(0);
}
void AddXEqualYOrXEqualZero(int x_eq_y, int x, int y,
PresolveContext* context) {
ConstraintProto* equality = context->working_model->add_constraints();
equality->add_enforcement_literal(x_eq_y);
equality->mutable_linear()->add_vars(x);
equality->mutable_linear()->add_coeffs(1);
equality->mutable_linear()->add_vars(y);
equality->mutable_linear()->add_coeffs(-1);
equality->mutable_linear()->add_domain(0);
equality->mutable_linear()->add_domain(0);
context->AddImplyInDomain(NegatedRef(x_eq_y), x, {0, 0});
}
// a_ref spans across 0, b_ref does not.
void ExpandIntProdWithOneAcrossZero(int a_ref, int b_ref, int product_ref,
PresolveContext* context) {
DCHECK_LT(context->MinOf(a_ref), 0);
DCHECK_GT(context->MaxOf(a_ref), 0);
DCHECK(context->MinOf(b_ref) >= 0 || context->MaxOf(b_ref) <= 0);
// Split the domain of a in two, controlled by a new literal.
const int a_is_positive = context->NewBoolVar();
context->AddImplyInDomain(a_is_positive, a_ref,
{0, std::numeric_limits<int64_t>::max()});
context->AddImplyInDomain(NegatedRef(a_is_positive), a_ref,
{std::numeric_limits<int64_t>::min(), -1});
const int pos_a_ref = context->NewIntVar({0, context->MaxOf(a_ref)});
AddXEqualYOrXEqualZero(a_is_positive, pos_a_ref, a_ref, context);
const int neg_a_ref = context->NewIntVar({context->MinOf(a_ref), 0});
AddXEqualYOrXEqualZero(NegatedRef(a_is_positive), neg_a_ref, a_ref, context);
// Create product with the positive part ofa_ref.
const bool b_is_positive = context->MinOf(b_ref) >= 0;
const Domain pos_a_product_domain =
b_is_positive ? Domain({0, context->MaxOf(product_ref)})
: Domain({context->MinOf(product_ref), 0});
const int pos_a_product = context->NewIntVar(pos_a_product_domain);
IntegerArgumentProto* pos_product =
context->working_model->add_constraints()->mutable_int_prod();
pos_product->set_target(pos_a_product);
pos_product->add_vars(pos_a_ref);
pos_product->add_vars(b_ref);
// Create product with the negative part of a_ref.
const Domain neg_a_product_domain =
b_is_positive ? Domain({context->MinOf(product_ref), 0})
: Domain({0, context->MaxOf(product_ref)});
const int neg_a_product = context->NewIntVar(neg_a_product_domain);
IntegerArgumentProto* neg_product =
context->working_model->add_constraints()->mutable_int_prod();
neg_product->set_target(neg_a_product);
neg_product->add_vars(neg_a_ref);
neg_product->add_vars(b_ref);
// Link back to the original product.
LinearConstraintProto* lin =
context->working_model->add_constraints()->mutable_linear();
lin->add_vars(product_ref);
lin->add_coeffs(-1);
lin->add_vars(pos_a_product);
lin->add_coeffs(1);
lin->add_vars(neg_a_product);
lin->add_coeffs(1);
lin->add_domain(0);
lin->add_domain(0);
}
void ExpandIntProdWithTwoAcrossZero(int a_ref, int b_ref, int product_ref,
PresolveContext* context) {
// Split a_ref domain in two, controlled by a new literal.
const int a_is_positive = context->NewBoolVar();
context->AddImplyInDomain(a_is_positive, a_ref,
{0, std::numeric_limits<int64_t>::max()});
context->AddImplyInDomain(NegatedRef(a_is_positive), a_ref,
{std::numeric_limits<int64_t>::min(), -1});
const int64_t min_of_a = context->MinOf(a_ref);
const int64_t max_of_a = context->MaxOf(a_ref);
const int pos_a_ref = context->NewIntVar({0, max_of_a});
AddXEqualYOrXEqualZero(a_is_positive, pos_a_ref, a_ref, context);
const int neg_a_ref = context->NewIntVar({min_of_a, 0});
AddXEqualYOrXEqualZero(NegatedRef(a_is_positive), neg_a_ref, a_ref, context);
// Create product with two sub parts of a_ref.
const int pos_product_ref =
context->NewIntVar(context->DomainOf(product_ref));
ExpandIntProdWithOneAcrossZero(b_ref, pos_a_ref, pos_product_ref, context);
const int neg_product_ref =
context->NewIntVar(context->DomainOf(product_ref));
ExpandIntProdWithOneAcrossZero(b_ref, neg_a_ref, neg_product_ref, context);
// Link back to the original product.
LinearConstraintProto* lin =
context->working_model->add_constraints()->mutable_linear();
lin->add_vars(product_ref);
lin->add_coeffs(-1);
lin->add_vars(pos_product_ref);
lin->add_coeffs(1);
lin->add_vars(neg_product_ref);
lin->add_coeffs(1);
lin->add_domain(0);
lin->add_domain(0);
}
void ExpandIntProd(ConstraintProto* ct, PresolveContext* context) {
const IntegerArgumentProto& int_prod = ct->int_prod();
if (int_prod.vars_size() != 2) return;
const int a = int_prod.vars(0);
const int b = int_prod.vars(1);
const int p = int_prod.target();
const bool a_is_boolean =
RefIsPositive(a) && context->MinOf(a) == 0 && context->MaxOf(a) == 1;
const bool b_is_boolean =
RefIsPositive(b) && context->MinOf(b) == 0 && context->MaxOf(b) == 1;
// We expand if exactly one of {a, b} is Boolean. If both are Boolean, it
// will be presolved into a better version.
if (a_is_boolean && !b_is_boolean) {
ExpandIntProdWithBoolean(a, b, p, context);
ct->Clear();
context->UpdateRuleStats("int_prod: expanded product with Boolean var");
return;
}
if (b_is_boolean && !a_is_boolean) {
ExpandIntProdWithBoolean(b, a, p, context);
ct->Clear();
context->UpdateRuleStats("int_prod: expanded product with Boolean var");
return;
}
const bool a_span_across_zero =
context->MinOf(a) < 0 && context->MaxOf(a) > 0;
const bool b_span_across_zero =
context->MinOf(b) < 0 && context->MaxOf(b) > 0;
if (a_span_across_zero && !b_span_across_zero) {
ExpandIntProdWithOneAcrossZero(a, b, p, context);
ct->Clear();
context->UpdateRuleStats(
"int_prod: expanded product with general integer variables");
return;
}
if (!a_span_across_zero && b_span_across_zero) {
ExpandIntProdWithOneAcrossZero(b, a, p, context);
ct->Clear();
context->UpdateRuleStats(
"int_prod: expanded product with general integer variables");
return;
}
if (a_span_across_zero && b_span_across_zero) {
ExpandIntProdWithTwoAcrossZero(a, b, p, context);
ct->Clear();
context->UpdateRuleStats(
"int_prod: expanded product with general integer variables");
return;
}
}
void ExpandInverse(ConstraintProto* ct, PresolveContext* context) {
const int size = ct->inverse().f_direct().size();
CHECK_EQ(size, ct->inverse().f_inverse().size());
// Make sure the domains are included in [0, size - 1).
//
// TODO(user): Add support for UNSAT at expansion. This should create empty
// domain if UNSAT, so it should still work correctly.
for (const int ref : ct->inverse().f_direct()) {
if (!context->IntersectDomainWith(ref, Domain(0, size - 1))) {
VLOG(1) << "Empty domain for a variable in ExpandInverse()";
return;
}
}
for (const int ref : ct->inverse().f_inverse()) {
if (!context->IntersectDomainWith(ref, Domain(0, size - 1))) {
VLOG(1) << "Empty domain for a variable in ExpandInverse()";
return;
}
}
// Reduce the domains of each variable by checking that the inverse value
// exists.
std::vector<int64_t> possible_values;
// Propagate from one vector to its counterpart.
// Note this reaches the fixpoint as there is a one to one mapping between
// (variable-value) pairs in each vector.
const auto filter_inverse_domain = [context, size, &possible_values](
const auto& direct,
const auto& inverse) {
// Propagate for the inverse vector to the direct vector.
for (int i = 0; i < size; ++i) {
possible_values.clear();
const Domain domain = context->DomainOf(direct[i]);
bool removed_value = false;
for (const ClosedInterval& interval : domain) {
for (int64_t j = interval.start; j <= interval.end; ++j) {
if (context->DomainOf(inverse[j]).Contains(i)) {
possible_values.push_back(j);
} else {
removed_value = true;
}
}
}
if (removed_value) {
if (!context->IntersectDomainWith(
direct[i], Domain::FromValues(possible_values))) {
VLOG(1) << "Empty domain for a variable in ExpandInverse()";
return false;
}
}
}
return true;
};
if (!filter_inverse_domain(ct->inverse().f_direct(),
ct->inverse().f_inverse())) {
return;
}
if (!filter_inverse_domain(ct->inverse().f_inverse(),
ct->inverse().f_direct())) {
return;
}
// Expand the inverse constraint by associating literal to var == value
// and sharing them between the direct and inverse variables.
for (int i = 0; i < size; ++i) {
const int f_i = ct->inverse().f_direct(i);
const Domain domain = context->DomainOf(f_i);
for (const ClosedInterval& interval : domain) {
for (int64_t j = interval.start; j <= interval.end; ++j) {
// We have f[i] == j <=> r[j] == i;
const int r_j = ct->inverse().f_inverse(j);
int r_j_i;
if (context->HasVarValueEncoding(r_j, i, &r_j_i)) {
context->InsertVarValueEncoding(r_j_i, f_i, j);
} else {
const int f_i_j = context->GetOrCreateVarValueEncoding(f_i, j);
context->InsertVarValueEncoding(f_i_j, r_j, i);
}
}
}
}
ct->Clear();
context->UpdateRuleStats("inverse: expanded");
}
void ExpandElement(ConstraintProto* ct, PresolveContext* context) {
const ElementConstraintProto& element = ct->element();
const int index_ref = element.index();
const int target_ref = element.target();
const int size = element.vars_size();
if (!context->IntersectDomainWith(index_ref, Domain(0, size - 1))) {
VLOG(1) << "Empty domain for the index variable in ExpandElement()";
return (void)context->NotifyThatModelIsUnsat();
}
bool all_constants = true;
absl::flat_hash_map<int64_t, int> constant_var_values_usage;
std::vector<int64_t> constant_var_values;
std::vector<int64_t> invalid_indices;
Domain index_domain = context->DomainOf(index_ref);
Domain target_domain = context->DomainOf(target_ref);
for (const ClosedInterval& interval : index_domain) {
for (int64_t v = interval.start; v <= interval.end; ++v) {
const int var = element.vars(v);
const Domain var_domain = context->DomainOf(var);
if (var_domain.IntersectionWith(target_domain).IsEmpty()) {
invalid_indices.push_back(v);
continue;
}
if (var_domain.Min() != var_domain.Max()) {
all_constants = false;
break;
}
const int64_t value = var_domain.Min();
if (constant_var_values_usage[value]++ == 0) {
constant_var_values.push_back(value);
}
}
}
if (!invalid_indices.empty() && target_ref != index_ref) {
if (!context->IntersectDomainWith(
index_ref, Domain::FromValues(invalid_indices).Complement())) {
VLOG(1) << "No compatible variable domains in ExpandElement()";
return (void)context->NotifyThatModelIsUnsat();
}
// Re-read the domain.
index_domain = context->DomainOf(index_ref);
}
// This BoolOrs implements the deduction that if all index literals pointing
// to the same values in the constant array are false, then this value is no
// no longer valid for the target variable. They are created only for values
// that have multiples literals supporting them.
// Order is not important.
absl::flat_hash_map<int64_t, BoolArgumentProto*> supports;
if (all_constants && target_ref != index_ref) {
if (!context->IntersectDomainWith(
target_ref, Domain::FromValues(constant_var_values))) {
VLOG(1) << "Empty domain for the target variable in ExpandElement()";
return;
}
target_domain = context->DomainOf(target_ref);
if (target_domain.Size() == 1) {
context->UpdateRuleStats("element: one value array");
ct->Clear();
return;
}
for (const ClosedInterval& interval : target_domain) {
for (int64_t v = interval.start; v <= interval.end; ++v) {
const int usage = gtl::FindOrDie(constant_var_values_usage, v);
if (usage > 1) {
const int lit = context->GetOrCreateVarValueEncoding(target_ref, v);
BoolArgumentProto* const support =
context->working_model->add_constraints()->mutable_bool_or();
supports[v] = support;
support->add_literals(NegatedRef(lit));
}
}
}
}
// While this is not stricly needed since all value in the index will be
// covered, it allows to easily detect this fact in the presolve.
auto* bool_or = context->working_model->add_constraints()->mutable_bool_or();
for (const ClosedInterval& interval : index_domain) {
for (int64_t v = interval.start; v <= interval.end; ++v) {
const int var = element.vars(v);
const int index_lit = context->GetOrCreateVarValueEncoding(index_ref, v);
const Domain var_domain = context->DomainOf(var);
bool_or->add_literals(index_lit);
if (target_ref == index_ref) {
// This adds extra code. But this information is really important,
// and hard to retrieve once lost.
context->AddImplyInDomain(index_lit, var, Domain(v));
} else if (target_domain.Size() == 1) {
// TODO(user): If we know all variables are different, then this
// becomes an equivalence.
context->AddImplyInDomain(index_lit, var, target_domain);
} else if (var_domain.Size() == 1) {
if (all_constants) {
const int64_t value = var_domain.Min();
if (constant_var_values_usage[value] > 1) {
// The encoding literal for 'value' of the target_ref has been
// created before.
const int target_lit =
context->GetOrCreateVarValueEncoding(target_ref, value);
context->AddImplication(index_lit, target_lit);
gtl::FindOrDie(supports, value)->add_literals(index_lit);
} else {
// Try to reuse the literal of the index.
context->InsertVarValueEncoding(index_lit, target_ref, value);
}
} else {
context->AddImplyInDomain(index_lit, target_ref, var_domain);
}
} else {
ConstraintProto* const ct = context->working_model->add_constraints();
ct->add_enforcement_literal(index_lit);
ct->mutable_linear()->add_vars(var);
ct->mutable_linear()->add_coeffs(1);
ct->mutable_linear()->add_vars(target_ref);
ct->mutable_linear()->add_coeffs(-1);
ct->mutable_linear()->add_domain(0);
ct->mutable_linear()->add_domain(0);
}
}
}
if (all_constants) {
const int64_t var_min = target_domain.Min();
// Scan all values to find the one with the most literals attached.
int64_t most_frequent_value = std::numeric_limits<int64_t>::max();
int usage = -1;
for (const auto it : constant_var_values_usage) {
if (it.second > usage ||
(it.second == usage && it.first < most_frequent_value)) {
usage = it.second;
most_frequent_value = it.first;
}
}
// Add a linear constraint. This helps the linear relaxation.
//
// We try to minimize the size of the linear constraint (if the gain is
// meaningful compared to using the min that has the advantage that all
// coefficients are positive).
// TODO(user): Benchmark if using base is always beneficial.
// TODO(user): Try not to create this if max_usage == 1.
const int64_t base =
usage > 2 && usage > size / 10 ? most_frequent_value : var_min;
if (base != var_min) {
VLOG(3) << "expand element: choose " << base << " with usage " << usage
<< " over " << var_min << " among " << size << " values.";
}
LinearConstraintProto* const linear =
context->working_model->add_constraints()->mutable_linear();
int64_t rhs = -base;
linear->add_vars(target_ref);
linear->add_coeffs(-1);
for (const ClosedInterval& interval : index_domain) {
for (int64_t v = interval.start; v <= interval.end; ++v) {
const int ref = element.vars(v);
const int index_lit =
context->GetOrCreateVarValueEncoding(index_ref, v);
const int64_t delta = context->DomainOf(ref).Min() - base;
if (RefIsPositive(index_lit)) {
linear->add_vars(index_lit);
linear->add_coeffs(delta);
} else {
linear->add_vars(NegatedRef(index_lit));
linear->add_coeffs(-delta);
rhs -= delta;
}
}
}
linear->add_domain(rhs);
linear->add_domain(rhs);
context->UpdateRuleStats("element: expanded value element");
} else {
context->UpdateRuleStats("element: expanded");
}
ct->Clear();
}
// Adds clauses so that literals[i] true <=> encoding[value[i]] true.
// This also implicitly use the fact that exactly one alternative is true.
void LinkLiteralsAndValues(
const std::vector<int>& value_literals, const std::vector<int64_t>& values,
const absl::flat_hash_map<int64_t, int>& target_encoding,
PresolveContext* context) {
CHECK_EQ(value_literals.size(), values.size());
// TODO(user): Make sure this does not appear in the profile.
// We use a map to make this method deterministic.
std::map<int, std::vector<int>> value_literals_per_target_literal;
// If a value is false (i.e not possible), then the tuple with this
// value is false too (i.e not possible). Conversely, if the tuple is
// selected, the value must be selected.
for (int i = 0; i < values.size(); ++i) {
const int64_t v = values[i];
CHECK(target_encoding.contains(v));
const int lit = gtl::FindOrDie(target_encoding, v);
value_literals_per_target_literal[lit].push_back(value_literals[i]);
}
// If all tuples supporting a value are false, then this value must be
// false.
for (const auto& it : value_literals_per_target_literal) {
const int target_literal = it.first;
switch (it.second.size()) {
case 0: {
if (!context->SetLiteralToFalse(target_literal)) {
return;
}
break;
}
case 1: {
context->StoreBooleanEqualityRelation(target_literal,
it.second.front());
break;
}
default: {
BoolArgumentProto* const bool_or =
context->working_model->add_constraints()->mutable_bool_or();
bool_or->add_literals(NegatedRef(target_literal));
for (const int value_literal : it.second) {
bool_or->add_literals(value_literal);
context->AddImplication(value_literal, target_literal);
}
}
}
}
}
void ExpandAutomaton(ConstraintProto* ct, PresolveContext* context) {
AutomatonConstraintProto& proto = *ct->mutable_automaton();
if (proto.vars_size() == 0) {
const int64_t initial_state = proto.starting_state();
for (const int64_t final_state : proto.final_states()) {
if (initial_state == final_state) {
context->UpdateRuleStats("automaton: empty constraint");
ct->Clear();
return;
}
}
// The initial state is not in the final state. The model is unsat.
return (void)context->NotifyThatModelIsUnsat();
} else if (proto.transition_label_size() == 0) {
// Not transitions. The constraint is infeasible.
return (void)context->NotifyThatModelIsUnsat();
}
const int n = proto.vars_size();
const std::vector<int> vars = {proto.vars().begin(), proto.vars().end()};
// Compute the set of reachable state at each time point.
const absl::flat_hash_set<int64_t> final_states(
{proto.final_states().begin(), proto.final_states().end()});
std::vector<absl::flat_hash_set<int64_t>> reachable_states(n + 1);
reachable_states[0].insert(proto.starting_state());
// Forward pass.
for (int time = 0; time < n; ++time) {
for (int t = 0; t < proto.transition_tail_size(); ++t) {
const int64_t tail = proto.transition_tail(t);
const int64_t label = proto.transition_label(t);
const int64_t head = proto.transition_head(t);
if (!reachable_states[time].contains(tail)) continue;
if (!context->DomainContains(vars[time], label)) continue;
if (time == n - 1 && !final_states.contains(head)) continue;
reachable_states[time + 1].insert(head);
}
}
// Backward pass.
for (int time = n - 1; time >= 0; --time) {
absl::flat_hash_set<int64_t> new_set;
for (int t = 0; t < proto.transition_tail_size(); ++t) {
const int64_t tail = proto.transition_tail(t);
const int64_t label = proto.transition_label(t);
const int64_t head = proto.transition_head(t);
if (!reachable_states[time].contains(tail)) continue;
if (!context->DomainContains(vars[time], label)) continue;
if (!reachable_states[time + 1].contains(head)) continue;
new_set.insert(tail);
}
reachable_states[time].swap(new_set);
}
// We will model at each time step the current automaton state using Boolean
// variables. We will have n+1 time step. At time zero, we start in the
// initial state, and at time n we should be in one of the final states. We
// don't need to create Booleans at at time when there is just one possible
// state (like at time zero).
absl::flat_hash_map<int64_t, int> encoding;
absl::flat_hash_map<int64_t, int> in_encoding;
absl::flat_hash_map<int64_t, int> out_encoding;
bool removed_values = false;
for (int time = 0; time < n; ++time) {
// All these vector have the same size. We will use them to enforce a
// local table constraint representing one step of the automaton at the
// given time.
std::vector<int64_t> in_states;
std::vector<int64_t> transition_values;
std::vector<int64_t> out_states;
for (int i = 0; i < proto.transition_label_size(); ++i) {
const int64_t tail = proto.transition_tail(i);
const int64_t label = proto.transition_label(i);
const int64_t head = proto.transition_head(i);
if (!reachable_states[time].contains(tail)) continue;
if (!reachable_states[time + 1].contains(head)) continue;
if (!context->DomainContains(vars[time], label)) continue;
// TODO(user): if this transition correspond to just one in-state or
// one-out state or one variable value, we could reuse the corresponding
// Boolean variable instead of creating a new one!
in_states.push_back(tail);
transition_values.push_back(label);
// On the last step we don't need to distinguish the output states, so
// we use zero.
out_states.push_back(time + 1 == n ? 0 : head);
}
std::vector<int> tuple_literals;
if (transition_values.size() == 1) {
bool tmp_removed_values = false;
tuple_literals.push_back(context->GetOrCreateConstantVar(1));
CHECK_EQ(reachable_states[time + 1].size(), 1);
if (!context->IntersectDomainWith(vars[time],
Domain(transition_values.front()),
&tmp_removed_values)) {
return (void)context->NotifyThatModelIsUnsat();
}
in_encoding.clear();
continue;
} else if (transition_values.size() == 2) {
const int bool_var = context->NewBoolVar();
tuple_literals.push_back(bool_var);
tuple_literals.push_back(NegatedRef(bool_var));
} else {
// Note that we do not need the ExactlyOneConstraint(tuple_literals)
// because it is already implicitly encoded since we have exactly one
// transition value.
LinearConstraintProto* const exactly_one =
context->working_model->add_constraints()->mutable_linear();
exactly_one->add_domain(1);
exactly_one->add_domain(1);
for (int i = 0; i < transition_values.size(); ++i) {
const int tuple_literal = context->NewBoolVar();
tuple_literals.push_back(tuple_literal);
exactly_one->add_vars(tuple_literal);
exactly_one->add_coeffs(1);
}
}
// Fully encode vars[time].
{
std::vector<int64_t> s = transition_values;
gtl::STLSortAndRemoveDuplicates(&s);
encoding.clear();
if (!context->IntersectDomainWith(vars[time], Domain::FromValues(s),
&removed_values)) {
return (void)context->NotifyThatModelIsUnsat();
}
// Fully encode the variable.
for (const ClosedInterval& interval : context->DomainOf(vars[time])) {
for (int64_t v = interval.start; v <= interval.end; ++v) {
encoding[v] = context->GetOrCreateVarValueEncoding(vars[time], v);
}
}
}
// For each possible out states, create one Boolean variable.
{
std::vector<int64_t> s = out_states;
gtl::STLSortAndRemoveDuplicates(&s);
out_encoding.clear();
if (s.size() == 2) {
const int var = context->NewBoolVar();
out_encoding[s.front()] = var;
out_encoding[s.back()] = NegatedRef(var);
} else if (s.size() > 2) {
for (const int64_t state : s) {
out_encoding[state] = context->NewBoolVar();
}
}
}
if (!in_encoding.empty()) {
LinkLiteralsAndValues(tuple_literals, in_states, in_encoding, context);
}
if (!encoding.empty()) {
LinkLiteralsAndValues(tuple_literals, transition_values, encoding,
context);
}
if (!out_encoding.empty()) {
LinkLiteralsAndValues(tuple_literals, out_states, out_encoding, context);
}
in_encoding.swap(out_encoding);
out_encoding.clear();
}
if (removed_values) {
context->UpdateRuleStats("automaton: reduced variable domains");
}
context->UpdateRuleStats("automaton: expanded");
ct->Clear();
}
void ExpandNegativeTable(ConstraintProto* ct, PresolveContext* context) {
TableConstraintProto& table = *ct->mutable_table();
const int num_vars = table.vars_size();
const int num_original_tuples = table.values_size() / num_vars;
std::vector<std::vector<int64_t>> tuples(num_original_tuples);
int count = 0;
for (int i = 0; i < num_original_tuples; ++i) {
for (int j = 0; j < num_vars; ++j) {
tuples[i].push_back(table.values(count++));
}
}
if (tuples.empty()) { // Early exit.
context->UpdateRuleStats("table: empty negated constraint");
ct->Clear();
return;
}
// Compress tuples.
const int64_t any_value = std::numeric_limits<int64_t>::min();
std::vector<int64_t> domain_sizes;
for (int i = 0; i < num_vars; ++i) {
domain_sizes.push_back(context->DomainOf(table.vars(i)).Size());
}
CompressTuples(domain_sizes, any_value, &tuples);
// For each tuple, forbid the variables values to be this tuple.
std::vector<int> clause;
for (const std::vector<int64_t>& tuple : tuples) {
clause.clear();
for (int i = 0; i < num_vars; ++i) {
const int64_t value = tuple[i];
if (value == any_value) continue;
const int literal =
context->GetOrCreateVarValueEncoding(table.vars(i), value);
clause.push_back(NegatedRef(literal));
}
if (!clause.empty()) {
BoolArgumentProto* bool_or =
context->working_model->add_constraints()->mutable_bool_or();
for (const int lit : clause) {
bool_or->add_literals(lit);
}
}
}
context->UpdateRuleStats("table: expanded negated constraint");
ct->Clear();
}
void ExpandLinMin(ConstraintProto* ct, PresolveContext* context) {
ConstraintProto* const lin_max = context->working_model->add_constraints();
for (int i = 0; i < ct->enforcement_literal_size(); ++i) {
lin_max->add_enforcement_literal(ct->enforcement_literal(i));
}
// Target
SetToNegatedLinearExpression(ct->lin_min().target(),
lin_max->mutable_lin_max()->mutable_target());
for (int i = 0; i < ct->lin_min().exprs_size(); ++i) {
LinearExpressionProto* const expr = lin_max->mutable_lin_max()->add_exprs();
SetToNegatedLinearExpression(ct->lin_min().exprs(i), expr);
}
ct->Clear();
}
// Add the implications and clauses to link one variable of a table to the
// literals controling if the tuples are possible or not. The parallel vectors
// (tuple_literals, values) contains all valid projected tuples. The
// tuples_with_any vector provides a list of tuple_literals that will support
// any value.
void ProcessOneVariable(const std::vector<int>& tuple_literals,
const std::vector<int64_t>& values, int variable,
const std::vector<int>& tuples_with_any,
PresolveContext* context) {
VLOG(2) << "Process var(" << variable << ") with domain "
<< context->DomainOf(variable) << " and " << values.size()
<< " active tuples, and " << tuples_with_any.size() << " any tuples";
CHECK_EQ(tuple_literals.size(), values.size());
std::vector<std::pair<int64_t, int>> pairs;
// Collect pairs of value-literal.
for (int i = 0; i < values.size(); ++i) {
const int64_t value = values[i];
CHECK(context->DomainContains(variable, value));
pairs.emplace_back(value, tuple_literals[i]);