forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expressions.cc
7479 lines (6530 loc) · 221 KB
/
expressions.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 <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/util/bitset.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/string_array.h"
DEFINE_bool(cp_disable_expression_optimization, false,
"Disable special optimization when creating expressions.");
DEFINE_bool(cp_share_int_consts, true, "Share IntConst's with the same value.");
#if defined(_MSC_VER)
#pragma warning(disable : 4351 4355)
#endif
namespace operations_research {
// ---------- IntExpr ----------
IntVar* IntExpr::VarWithName(const std::string& name) {
IntVar* const var = Var();
var->set_name(name);
return var;
}
// ---------- IntVar ----------
IntVar::IntVar(Solver* const s) : IntExpr(s), index_(s->GetNewIntVarIndex()) {}
IntVar::IntVar(Solver* const s, const std::string& name)
: IntExpr(s), index_(s->GetNewIntVarIndex()) {
set_name(name);
}
// ----- Boolean variable -----
const int BooleanVar::kUnboundBooleanVarValue = 2;
void BooleanVar::SetMin(int64 m) {
if (m <= 0) return;
if (m > 1) solver()->Fail();
SetValue(1);
}
void BooleanVar::SetMax(int64 m) {
if (m >= 1) return;
if (m < 0) solver()->Fail();
SetValue(0);
}
void BooleanVar::SetRange(int64 mi, int64 ma) {
if (mi > 1 || ma < 0 || mi > ma) {
solver()->Fail();
}
if (mi == 1) {
SetValue(1);
} else if (ma == 0) {
SetValue(0);
}
}
void BooleanVar::RemoveValue(int64 v) {
if (value_ == kUnboundBooleanVarValue) {
if (v == 0) {
SetValue(1);
} else if (v == 1) {
SetValue(0);
}
} else if (v == value_) {
solver()->Fail();
}
}
void BooleanVar::RemoveInterval(int64 l, int64 u) {
if (u < l) return;
if (l <= 0 && u >= 1) {
solver()->Fail();
} else if (l == 1) {
SetValue(0);
} else if (u == 0) {
SetValue(1);
}
}
void BooleanVar::WhenBound(Demon* d) {
if (value_ == kUnboundBooleanVarValue) {
if (d->priority() == Solver::DELAYED_PRIORITY) {
delayed_bound_demons_.PushIfNotTop(solver(), solver()->RegisterDemon(d));
} else {
bound_demons_.PushIfNotTop(solver(), solver()->RegisterDemon(d));
}
}
}
uint64 BooleanVar::Size() const {
return (1 + (value_ == kUnboundBooleanVarValue));
}
bool BooleanVar::Contains(int64 v) const {
return ((v == 0 && value_ != 1) || (v == 1 && value_ != 0));
}
IntVar* BooleanVar::IsEqual(int64 constant) {
if (constant > 1 || constant < 0) {
return solver()->MakeIntConst(0);
}
if (constant == 1) {
return this;
} else { // constant == 0.
return solver()->MakeDifference(1, this)->Var();
}
}
IntVar* BooleanVar::IsDifferent(int64 constant) {
if (constant > 1 || constant < 0) {
return solver()->MakeIntConst(1);
}
if (constant == 1) {
return solver()->MakeDifference(1, this)->Var();
} else { // constant == 0.
return this;
}
}
IntVar* BooleanVar::IsGreaterOrEqual(int64 constant) {
if (constant > 1) {
return solver()->MakeIntConst(0);
} else if (constant <= 0) {
return solver()->MakeIntConst(1);
} else {
return this;
}
}
IntVar* BooleanVar::IsLessOrEqual(int64 constant) {
if (constant < 0) {
return solver()->MakeIntConst(0);
} else if (constant >= 1) {
return solver()->MakeIntConst(1);
} else {
return IsEqual(0);
}
}
std::string BooleanVar::DebugString() const {
std::string out;
const std::string& var_name = name();
if (!var_name.empty()) {
out = var_name + "(";
} else {
out = "BooleanVar(";
}
switch (value_) {
case 0:
out += "0";
break;
case 1:
out += "1";
break;
case kUnboundBooleanVarValue:
out += "0 .. 1";
break;
}
out += ")";
return out;
}
namespace {
// ---------- Subclasses of IntVar ----------
// ----- Domain Int Var: base class for variables -----
// It Contains bounds and a bitset representation of possible values.
class DomainIntVar : public IntVar {
public:
// Utility classes
class BitSetIterator : public BaseObject {
public:
BitSetIterator(uint64* const bitset, int64 omin)
: bitset_(bitset), omin_(omin), max_(kint64min), current_(kint64max) {}
~BitSetIterator() override {}
void Init(int64 min, int64 max) {
max_ = max;
current_ = min;
}
bool Ok() const { return current_ <= max_; }
int64 Value() const { return current_; }
void Next() {
if (++current_ <= max_) {
current_ = UnsafeLeastSignificantBitPosition64(
bitset_, current_ - omin_, max_ - omin_) +
omin_;
}
}
std::string DebugString() const override { return "BitSetIterator"; }
private:
uint64* const bitset_;
const int64 omin_;
int64 max_;
int64 current_;
};
class BitSet : public BaseObject {
public:
explicit BitSet(Solver* const s) : solver_(s), holes_stamp_(0) {}
~BitSet() override {}
virtual int64 ComputeNewMin(int64 nmin, int64 cmin, int64 cmax) = 0;
virtual int64 ComputeNewMax(int64 nmax, int64 cmin, int64 cmax) = 0;
virtual bool Contains(int64 val) const = 0;
virtual bool SetValue(int64 val) = 0;
virtual bool RemoveValue(int64 val) = 0;
virtual uint64 Size() const = 0;
virtual void DelayRemoveValue(int64 val) = 0;
virtual void ApplyRemovedValues(DomainIntVar* var) = 0;
virtual void ClearRemovedValues() = 0;
virtual std::string pretty_DebugString(int64 min, int64 max) const = 0;
virtual BitSetIterator* MakeIterator() = 0;
void InitHoles() {
const uint64 current_stamp = solver_->stamp();
if (holes_stamp_ < current_stamp) {
holes_.clear();
holes_stamp_ = current_stamp;
}
}
virtual void ClearHoles() { holes_.clear(); }
const std::vector<int64>& Holes() { return holes_; }
void AddHole(int64 value) { holes_.push_back(value); }
int NumHoles() const {
return holes_stamp_ < solver_->stamp() ? 0 : holes_.size();
}
protected:
Solver* const solver_;
private:
std::vector<int64> holes_;
uint64 holes_stamp_;
};
class QueueHandler : public Demon {
public:
explicit QueueHandler(DomainIntVar* const var) : var_(var) {}
~QueueHandler() override {}
void Run(Solver* const s) override {
s->GetPropagationMonitor()->StartProcessingIntegerVariable(var_);
var_->Process();
s->GetPropagationMonitor()->EndProcessingIntegerVariable(var_);
}
Solver::DemonPriority priority() const override {
return Solver::VAR_PRIORITY;
}
std::string DebugString() const override {
return absl::StrFormat("Handler(%s)", var_->DebugString());
}
private:
DomainIntVar* const var_;
};
// Bounds and Value watchers
// This class stores the watchers variables attached to values. It is
// reversible and it helps maintaining the set of 'active' watchers
// (variables not bound to a single value).
template <class T>
class RevIntPtrMap {
public:
RevIntPtrMap(Solver* const solver, int64 rmin, int64 rmax)
: solver_(solver), range_min_(rmin), start_(0) {}
~RevIntPtrMap() {}
bool Empty() const { return start_.Value() == elements_.size(); }
void SortActive() { std::sort(elements_.begin(), elements_.end()); }
// Access with value API.
// Add the pointer to the map attached to the given value.
void UnsafeRevInsert(int64 value, T* elem) {
elements_.push_back(std::make_pair(value, elem));
if (solver_->state() != Solver::OUTSIDE_SEARCH) {
solver_->AddBacktrackAction(
[this, value](Solver* s) { Uninsert(value); }, false);
}
}
T* FindPtrOrNull(int64 value, int* position) {
for (int pos = start_.Value(); pos < elements_.size(); ++pos) {
if (elements_[pos].first == value) {
if (position != nullptr) *position = pos;
return At(pos).second;
}
}
return nullptr;
}
// Access map through the underlying vector.
void RemoveAt(int position) {
const int start = start_.Value();
DCHECK_GE(position, start);
DCHECK_LT(position, elements_.size());
if (position > start) {
// Swap the current element with the one at the start position, and
// increase start.
const std::pair<int64, T*> copy = elements_[start];
elements_[start] = elements_[position];
elements_[position] = copy;
}
start_.Incr(solver_);
}
const std::pair<int64, T*>& At(int position) const {
DCHECK_GE(position, start_.Value());
DCHECK_LT(position, elements_.size());
return elements_[position];
}
void RemoveAll() { start_.SetValue(solver_, elements_.size()); }
int start() const { return start_.Value(); }
int end() const { return elements_.size(); }
// Number of active elements.
int Size() const { return elements_.size() - start_.Value(); }
// Removes the object permanently from the map.
void Uninsert(int64 value) {
for (int pos = 0; pos < elements_.size(); ++pos) {
if (elements_[pos].first == value) {
DCHECK_GE(pos, start_.Value());
const int last = elements_.size() - 1;
if (pos != last) { // Swap the current with the last.
elements_[pos] = elements_.back();
}
elements_.pop_back();
return;
}
}
LOG(FATAL) << "The element should have been removed";
}
private:
Solver* const solver_;
const int64 range_min_;
NumericalRev<int> start_;
std::vector<std::pair<int64, T*>> elements_;
};
// Base class for value watchers
class BaseValueWatcher : public Constraint {
public:
explicit BaseValueWatcher(Solver* const solver) : Constraint(solver) {}
~BaseValueWatcher() override {}
virtual IntVar* GetOrMakeValueWatcher(int64 value) = 0;
virtual void SetValueWatcher(IntVar* const boolvar, int64 value) = 0;
};
// This class monitors the domain of the variable and updates the
// IsEqual/IsDifferent boolean variables accordingly.
class ValueWatcher : public BaseValueWatcher {
public:
class WatchDemon : public Demon {
public:
WatchDemon(ValueWatcher* const watcher, int64 value, IntVar* var)
: value_watcher_(watcher), value_(value), var_(var) {}
~WatchDemon() override {}
void Run(Solver* const solver) override {
value_watcher_->ProcessValueWatcher(value_, var_);
}
private:
ValueWatcher* const value_watcher_;
const int64 value_;
IntVar* const var_;
};
class VarDemon : public Demon {
public:
explicit VarDemon(ValueWatcher* const watcher)
: value_watcher_(watcher) {}
~VarDemon() override {}
void Run(Solver* const solver) override { value_watcher_->ProcessVar(); }
private:
ValueWatcher* const value_watcher_;
};
ValueWatcher(Solver* const solver, DomainIntVar* const variable)
: BaseValueWatcher(solver),
variable_(variable),
hole_iterator_(variable_->MakeHoleIterator(true)),
var_demon_(nullptr),
watchers_(solver, variable->Min(), variable->Max()) {}
~ValueWatcher() override {}
IntVar* GetOrMakeValueWatcher(int64 value) override {
IntVar* const watcher = watchers_.FindPtrOrNull(value, nullptr);
if (watcher != nullptr) return watcher;
if (variable_->Contains(value)) {
if (variable_->Bound()) {
return solver()->MakeIntConst(1);
} else {
const std::string vname = variable_->HasName()
? variable_->name()
: variable_->DebugString();
const std::string bname =
absl::StrFormat("Watch<%s == %d>", vname, value);
IntVar* const boolvar = solver()->MakeBoolVar(bname);
watchers_.UnsafeRevInsert(value, boolvar);
if (posted_.Switched()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
}
return boolvar;
}
} else {
return variable_->solver()->MakeIntConst(0);
}
}
void SetValueWatcher(IntVar* const boolvar, int64 value) override {
CHECK(watchers_.FindPtrOrNull(value, nullptr) == nullptr);
if (!boolvar->Bound()) {
watchers_.UnsafeRevInsert(value, boolvar);
if (posted_.Switched() && !boolvar->Bound()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
}
}
}
void Post() override {
var_demon_ = solver()->RevAlloc(new VarDemon(this));
variable_->WhenDomain(var_demon_);
for (int pos = watchers_.start(); pos < watchers_.end(); ++pos) {
const std::pair<int64, IntVar*>& w = watchers_.At(pos);
const int64 value = w.first;
IntVar* const boolvar = w.second;
if (!boolvar->Bound() && variable_->Contains(value)) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
}
}
posted_.Switch(solver());
}
void InitialPropagate() override {
if (variable_->Bound()) {
VariableBound();
} else {
for (int pos = watchers_.start(); pos < watchers_.end(); ++pos) {
const std::pair<int64, IntVar*>& w = watchers_.At(pos);
const int64 value = w.first;
IntVar* const boolvar = w.second;
if (!variable_->Contains(value)) {
boolvar->SetValue(0);
watchers_.RemoveAt(pos);
} else {
if (boolvar->Bound()) {
ProcessValueWatcher(value, boolvar);
watchers_.RemoveAt(pos);
}
}
}
CheckInhibit();
}
}
void ProcessValueWatcher(int64 value, IntVar* boolvar) {
if (boolvar->Min() == 0) {
if (variable_->Size() < 0xFFFFFF) {
variable_->RemoveValue(value);
} else {
// Delay removal.
solver()->AddConstraint(solver()->MakeNonEquality(variable_, value));
}
} else {
variable_->SetValue(value);
}
}
void ProcessVar() {
const int kSmallList = 16;
if (variable_->Bound()) {
VariableBound();
} else if (watchers_.Size() <= kSmallList ||
variable_->Min() != variable_->OldMin() ||
variable_->Max() != variable_->OldMax()) {
// Brute force loop for small numbers of watchers, or if the bounds have
// changed, which would have required a sort (n log(n)) anyway to take
// advantage of.
ScanWatchers();
CheckInhibit();
} else {
// If there is no bitset, then there are no holes.
// In that case, the two loops above should have performed all
// propagation. Otherwise, scan the remaining watchers.
BitSet* const bitset = variable_->bitset();
if (bitset != nullptr && !watchers_.Empty()) {
if (bitset->NumHoles() * 2 < watchers_.Size()) {
for (const int64 hole : InitAndGetValues(hole_iterator_)) {
int pos = 0;
IntVar* const boolvar = watchers_.FindPtrOrNull(hole, &pos);
if (boolvar != nullptr) {
boolvar->SetValue(0);
watchers_.RemoveAt(pos);
}
}
} else {
ScanWatchers();
}
}
CheckInhibit();
}
}
// Optimized case if the variable is bound.
void VariableBound() {
DCHECK(variable_->Bound());
const int64 value = variable_->Min();
for (int pos = watchers_.start(); pos < watchers_.end(); ++pos) {
const std::pair<int64, IntVar*>& w = watchers_.At(pos);
w.second->SetValue(w.first == value);
}
watchers_.RemoveAll();
var_demon_->inhibit(solver());
}
// Scans all the watchers to check and assign them.
void ScanWatchers() {
for (int pos = watchers_.start(); pos < watchers_.end(); ++pos) {
const std::pair<int64, IntVar*>& w = watchers_.At(pos);
if (!variable_->Contains(w.first)) {
IntVar* const boolvar = w.second;
boolvar->SetValue(0);
watchers_.RemoveAt(pos);
}
}
}
// If the set of active watchers is empty, we can inhibit the demon on the
// main variable.
void CheckInhibit() {
if (watchers_.Empty()) {
var_demon_->inhibit(solver());
}
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(ModelVisitor::kVarValueWatcher, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kVariableArgument,
variable_);
std::vector<int64> all_coefficients;
std::vector<IntVar*> all_bool_vars;
for (int position = watchers_.start(); position < watchers_.end();
++position) {
const std::pair<int64, IntVar*>& w = watchers_.At(position);
all_coefficients.push_back(w.first);
all_bool_vars.push_back(w.second);
}
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
all_bool_vars);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument,
all_coefficients);
visitor->EndVisitConstraint(ModelVisitor::kVarValueWatcher, this);
}
std::string DebugString() const override {
return absl::StrFormat("ValueWatcher(%s)", variable_->DebugString());
}
private:
DomainIntVar* const variable_;
IntVarIterator* const hole_iterator_;
RevSwitch posted_;
Demon* var_demon_;
RevIntPtrMap<IntVar> watchers_;
};
// Optimized case for small maps.
class DenseValueWatcher : public BaseValueWatcher {
public:
class WatchDemon : public Demon {
public:
WatchDemon(DenseValueWatcher* const watcher, int64 value, IntVar* var)
: value_watcher_(watcher), value_(value), var_(var) {}
~WatchDemon() override {}
void Run(Solver* const solver) override {
value_watcher_->ProcessValueWatcher(value_, var_);
}
private:
DenseValueWatcher* const value_watcher_;
const int64 value_;
IntVar* const var_;
};
class VarDemon : public Demon {
public:
explicit VarDemon(DenseValueWatcher* const watcher)
: value_watcher_(watcher) {}
~VarDemon() override {}
void Run(Solver* const solver) override { value_watcher_->ProcessVar(); }
private:
DenseValueWatcher* const value_watcher_;
};
DenseValueWatcher(Solver* const solver, DomainIntVar* const variable)
: BaseValueWatcher(solver),
variable_(variable),
hole_iterator_(variable_->MakeHoleIterator(true)),
var_demon_(nullptr),
offset_(variable->Min()),
watchers_(variable->Max() - variable->Min() + 1, nullptr),
active_watchers_(0) {}
~DenseValueWatcher() override {}
IntVar* GetOrMakeValueWatcher(int64 value) override {
const int64 var_max = offset_ + watchers_.size() - 1; // Bad cast.
if (value < offset_ || value > var_max) {
return solver()->MakeIntConst(0);
}
const int index = value - offset_;
IntVar* const watcher = watchers_[index];
if (watcher != nullptr) return watcher;
if (variable_->Contains(value)) {
if (variable_->Bound()) {
return solver()->MakeIntConst(1);
} else {
const std::string vname = variable_->HasName()
? variable_->name()
: variable_->DebugString();
const std::string bname =
absl::StrFormat("Watch<%s == %d>", vname, value);
IntVar* const boolvar = solver()->MakeBoolVar(bname);
RevInsert(index, boolvar);
if (posted_.Switched()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
}
return boolvar;
}
} else {
return variable_->solver()->MakeIntConst(0);
}
}
void SetValueWatcher(IntVar* const boolvar, int64 value) override {
const int index = value - offset_;
CHECK(watchers_[index] == nullptr);
if (!boolvar->Bound()) {
RevInsert(index, boolvar);
if (posted_.Switched() && !boolvar->Bound()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
}
}
}
void Post() override {
var_demon_ = solver()->RevAlloc(new VarDemon(this));
variable_->WhenDomain(var_demon_);
for (int pos = 0; pos < watchers_.size(); ++pos) {
const int64 value = pos + offset_;
IntVar* const boolvar = watchers_[pos];
if (boolvar != nullptr && !boolvar->Bound() &&
variable_->Contains(value)) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
}
}
posted_.Switch(solver());
}
void InitialPropagate() override {
if (variable_->Bound()) {
VariableBound();
} else {
for (int pos = 0; pos < watchers_.size(); ++pos) {
IntVar* const boolvar = watchers_[pos];
if (boolvar == nullptr) continue;
const int64 value = pos + offset_;
if (!variable_->Contains(value)) {
boolvar->SetValue(0);
RevRemove(pos);
} else if (boolvar->Bound()) {
ProcessValueWatcher(value, boolvar);
RevRemove(pos);
}
}
if (active_watchers_.Value() == 0) {
var_demon_->inhibit(solver());
}
}
}
void ProcessValueWatcher(int64 value, IntVar* boolvar) {
if (boolvar->Min() == 0) {
variable_->RemoveValue(value);
} else {
variable_->SetValue(value);
}
}
void ProcessVar() {
if (variable_->Bound()) {
VariableBound();
} else {
// Brute force loop for small numbers of watchers.
ScanWatchers();
if (active_watchers_.Value() == 0) {
var_demon_->inhibit(solver());
}
}
}
// Optimized case if the variable is bound.
void VariableBound() {
DCHECK(variable_->Bound());
const int64 value = variable_->Min();
for (int pos = 0; pos < watchers_.size(); ++pos) {
IntVar* const boolvar = watchers_[pos];
if (boolvar != nullptr) {
boolvar->SetValue(pos + offset_ == value);
RevRemove(pos);
}
}
var_demon_->inhibit(solver());
}
// Scans all the watchers to check and assign them.
void ScanWatchers() {
const int64 old_min_index = variable_->OldMin() - offset_;
const int64 old_max_index = variable_->OldMax() - offset_;
const int64 min_index = variable_->Min() - offset_;
const int64 max_index = variable_->Max() - offset_;
for (int pos = old_min_index; pos < min_index; ++pos) {
IntVar* const boolvar = watchers_[pos];
if (boolvar != nullptr) {
boolvar->SetValue(0);
RevRemove(pos);
}
}
for (int pos = max_index + 1; pos <= old_max_index; ++pos) {
IntVar* const boolvar = watchers_[pos];
if (boolvar != nullptr) {
boolvar->SetValue(0);
RevRemove(pos);
}
}
BitSet* const bitset = variable_->bitset();
if (bitset != nullptr) {
if (bitset->NumHoles() * 2 < active_watchers_.Value()) {
for (const int64 hole : InitAndGetValues(hole_iterator_)) {
IntVar* const boolvar = watchers_[hole - offset_];
if (boolvar != nullptr) {
boolvar->SetValue(0);
RevRemove(hole - offset_);
}
}
} else {
for (int pos = min_index + 1; pos < max_index; ++pos) {
IntVar* const boolvar = watchers_[pos];
if (boolvar != nullptr && !variable_->Contains(offset_ + pos)) {
boolvar->SetValue(0);
RevRemove(pos);
}
}
}
}
}
void RevRemove(int pos) {
solver()->SaveValue(reinterpret_cast<void**>(&watchers_[pos]));
watchers_[pos] = nullptr;
active_watchers_.Decr(solver());
}
void RevInsert(int pos, IntVar* boolvar) {
solver()->SaveValue(reinterpret_cast<void**>(&watchers_[pos]));
watchers_[pos] = boolvar;
active_watchers_.Incr(solver());
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(ModelVisitor::kVarValueWatcher, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kVariableArgument,
variable_);
std::vector<int64> all_coefficients;
std::vector<IntVar*> all_bool_vars;
for (int position = 0; position < watchers_.size(); ++position) {
if (watchers_[position] != nullptr) {
all_coefficients.push_back(position + offset_);
all_bool_vars.push_back(watchers_[position]);
}
}
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
all_bool_vars);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument,
all_coefficients);
visitor->EndVisitConstraint(ModelVisitor::kVarValueWatcher, this);
}
std::string DebugString() const override {
return absl::StrFormat("DenseValueWatcher(%s)", variable_->DebugString());
}
private:
DomainIntVar* const variable_;
IntVarIterator* const hole_iterator_;
RevSwitch posted_;
Demon* var_demon_;
const int64 offset_;
std::vector<IntVar*> watchers_;
NumericalRev<int> active_watchers_;
};
class BaseUpperBoundWatcher : public Constraint {
public:
explicit BaseUpperBoundWatcher(Solver* const solver) : Constraint(solver) {}
~BaseUpperBoundWatcher() override {}
virtual IntVar* GetOrMakeUpperBoundWatcher(int64 value) = 0;
virtual void SetUpperBoundWatcher(IntVar* const boolvar, int64 value) = 0;
};
// This class watches the bounds of the variable and updates the
// IsGreater/IsGreaterOrEqual/IsLess/IsLessOrEqual demons
// accordingly.
class UpperBoundWatcher : public BaseUpperBoundWatcher {
public:
class WatchDemon : public Demon {
public:
WatchDemon(UpperBoundWatcher* const watcher, int64 index,
IntVar* const var)
: value_watcher_(watcher), index_(index), var_(var) {}
~WatchDemon() override {}
void Run(Solver* const solver) override {
value_watcher_->ProcessUpperBoundWatcher(index_, var_);
}
private:
UpperBoundWatcher* const value_watcher_;
const int64 index_;
IntVar* const var_;
};
class VarDemon : public Demon {
public:
explicit VarDemon(UpperBoundWatcher* const watcher)
: value_watcher_(watcher) {}
~VarDemon() override {}
void Run(Solver* const solver) override { value_watcher_->ProcessVar(); }
private:
UpperBoundWatcher* const value_watcher_;
};
UpperBoundWatcher(Solver* const solver, DomainIntVar* const variable)
: BaseUpperBoundWatcher(solver),
variable_(variable),
var_demon_(nullptr),
watchers_(solver, variable->Min(), variable->Max()),
start_(0),
end_(0),
sorted_(false) {}
~UpperBoundWatcher() override {}
IntVar* GetOrMakeUpperBoundWatcher(int64 value) override {
IntVar* const watcher = watchers_.FindPtrOrNull(value, nullptr);
if (watcher != nullptr) {
return watcher;
}
if (variable_->Max() >= value) {
if (variable_->Min() >= value) {
return solver()->MakeIntConst(1);
} else {
const std::string vname = variable_->HasName()
? variable_->name()
: variable_->DebugString();
const std::string bname =
absl::StrFormat("Watch<%s >= %d>", vname, value);
IntVar* const boolvar = solver()->MakeBoolVar(bname);
watchers_.UnsafeRevInsert(value, boolvar);
if (posted_.Switched()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
sorted_ = false;
}
return boolvar;
}
} else {
return variable_->solver()->MakeIntConst(0);
}
}
void SetUpperBoundWatcher(IntVar* const boolvar, int64 value) override {
CHECK(watchers_.FindPtrOrNull(value, nullptr) == nullptr);
watchers_.UnsafeRevInsert(value, boolvar);
if (posted_.Switched() && !boolvar->Bound()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
var_demon_->desinhibit(solver());
sorted_ = false;
}
}
void Post() override {
const int kTooSmallToSort = 8;
var_demon_ = solver()->RevAlloc(new VarDemon(this));
variable_->WhenRange(var_demon_);
if (watchers_.Size() > kTooSmallToSort) {
watchers_.SortActive();
sorted_ = true;
start_.SetValue(solver(), watchers_.start());
end_.SetValue(solver(), watchers_.end() - 1);
}
for (int pos = watchers_.start(); pos < watchers_.end(); ++pos) {
const std::pair<int64, IntVar*>& w = watchers_.At(pos);
IntVar* const boolvar = w.second;
const int64 value = w.first;
if (!boolvar->Bound() && value > variable_->Min() &&
value <= variable_->Max()) {
boolvar->WhenBound(
solver()->RevAlloc(new WatchDemon(this, value, boolvar)));
}
}
posted_.Switch(solver());
}
void InitialPropagate() override {
const int64 var_min = variable_->Min();
const int64 var_max = variable_->Max();
if (sorted_) {
while (start_.Value() <= end_.Value()) {
const std::pair<int64, IntVar*>& w = watchers_.At(start_.Value());