Repository navigation
Expand file tree
/
Copy pathtable.cc
More file actions
1156 lines (1065 loc) · 39.6 KB
/
Copy pathtable.cc
File metadata and controls
1156 lines (1065 loc) · 39.6 KB
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-2025 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.
// This file implements the table constraints.
#include "ortools/constraint_solver/table.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/types/span.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/variables.h"
#include "ortools/util/bitset.h"
#include "ortools/util/string_array.h"
#include "ortools/util/tuple_set.h"
namespace operations_research {
bool HasCompactDomains(const std::vector<IntVar*>& vars) {
return true; // Always assume compact table.
}
// ----- Presolve helpers -----
AffineTransformation::AffineTransformation() : a(1), b(0) {}
AffineTransformation::AffineTransformation(int64_t aa, int64_t bb)
: a(aa), b(bb) {
CHECK_NE(a, 0);
}
bool AffineTransformation::Reverse(int64_t value, int64_t* reverse) const {
const int64_t temp = value - b;
if (temp % a == 0) {
*reverse = temp / a;
DCHECK_EQ(Forward(*reverse), value);
return true;
} else {
return false;
}
}
int64_t AffineTransformation::Forward(int64_t value) const {
return value * a + b;
}
int64_t AffineTransformation::UnsafeReverse(int64_t value) const {
return (value - b) / a;
}
void AffineTransformation::Clear() {
a = 1;
b = 0;
}
std::string AffineTransformation::DebugString() const {
return absl::StrFormat("(%d * x + %d)", a, b);
}
VarLinearizer::VarLinearizer()
: target_var_(nullptr), transformation_(nullptr) {}
VarLinearizer::~VarLinearizer() {}
void VarLinearizer::VisitIntegerVariable(const IntVar* variable,
const std::string& operation,
int64_t value, IntVar* delegate) {
if (operation == ModelVisitor::kSumOperation) {
AddConstant(value);
delegate->Accept(this);
} else if (operation == ModelVisitor::kDifferenceOperation) {
AddConstant(value);
PushMultiplier(-1);
delegate->Accept(this);
PopMultiplier();
} else if (operation == ModelVisitor::kProductOperation) {
PushMultiplier(value);
delegate->Accept(this);
PopMultiplier();
} else if (operation == ModelVisitor::kTraceOperation) {
*target_var_ = const_cast<IntVar*>(variable);
transformation_->a = multipliers_.back();
}
}
void VarLinearizer::VisitIntegerVariable(const IntVar* variable,
IntExpr* delegate) {
*target_var_ = const_cast<IntVar*>(variable);
transformation_->a = multipliers_.back();
}
void VarLinearizer::Visit(const IntVar* var, IntVar** target_var,
AffineTransformation* transformation) {
target_var_ = target_var;
transformation_ = transformation;
transformation->Clear();
PushMultiplier(1);
var->Accept(this);
PopMultiplier();
CHECK(multipliers_.empty());
}
std::string VarLinearizer::DebugString() const { return "VarLinearizer"; }
void VarLinearizer::AddConstant(int64_t constant) {
transformation_->b += constant * multipliers_.back();
}
void VarLinearizer::PushMultiplier(int64_t multiplier) {
if (multipliers_.empty()) {
multipliers_.push_back(multiplier);
} else {
multipliers_.push_back(multiplier * multipliers_.back());
}
}
void VarLinearizer::PopMultiplier() { multipliers_.pop_back(); }
// ----- Positive Table Constraint -----
BasePositiveTableConstraint::BasePositiveTableConstraint(
Solver* s, const std::vector<IntVar*>& vars, const IntTupleSet& tuples)
: Constraint(s),
tuple_count_(tuples.NumTuples()),
arity_(vars.size()),
vars_(arity_),
holes_(arity_),
iterators_(arity_),
tuples_(tuples),
transformations_(arity_) {
// This constraint is intensive on domain and holes iterations on
// variables. Thus we can visit all variables to get to the
// boolean or domain int var beneath it. Then we can reverse
// process the tupleset to move in parallel to the simplifications
// of the variables. This way, we can keep the memory efficient
// nature of shared tuplesets (especially important for
// transitions constraints which are a chain of table
// constraints). The cost in running time is small as the tuples
// are read only once to construct the bitset data structures.
VarLinearizer linearizer;
for (int i = 0; i < arity_; ++i) {
linearizer.Visit(vars[i], &vars_[i], &transformations_[i]);
}
// Create hole iterators
for (int i = 0; i < arity_; ++i) {
holes_[i] = vars_[i]->MakeHoleIterator(true);
iterators_[i] = vars_[i]->MakeDomainIterator(true);
}
}
BasePositiveTableConstraint::~BasePositiveTableConstraint() {}
std::string BasePositiveTableConstraint::DebugString() const {
return absl::StrFormat("AllowedAssignments(arity = %d, tuple_count = %d)",
arity_, tuple_count_);
}
void BasePositiveTableConstraint::Accept(ModelVisitor* visitor) const {
visitor->BeginVisitConstraint(ModelVisitor::kAllowedAssignments, this);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
vars_);
visitor->VisitIntegerMatrixArgument(ModelVisitor::kTuplesArgument, tuples_);
visitor->EndVisitConstraint(ModelVisitor::kAllowedAssignments, this);
}
bool BasePositiveTableConstraint::TupleValue(int tuple_index, int var_index,
int64_t* value) const {
return transformations_[var_index].Reverse(
tuples_.Value(tuple_index, var_index), value);
}
int64_t BasePositiveTableConstraint::UnsafeTupleValue(int tuple_index,
int var_index) const {
return transformations_[var_index].UnsafeReverse(
tuples_.Value(tuple_index, var_index));
}
bool BasePositiveTableConstraint::IsTupleSupported(int tuple_index) {
for (int var_index = 0; var_index < arity_; ++var_index) {
int64_t value = 0;
if (!TupleValue(tuple_index, var_index, &value) ||
!vars_[var_index]->Contains(value)) {
return false;
}
}
return true;
}
PositiveTableConstraint::PositiveTableConstraint(
Solver* s, const std::vector<IntVar*>& vars, const IntTupleSet& tuples)
: BasePositiveTableConstraint(s, vars, tuples),
word_length_(BitLength64(tuples.NumTuples())),
active_tuples_(tuples.NumTuples()) {}
PositiveTableConstraint::~PositiveTableConstraint() {}
void PositiveTableConstraint::Post() {
Demon* d = MakeDelayedConstraintDemon0(
solver(), this, &PositiveTableConstraint::Propagate, "Propagate");
for (int i = 0; i < arity_; ++i) {
vars_[i]->WhenDomain(d);
Demon* u = MakeConstraintDemon1(
solver(), this, &PositiveTableConstraint::Update, "Update", i);
vars_[i]->WhenDomain(u);
}
masks_.clear();
masks_.resize(arity_);
for (int i = 0; i < tuple_count_; ++i) {
InitializeMask(i);
}
std::vector<uint64_t> actives(word_length_, 0);
for (int tuple_index = 0; tuple_index < tuple_count_; ++tuple_index) {
if (IsTupleSupported(tuple_index)) {
SetBit64(actives.data(), tuple_index);
}
}
active_tuples_.Init(solver(), actives);
}
void PositiveTableConstraint::InitialPropagate() {
// Build active_ structure.
for (int var_index = 0; var_index < arity_; ++var_index) {
for (const auto& it : masks_[var_index]) {
if (!vars_[var_index]->Contains(it.first)) {
active_tuples_.RevSubtract(solver(), it.second);
}
}
}
if (active_tuples_.Empty()) {
solver()->Fail();
}
// Remove unreached values.
for (int var_index = 0; var_index < arity_; ++var_index) {
const ValueBitset& mask = masks_[var_index];
IntVar* const var = vars_[var_index];
to_remove_.clear();
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
if (!mask.contains(value)) {
to_remove_.push_back(value);
}
}
if (!to_remove_.empty()) {
var->RemoveValues(to_remove_);
}
}
}
void PositiveTableConstraint::Propagate() {
for (int var_index = 0; var_index < arity_; ++var_index) {
IntVar* const var = vars_[var_index];
to_remove_.clear();
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
if (!Supported(var_index, value)) {
to_remove_.push_back(value);
}
}
if (!to_remove_.empty()) {
var->RemoveValues(to_remove_);
}
}
}
void PositiveTableConstraint::Update(int var_index) {
IntVar* const var = vars_[var_index];
const int64_t old_max = var->OldMax();
const int64_t vmin = var->Min();
const int64_t vmax = var->Max();
const ValueBitset& var_masks = masks_[var_index];
for (int64_t value = var->OldMin(); value < vmin; ++value) {
const auto& it = var_masks.find(value);
if (it != var_masks.end()) {
BlankActives(it->second);
}
}
for (const int64_t value : InitAndGetValues(holes_[var_index])) {
const auto& it = var_masks.find(value);
if (it != var_masks.end()) {
BlankActives(it->second);
}
}
for (int64_t value = vmax + 1; value <= old_max; ++value) {
const auto& it = var_masks.find(value);
if (it != var_masks.end()) {
BlankActives(it->second);
}
}
}
void PositiveTableConstraint::BlankActives(const std::vector<uint64_t>& mask) {
if (!mask.empty()) {
active_tuples_.RevSubtract(solver(), mask);
if (active_tuples_.Empty()) {
solver()->Fail();
}
}
}
bool PositiveTableConstraint::Supported(int var_index, int64_t value) {
DCHECK_GE(var_index, 0);
DCHECK_LT(var_index, arity_);
DCHECK(masks_[var_index].contains(value));
const std::vector<uint64_t>& mask = masks_[var_index][value];
int tmp = 0;
return active_tuples_.Intersects(mask, &tmp);
}
std::string PositiveTableConstraint::DebugString() const {
return absl::StrFormat("PositiveTableConstraint([%s], %d tuples)",
JoinDebugStringPtr(vars_), tuple_count_);
}
void PositiveTableConstraint::InitializeMask(int tuple_index) {
std::vector<int64_t> cache(arity_);
for (int var_index = 0; var_index < arity_; ++var_index) {
if (!TupleValue(tuple_index, var_index, &cache[var_index])) {
return;
}
}
for (int var_index = 0; var_index < arity_; ++var_index) {
const int64_t value = cache[var_index];
std::vector<uint64_t>& mask = masks_[var_index][value];
if (mask.empty()) {
mask.assign(word_length_, 0);
}
SetBit64(mask.data(), tuple_index);
}
}
CompactPositiveTableConstraint::CompactPositiveTableConstraint(
Solver* s, const std::vector<IntVar*>& vars, const IntTupleSet& tuples)
: BasePositiveTableConstraint(s, vars, tuples),
word_length_(BitLength64(tuples.NumTuples())),
active_tuples_(tuples.NumTuples()),
masks_(arity_),
mask_starts_(arity_),
mask_ends_(arity_),
original_min_(arity_, 0),
temp_mask_(word_length_, 0),
supports_(arity_),
demon_(nullptr),
touched_var_(-1),
var_sizes_(arity_, 0) {}
CompactPositiveTableConstraint::~CompactPositiveTableConstraint() {}
void CompactPositiveTableConstraint::Post() {
demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &CompactPositiveTableConstraint::Propagate, "Propagate"));
for (int i = 0; i < arity_; ++i) {
Demon* const u = MakeConstraintDemon1(
solver(), this, &CompactPositiveTableConstraint::Update, "Update", i);
vars_[i]->WhenDomain(u);
}
for (int i = 0; i < arity_; ++i) {
var_sizes_.SetValue(solver(), i, vars_[i]->Size());
}
}
void CompactPositiveTableConstraint::InitialPropagate() {
BuildMasks();
FillMasksAndActiveTuples();
ComputeMasksBoundaries();
BuildSupports();
RemoveUnsupportedValues();
}
void CompactPositiveTableConstraint::Propagate() {
// Reset touch_var_ if in mode (more than 1 variable was modified).
if (touched_var_ == -2) {
touched_var_ = -1;
}
// This methods scans all values of all variables to see if they
// are still supported.
// This method is not attached to any particular variable, but is pushed
// at a delayed priority after Update(var_index) is called.
for (int var_index = 0; var_index < arity_; ++var_index) {
// This demons runs in low priority. Thus we know all the
// variables that have changed since the last time it was run.
// In that case, if only one var was touched, as propagation is
// exact, we do not need to recheck that variable.
if (var_index == touched_var_) {
touched_var_ = -1; // Clean now, it is a 1 time flag.
continue;
}
IntVar* const var = vars_[var_index];
const int64_t original_min = original_min_[var_index];
const int64_t var_size = var->Size();
// The domain iterator is very slow, let's try to see if we can
// work our way around.
switch (var_size) {
case 1: {
if (!Supported(var_index, var->Min() - original_min)) {
solver()->Fail();
}
break;
}
case 2: {
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
const bool min_support = Supported(var_index, var_min - original_min);
const bool max_support = Supported(var_index, var_max - original_min);
if (!min_support) {
if (!max_support) {
solver()->Fail();
} else {
var->SetValue(var_max);
var_sizes_.SetValue(solver(), var_index, 1);
}
} else if (!max_support) {
var->SetValue(var_min);
var_sizes_.SetValue(solver(), var_index, 1);
}
break;
}
default: {
to_remove_.clear();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
int64_t new_min = var_min;
int64_t new_max = var_max;
// If the domain of a variable is an interval, it is much
// faster to iterate on that interval instead of using the
// iterator.
if (var_max - var_min + 1 == var_size) {
for (; new_min <= var_max; ++new_min) {
if (Supported(var_index, new_min - original_min)) {
break;
}
}
for (; new_max >= new_min; --new_max) {
if (Supported(var_index, new_max - original_min)) {
break;
}
}
var->SetRange(new_min, new_max);
for (int64_t value = new_min + 1; value < new_max; ++value) {
if (!Supported(var_index, value - original_min)) {
to_remove_.push_back(value);
}
}
} else { // Domain is sparse.
// Let's not collect all values below the first supported
// value as this can easily and more rapidly be taken care
// of by a SetRange() call.
new_min = kint64max; // escape value.
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
if (!Supported(var_index, value - original_min)) {
to_remove_.push_back(value);
} else {
if (new_min == kint64max) {
new_min = value;
// This will be covered by the SetRange.
to_remove_.clear();
}
new_max = value;
}
}
var->SetRange(new_min, new_max);
// Trim the to_remove vector.
int index = to_remove_.size() - 1;
while (index >= 0 && to_remove_[index] > new_max) {
index--;
}
to_remove_.resize(index + 1);
}
var->RemoveValues(to_remove_);
var_sizes_.SetValue(solver(), var_index, var->Size());
}
}
}
}
void CompactPositiveTableConstraint::Update(int var_index) {
if (vars_[var_index]->Size() == var_sizes_.Value(var_index)) {
return;
}
// This method will update the set of active tuples by masking out all
// tuples attached to values of the variables that have been removed.
// We first collect the complete set of tuples to blank out in temp_mask_.
IntVar* const var = vars_[var_index];
bool changed = false;
const int64_t omin = original_min_[var_index];
const int64_t var_size = var->Size();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
switch (var_size) {
case 1: {
changed = AndMaskWithActive(masks_[var_index][var_min - omin]);
break;
}
case 2: {
SetTempMask(var_index, var_min - omin);
OrTempMask(var_index, var_max - omin);
changed = AndMaskWithActive(temp_mask_);
break;
}
default: {
const int64_t estimated_hole_size =
var_sizes_.Value(var_index) - var_size;
const int64_t old_min = var->OldMin();
const int64_t old_max = var->OldMax();
// Rough estimation of the number of operation if we scan
// deltas in the domain of the variable.
const int64_t number_of_operations =
estimated_hole_size + var_min - old_min + old_max - var_max;
if (number_of_operations < var_size) {
// Let's scan the removed values since last run.
for (int64_t value = old_min; value < var_min; ++value) {
changed |= SubtractMaskFromActive(masks_[var_index][value - omin]);
}
for (const int64_t value : InitAndGetValues(holes_[var_index])) {
changed |= SubtractMaskFromActive(masks_[var_index][value - omin]);
}
for (int64_t value = var_max + 1; value <= old_max; ++value) {
changed |= SubtractMaskFromActive(masks_[var_index][value - omin]);
}
} else {
ClearTempMask();
// Let's build the mask of supported tuples from the current
// domain.
if (var_max - var_min + 1 == var_size) { // Contiguous.
for (int64_t value = var_min; value <= var_max; ++value) {
OrTempMask(var_index, value - omin);
}
} else {
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
OrTempMask(var_index, value - omin);
}
}
// Then we and this mask with active_tuples_.
changed = AndMaskWithActive(temp_mask_);
}
// We maintain the size of the variables incrementally (when it
// is > 2).
var_sizes_.SetValue(solver(), var_index, var_size);
}
}
// We push the propagate method only if something has changed.
if (changed) {
if (touched_var_ == -1 || touched_var_ == var_index) {
touched_var_ = var_index;
} else {
touched_var_ = -2; // more than one var.
}
EnqueueDelayedDemon(demon_);
}
}
std::string CompactPositiveTableConstraint::DebugString() const {
return absl::StrFormat("CompactPositiveTableConstraint([%s], %d tuples)",
JoinDebugStringPtr(vars_), tuple_count_);
}
void CompactPositiveTableConstraint::BuildMasks() {
// Build masks.
for (int i = 0; i < arity_; ++i) {
original_min_[i] = vars_[i]->Min();
const int64_t span = vars_[i]->Max() - original_min_[i] + 1;
masks_[i].resize(span);
}
}
void CompactPositiveTableConstraint::FillMasksAndActiveTuples() {
std::vector<uint64_t> actives(word_length_, 0);
for (int tuple_index = 0; tuple_index < tuple_count_; ++tuple_index) {
if (IsTupleSupported(tuple_index)) {
SetBit64(actives.data(), tuple_index);
// Fill in all masks.
for (int var_index = 0; var_index < arity_; ++var_index) {
const int64_t value = UnsafeTupleValue(tuple_index, var_index);
const int64_t value_index = value - original_min_[var_index];
DCHECK_GE(value_index, 0);
DCHECK_LT(value_index, masks_[var_index].size());
if (masks_[var_index][value_index].empty()) {
masks_[var_index][value_index].assign(word_length_, 0);
}
SetBit64(masks_[var_index][value_index].data(), tuple_index);
}
}
}
active_tuples_.Init(solver(), actives);
}
void CompactPositiveTableConstraint::RemoveUnsupportedValues() {
// remove unreached values.
for (int var_index = 0; var_index < arity_; ++var_index) {
IntVar* const var = vars_[var_index];
to_remove_.clear();
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
if (masks_[var_index][value - original_min_[var_index]].empty()) {
to_remove_.push_back(value);
}
}
if (!to_remove_.empty()) {
var->RemoveValues(to_remove_);
}
}
}
void CompactPositiveTableConstraint::ComputeMasksBoundaries() {
for (int var_index = 0; var_index < arity_; ++var_index) {
mask_starts_[var_index].resize(masks_[var_index].size());
mask_ends_[var_index].resize(masks_[var_index].size());
for (int value_index = 0; value_index < masks_[var_index].size();
++value_index) {
const std::vector<uint64_t>& mask = masks_[var_index][value_index];
if (mask.empty()) {
continue;
}
int start = 0;
while (start < word_length_ && mask[start] == 0) {
start++;
}
DCHECK_LT(start, word_length_);
int end = word_length_ - 1;
while (end > start && mask[end] == 0) {
end--;
}
DCHECK_LE(start, end);
DCHECK_NE(mask[start], 0);
DCHECK_NE(mask[end], 0);
mask_starts_[var_index][value_index] = start;
mask_ends_[var_index][value_index] = end;
}
}
}
void CompactPositiveTableConstraint::BuildSupports() {
for (int var_index = 0; var_index < arity_; ++var_index) {
supports_[var_index].resize(masks_[var_index].size());
}
}
bool CompactPositiveTableConstraint::AndMaskWithActive(
const std::vector<uint64_t>& mask) {
const bool result = active_tuples_.RevAnd(solver(), mask);
if (active_tuples_.Empty()) {
solver()->Fail();
}
return result;
}
bool CompactPositiveTableConstraint::SubtractMaskFromActive(
const std::vector<uint64_t>& mask) {
const bool result = active_tuples_.RevSubtract(solver(), mask);
if (active_tuples_.Empty()) {
solver()->Fail();
}
return result;
}
bool CompactPositiveTableConstraint::Supported(int var_index,
int64_t value_index) {
DCHECK_GE(var_index, 0);
DCHECK_LT(var_index, arity_);
DCHECK_GE(value_index, 0);
DCHECK_LT(value_index, masks_[var_index].size());
const std::vector<uint64_t>& mask = masks_[var_index][value_index];
DCHECK(!mask.empty());
return active_tuples_.Intersects(mask, &supports_[var_index][value_index]);
}
void CompactPositiveTableConstraint::OrTempMask(int var_index,
int64_t value_index) {
const std::vector<uint64_t>& mask = masks_[var_index][value_index];
if (!mask.empty()) {
const int mask_span = mask_ends_[var_index][value_index] -
mask_starts_[var_index][value_index] + 1;
if (active_tuples_.ActiveWordSize() < mask_span) {
for (int i : active_tuples_.active_words()) {
temp_mask_[i] |= mask[i];
}
} else {
for (int i = mask_starts_[var_index][value_index];
i <= mask_ends_[var_index][value_index]; ++i) {
temp_mask_[i] |= mask[i];
}
}
}
}
void CompactPositiveTableConstraint::SetTempMask(int var_index,
int64_t value_index) {
// We assume memset is much faster that looping and assigning.
// Still we do want to stay sparse if possible.
// Thus we switch between dense and sparse initialization by
// comparing the number of operations in both case, with constant factor.
// TODO(user): experiment with different constant values.
if (active_tuples_.ActiveWordSize() < word_length_ / 4) {
for (int i : active_tuples_.active_words()) {
temp_mask_[i] = masks_[var_index][value_index][i];
}
} else {
temp_mask_ = masks_[var_index][value_index];
}
}
void CompactPositiveTableConstraint::ClearTempMask() {
// See comment above.
if (active_tuples_.ActiveWordSize() < word_length_ / 4) {
for (int i : active_tuples_.active_words()) {
temp_mask_[i] = 0;
}
} else {
temp_mask_.assign(word_length_, 0);
}
}
SmallCompactPositiveTableConstraint::SmallCompactPositiveTableConstraint(
Solver* s, const std::vector<IntVar*>& vars, const IntTupleSet& tuples)
: BasePositiveTableConstraint(s, vars, tuples),
active_tuples_(0),
stamp_(0),
masks_(arity_),
original_min_(arity_, 0),
demon_(nullptr),
touched_var_(-1) {
CHECK_GE(tuple_count_, 0);
CHECK_GE(arity_, 0);
CHECK_LE(tuples.NumTuples(), kBitsInUint64);
}
SmallCompactPositiveTableConstraint::~SmallCompactPositiveTableConstraint() {}
void SmallCompactPositiveTableConstraint::Post() {
demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &SmallCompactPositiveTableConstraint::Propagate,
"Propagate"));
for (int i = 0; i < arity_; ++i) {
if (!vars_[i]->Bound()) {
Demon* const update_demon = MakeConstraintDemon1(
solver(), this, &SmallCompactPositiveTableConstraint::Update,
"Update", i);
vars_[i]->WhenDomain(update_demon);
}
}
stamp_ = 0;
}
void SmallCompactPositiveTableConstraint::InitMasks() {
// Build masks.
for (int i = 0; i < arity_; ++i) {
original_min_[i] = vars_[i]->Min();
const int64_t span = vars_[i]->Max() - original_min_[i] + 1;
masks_[i].assign(span, 0);
}
}
bool SmallCompactPositiveTableConstraint::IsTupleSupported(int tuple_index) {
for (int var_index = 0; var_index < arity_; ++var_index) {
int64_t value = 0;
if (!TupleValue(tuple_index, var_index, &value) ||
!vars_[var_index]->Contains(value)) {
return false;
}
}
return true;
}
void SmallCompactPositiveTableConstraint::ComputeActiveTuples() {
active_tuples_ = 0;
// Compute active_tuples_ and update masks.
for (int tuple_index = 0; tuple_index < tuple_count_; ++tuple_index) {
if (IsTupleSupported(tuple_index)) {
const uint64_t local_mask = OneBit64(tuple_index);
active_tuples_ |= local_mask;
for (int var_index = 0; var_index < arity_; ++var_index) {
const int64_t value = UnsafeTupleValue(tuple_index, var_index);
masks_[var_index][value - original_min_[var_index]] |= local_mask;
}
}
}
if (!active_tuples_) {
solver()->Fail();
}
}
void SmallCompactPositiveTableConstraint::RemoveUnsupportedValues() {
// remove unreached values.
for (int var_index = 0; var_index < arity_; ++var_index) {
IntVar* const var = vars_[var_index];
const int64_t original_min = original_min_[var_index];
to_remove_.clear();
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
if (masks_[var_index][value - original_min] == 0) {
to_remove_.push_back(value);
}
}
if (!to_remove_.empty()) {
var->RemoveValues(to_remove_);
}
}
}
void SmallCompactPositiveTableConstraint::InitialPropagate() {
InitMasks();
ComputeActiveTuples();
RemoveUnsupportedValues();
}
void SmallCompactPositiveTableConstraint::Propagate() {
// This methods scans all the values of all the variables to see if they
// are still supported.
// This method is not attached to any particular variable, but is pushed
// at a delayed priority and awakened by Update(var_index).
// Reset touch_var_ if in mode (more than 1 variable was modified).
if (touched_var_ == -2) {
touched_var_ = -1;
}
// We cache active_tuples_.
const uint64_t actives = active_tuples_;
// We scan all variables and check their domains.
for (int var_index = 0; var_index < arity_; ++var_index) {
// This demons runs in low priority. Thus we know all the
// variables that have changed since the last time it was run.
// In that case, if only one var was touched, as propagation is
// exact, we do not need to recheck that variable.
if (var_index == touched_var_) {
touched_var_ = -1; // Clean it, it is a one time flag.
continue;
}
const std::vector<uint64_t>& var_mask = masks_[var_index];
const int64_t original_min = original_min_[var_index];
IntVar* const var = vars_[var_index];
const int64_t var_size = var->Size();
switch (var_size) {
case 1: {
if ((var_mask[var->Min() - original_min] & actives) == 0) {
// The difference with the non-small version of the table
// is that checking the validity of the resulting active
// tuples is cheap. Therefore we do not delay the check
// code.
solver()->Fail();
}
break;
}
case 2: {
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
const bool min_support =
(var_mask[var_min - original_min] & actives) != 0;
const bool max_support =
(var_mask[var_max - original_min] & actives) != 0;
if (!min_support && !max_support) {
solver()->Fail();
} else if (!min_support) {
var->SetValue(var_max);
} else if (!max_support) {
var->SetValue(var_min);
}
break;
}
default: {
to_remove_.clear();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
int64_t new_min = var_min;
int64_t new_max = var_max;
if (var_max - var_min + 1 == var_size) {
// Contiguous case.
for (; new_min <= var_max; ++new_min) {
if ((var_mask[new_min - original_min] & actives) != 0) {
break;
}
}
for (; new_max >= new_min; --new_max) {
if ((var_mask[new_max - original_min] & actives) != 0) {
break;
}
}
var->SetRange(new_min, new_max);
for (int64_t value = new_min + 1; value < new_max; ++value) {
if ((var_mask[value - original_min] & actives) == 0) {
to_remove_.push_back(value);
}
}
} else {
bool min_set = false;
int last_size = 0;
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
// The iterator is not safe w.r.t. deletion. Thus we
// postpone all value removals.
if ((var_mask[value - original_min] & actives) == 0) {
if (min_set) {
to_remove_.push_back(value);
}
} else {
if (!min_set) {
new_min = value;
min_set = true;
}
new_max = value;
last_size = to_remove_.size();
}
}
if (min_set) {
var->SetRange(new_min, new_max);
} else {
solver()->Fail();
}
to_remove_.resize(last_size);
}
var->RemoveValues(to_remove_);
}
}
}
}
void SmallCompactPositiveTableConstraint::Update(int var_index) {
// This method updates the set of active tuples by masking out all
// tuples attached to values of the variables that have been removed.
IntVar* const var = vars_[var_index];
const int64_t original_min = original_min_[var_index];
const int64_t var_size = var->Size();
switch (var_size) {
case 1: {
ApplyMask(var_index, masks_[var_index][var->Min() - original_min]);
return;
}
case 2: {
ApplyMask(var_index, masks_[var_index][var->Min() - original_min] |
masks_[var_index][var->Max() - original_min]);
return;
}
default: {
// We first collect the complete set of tuples to blank out in
// temp_mask.
const std::vector<uint64_t>& var_mask = masks_[var_index];
const int64_t old_min = var->OldMin();
const int64_t old_max = var->OldMax();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
const bool contiguous = var_size == var_max - var_min + 1;
const bool nearly_contiguous =
var_size > (var_max - var_min + 1) * 7 / 10;
// Count the number of masks to collect to compare the deduction
// vs the construction of the new active bitset.
// TODO(user): Implement HolesSize() on IntVar* and use it
// to remove this code and the var_sizes in the non_small
// version.
uint64_t hole_mask = 0;
if (!contiguous) {
for (const int64_t value : InitAndGetValues(holes_[var_index])) {
hole_mask |= var_mask[value - original_min];
}
}
const int64_t hole_operations = var_min - old_min + old_max - var_max;
// We estimate the domain iterator to be 4x slower.
const int64_t domain_operations = contiguous ? var_size : 4 * var_size;
if (hole_operations < domain_operations) {
for (int64_t value = old_min; value < var_min; ++value) {
hole_mask |= var_mask[value - original_min];
}
for (int64_t value = var_max + 1; value <= old_max; ++value) {
hole_mask |= var_mask[value - original_min];
}
// We reverse the mask as this was negative information.
ApplyMask(var_index, ~hole_mask);
} else {
uint64_t domain_mask = 0;
if (contiguous) {
for (int64_t value = var_min; value <= var_max; ++value) {
domain_mask |= var_mask[value - original_min];
}
} else if (nearly_contiguous) {
for (int64_t value = var_min; value <= var_max; ++value) {
if (var->Contains(value)) {
domain_mask |= var_mask[value - original_min];
}
}
} else {
for (const int64_t value : InitAndGetValues(iterators_[var_index])) {
domain_mask |= var_mask[value - original_min];
}
}
ApplyMask(var_index, domain_mask);
}