forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
expr_array.cc
3577 lines (3238 loc) · 117 KB
/
expr_array.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-2024 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.
//
// Array Expression constraints
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/string_array.h"
namespace operations_research {
namespace {
// ----- Tree Array Constraint -----
class TreeArrayConstraint : public CastConstraint {
public:
TreeArrayConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const sum_var)
: CastConstraint(solver, sum_var),
vars_(vars),
block_size_(solver->parameters().array_split_size()) {
std::vector<int> lengths;
lengths.push_back(vars_.size());
while (lengths.back() > 1) {
const int current = lengths.back();
lengths.push_back((current + block_size_ - 1) / block_size_);
}
tree_.resize(lengths.size());
for (int i = 0; i < lengths.size(); ++i) {
tree_[i].resize(lengths[lengths.size() - i - 1]);
}
DCHECK_GE(tree_.size(), 1);
DCHECK_EQ(1, tree_[0].size());
root_node_ = &tree_[0][0];
}
std::string DebugStringInternal(absl::string_view name) const {
return absl::StrFormat("%s(%s) == %s", name,
JoinDebugStringPtr(vars_, ", "),
target_var_->DebugString());
}
void AcceptInternal(const std::string& name,
ModelVisitor* const visitor) const {
visitor->BeginVisitConstraint(name, this);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
vars_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
target_var_);
visitor->EndVisitConstraint(name, this);
}
// Increases min by delta_min, reduces max by delta_max.
void ReduceRange(int depth, int position, int64_t delta_min,
int64_t delta_max) {
NodeInfo* const info = &tree_[depth][position];
if (delta_min > 0) {
info->node_min.SetValue(solver(),
CapAdd(info->node_min.Value(), delta_min));
}
if (delta_max > 0) {
info->node_max.SetValue(solver(),
CapSub(info->node_max.Value(), delta_max));
}
}
// Sets the range on the given node.
void SetRange(int depth, int position, int64_t new_min, int64_t new_max) {
NodeInfo* const info = &tree_[depth][position];
if (new_min > info->node_min.Value()) {
info->node_min.SetValue(solver(), new_min);
}
if (new_max < info->node_max.Value()) {
info->node_max.SetValue(solver(), new_max);
}
}
void InitLeaf(int position, int64_t var_min, int64_t var_max) {
InitNode(MaxDepth(), position, var_min, var_max);
}
void InitNode(int depth, int position, int64_t node_min, int64_t node_max) {
tree_[depth][position].node_min.SetValue(solver(), node_min);
tree_[depth][position].node_max.SetValue(solver(), node_max);
}
int64_t Min(int depth, int position) const {
return tree_[depth][position].node_min.Value();
}
int64_t Max(int depth, int position) const {
return tree_[depth][position].node_max.Value();
}
int64_t RootMin() const { return root_node_->node_min.Value(); }
int64_t RootMax() const { return root_node_->node_max.Value(); }
int Parent(int position) const { return position / block_size_; }
int ChildStart(int position) const { return position * block_size_; }
int ChildEnd(int depth, int position) const {
DCHECK_LT(depth + 1, tree_.size());
return std::min((position + 1) * block_size_ - 1, Width(depth + 1) - 1);
}
bool IsLeaf(int depth) const { return depth == MaxDepth(); }
int MaxDepth() const { return tree_.size() - 1; }
int Width(int depth) const { return tree_[depth].size(); }
protected:
const std::vector<IntVar*> vars_;
private:
struct NodeInfo {
NodeInfo() : node_min(0), node_max(0) {}
Rev<int64_t> node_min;
Rev<int64_t> node_max;
};
std::vector<std::vector<NodeInfo> > tree_;
const int block_size_;
NodeInfo* root_node_;
};
// ---------- Sum Array ----------
// Some of these optimizations here are described in:
// "Bounds consistency techniques for long linear constraints". In
// Workshop on Techniques for Implementing Constraint Programming
// Systems (TRICS), a workshop of CP 2002, N. Beldiceanu, W. Harvey,
// Martin Henz, Francois Laburthe, Eric Monfroy, Tobias Müller,
// Laurent Perron and Christian Schulte editors, pages 39-46, 2002.
// ----- SumConstraint -----
// This constraint implements sum(vars) == sum_var.
class SumConstraint : public TreeArrayConstraint {
public:
SumConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const sum_var)
: TreeArrayConstraint(solver, vars, sum_var), sum_demon_(nullptr) {}
~SumConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &SumConstraint::LeafChanged, "LeafChanged", i);
vars_[i]->WhenRange(demon);
}
sum_demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &SumConstraint::SumChanged, "SumChanged"));
target_var_->WhenRange(sum_demon_);
}
void InitialPropagate() override {
// Copy vars to leaf nodes.
for (int i = 0; i < vars_.size(); ++i) {
InitLeaf(i, vars_[i]->Min(), vars_[i]->Max());
}
// Compute up.
for (int i = MaxDepth() - 1; i >= 0; --i) {
for (int j = 0; j < Width(i); ++j) {
int64_t sum_min = 0;
int64_t sum_max = 0;
const int block_start = ChildStart(j);
const int block_end = ChildEnd(i, j);
for (int k = block_start; k <= block_end; ++k) {
sum_min = CapAdd(sum_min, Min(i + 1, k));
sum_max = CapAdd(sum_max, Max(i + 1, k));
}
InitNode(i, j, sum_min, sum_max);
}
}
// Propagate to sum_var.
target_var_->SetRange(RootMin(), RootMax());
// Push down.
SumChanged();
}
void SumChanged() {
if (target_var_->Max() == RootMin() &&
target_var_->Max() != std::numeric_limits<int64_t>::max()) {
// We can fix all terms to min.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Min());
}
} else if (target_var_->Min() == RootMax() &&
target_var_->Min() != std::numeric_limits<int64_t>::min()) {
// We can fix all terms to max.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Max());
}
} else {
PushDown(0, 0, target_var_->Min(), target_var_->Max());
}
}
void PushDown(int depth, int position, int64_t new_min, int64_t new_max) {
// Nothing to do?
if (new_min <= Min(depth, position) && new_max >= Max(depth, position)) {
return;
}
// Leaf node -> push to leaf var.
if (IsLeaf(depth)) {
vars_[position]->SetRange(new_min, new_max);
return;
}
// Standard propagation from the bounds of the sum to the
// individuals terms.
// These are maintained automatically in the tree structure.
const int64_t sum_min = Min(depth, position);
const int64_t sum_max = Max(depth, position);
// Intersect the new bounds with the computed bounds.
new_max = std::min(sum_max, new_max);
new_min = std::max(sum_min, new_min);
// Detect failure early.
if (new_max < sum_min || new_min > sum_max) {
solver()->Fail();
}
// Push to children nodes.
const int block_start = ChildStart(position);
const int block_end = ChildEnd(depth, position);
for (int i = block_start; i <= block_end; ++i) {
const int64_t target_var_min = Min(depth + 1, i);
const int64_t target_var_max = Max(depth + 1, i);
const int64_t residual_min = CapSub(sum_min, target_var_min);
const int64_t residual_max = CapSub(sum_max, target_var_max);
PushDown(depth + 1, i, CapSub(new_min, residual_max),
CapSub(new_max, residual_min));
}
// TODO(user) : Is the diameter optimization (see reference
// above, rule 5) useful?
}
void LeafChanged(int term_index) {
IntVar* const var = vars_[term_index];
PushUp(term_index, CapSub(var->Min(), var->OldMin()),
CapSub(var->OldMax(), var->Max()));
EnqueueDelayedDemon(sum_demon_); // TODO(user): Is this needed?
}
void PushUp(int position, int64_t delta_min, int64_t delta_max) {
DCHECK_GE(delta_max, 0);
DCHECK_GE(delta_min, 0);
DCHECK_GT(CapAdd(delta_min, delta_max), 0);
for (int depth = MaxDepth(); depth >= 0; --depth) {
ReduceRange(depth, position, delta_min, delta_max);
position = Parent(position);
}
DCHECK_EQ(0, position);
target_var_->SetRange(RootMin(), RootMax());
}
std::string DebugString() const override {
return DebugStringInternal("Sum");
}
void Accept(ModelVisitor* const visitor) const override {
AcceptInternal(ModelVisitor::kSumEqual, visitor);
}
private:
Demon* sum_demon_;
};
// This constraint implements sum(vars) == target_var.
class SmallSumConstraint : public Constraint {
public:
SmallSumConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const target_var)
: Constraint(solver),
vars_(vars),
target_var_(target_var),
computed_min_(0),
computed_max_(0),
sum_demon_(nullptr) {}
~SmallSumConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
if (!vars_[i]->Bound()) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &SmallSumConstraint::VarChanged, "VarChanged",
vars_[i]);
vars_[i]->WhenRange(demon);
}
}
sum_demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &SmallSumConstraint::SumChanged, "SumChanged"));
target_var_->WhenRange(sum_demon_);
}
void InitialPropagate() override {
// Compute up.
int64_t sum_min = 0;
int64_t sum_max = 0;
for (IntVar* const var : vars_) {
sum_min = CapAdd(sum_min, var->Min());
sum_max = CapAdd(sum_max, var->Max());
}
// Propagate to sum_var.
computed_min_.SetValue(solver(), sum_min);
computed_max_.SetValue(solver(), sum_max);
target_var_->SetRange(sum_min, sum_max);
// Push down.
SumChanged();
}
void SumChanged() {
int64_t new_min = target_var_->Min();
int64_t new_max = target_var_->Max();
const int64_t sum_min = computed_min_.Value();
const int64_t sum_max = computed_max_.Value();
if (new_max == sum_min && new_max != std::numeric_limits<int64_t>::max()) {
// We can fix all terms to min.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Min());
}
} else if (new_min == sum_max &&
new_min != std::numeric_limits<int64_t>::min()) {
// We can fix all terms to max.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Max());
}
} else {
if (new_min > sum_min || new_max < sum_max) { // something to do.
// Intersect the new bounds with the computed bounds.
new_max = std::min(sum_max, new_max);
new_min = std::max(sum_min, new_min);
// Detect failure early.
if (new_max < sum_min || new_min > sum_max) {
solver()->Fail();
}
// Push to variables.
for (IntVar* const var : vars_) {
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
const int64_t residual_min = CapSub(sum_min, var_min);
const int64_t residual_max = CapSub(sum_max, var_max);
var->SetRange(CapSub(new_min, residual_max),
CapSub(new_max, residual_min));
}
}
}
}
void VarChanged(IntVar* var) {
const int64_t delta_min = CapSub(var->Min(), var->OldMin());
const int64_t delta_max = CapSub(var->OldMax(), var->Max());
computed_min_.Add(solver(), delta_min);
computed_max_.Add(solver(), -delta_max);
if (computed_max_.Value() < target_var_->Max() ||
computed_min_.Value() > target_var_->Min()) {
target_var_->SetRange(computed_min_.Value(), computed_max_.Value());
} else {
EnqueueDelayedDemon(sum_demon_);
}
}
std::string DebugString() const override {
return absl::StrFormat("SmallSum(%s) == %s",
JoinDebugStringPtr(vars_, ", "),
target_var_->DebugString());
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(ModelVisitor::kSumEqual, this);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
vars_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
target_var_);
visitor->EndVisitConstraint(ModelVisitor::kSumEqual, this);
}
private:
const std::vector<IntVar*> vars_;
IntVar* target_var_;
NumericalRev<int64_t> computed_min_;
NumericalRev<int64_t> computed_max_;
Demon* sum_demon_;
};
// ----- SafeSumConstraint -----
bool DetectSumOverflow(const std::vector<IntVar*>& vars) {
int64_t sum_min = 0;
int64_t sum_max = 0;
for (int i = 0; i < vars.size(); ++i) {
sum_min = CapAdd(sum_min, vars[i]->Min());
sum_max = CapAdd(sum_max, vars[i]->Max());
if (sum_min == std::numeric_limits<int64_t>::min() ||
sum_max == std::numeric_limits<int64_t>::max()) {
return true;
}
}
return false;
}
// This constraint implements sum(vars) == sum_var.
class SafeSumConstraint : public TreeArrayConstraint {
public:
SafeSumConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const sum_var)
: TreeArrayConstraint(solver, vars, sum_var), sum_demon_(nullptr) {}
~SafeSumConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &SafeSumConstraint::LeafChanged, "LeafChanged", i);
vars_[i]->WhenRange(demon);
}
sum_demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &SafeSumConstraint::SumChanged, "SumChanged"));
target_var_->WhenRange(sum_demon_);
}
void SafeComputeNode(int depth, int position, int64_t* const sum_min,
int64_t* const sum_max) {
DCHECK_LT(depth, MaxDepth());
const int block_start = ChildStart(position);
const int block_end = ChildEnd(depth, position);
for (int k = block_start; k <= block_end; ++k) {
if (*sum_min != std::numeric_limits<int64_t>::min()) {
*sum_min = CapAdd(*sum_min, Min(depth + 1, k));
}
if (*sum_max != std::numeric_limits<int64_t>::max()) {
*sum_max = CapAdd(*sum_max, Max(depth + 1, k));
}
if (*sum_min == std::numeric_limits<int64_t>::min() &&
*sum_max == std::numeric_limits<int64_t>::max()) {
break;
}
}
}
void InitialPropagate() override {
// Copy vars to leaf nodes.
for (int i = 0; i < vars_.size(); ++i) {
InitLeaf(i, vars_[i]->Min(), vars_[i]->Max());
}
// Compute up.
for (int i = MaxDepth() - 1; i >= 0; --i) {
for (int j = 0; j < Width(i); ++j) {
int64_t sum_min = 0;
int64_t sum_max = 0;
SafeComputeNode(i, j, &sum_min, &sum_max);
InitNode(i, j, sum_min, sum_max);
}
}
// Propagate to sum_var.
target_var_->SetRange(RootMin(), RootMax());
// Push down.
SumChanged();
}
void SumChanged() {
DCHECK(CheckInternalState());
if (target_var_->Max() == RootMin()) {
// We can fix all terms to min.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Min());
}
} else if (target_var_->Min() == RootMax()) {
// We can fix all terms to max.
for (int i = 0; i < vars_.size(); ++i) {
vars_[i]->SetValue(vars_[i]->Max());
}
} else {
PushDown(0, 0, target_var_->Min(), target_var_->Max());
}
}
void PushDown(int depth, int position, int64_t new_min, int64_t new_max) {
// Nothing to do?
if (new_min <= Min(depth, position) && new_max >= Max(depth, position)) {
return;
}
// Leaf node -> push to leaf var.
if (IsLeaf(depth)) {
vars_[position]->SetRange(new_min, new_max);
return;
}
// Standard propagation from the bounds of the sum to the
// individuals terms.
// These are maintained automatically in the tree structure.
const int64_t sum_min = Min(depth, position);
const int64_t sum_max = Max(depth, position);
// Intersect the new bounds with the computed bounds.
new_max = std::min(sum_max, new_max);
new_min = std::max(sum_min, new_min);
// Detect failure early.
if (new_max < sum_min || new_min > sum_max) {
solver()->Fail();
}
// Push to children nodes.
const int block_start = ChildStart(position);
const int block_end = ChildEnd(depth, position);
for (int pos = block_start; pos <= block_end; ++pos) {
const int64_t target_var_min = Min(depth + 1, pos);
const int64_t residual_min =
sum_min != std::numeric_limits<int64_t>::min()
? CapSub(sum_min, target_var_min)
: std::numeric_limits<int64_t>::min();
const int64_t target_var_max = Max(depth + 1, pos);
const int64_t residual_max =
sum_max != std::numeric_limits<int64_t>::max()
? CapSub(sum_max, target_var_max)
: std::numeric_limits<int64_t>::max();
PushDown(depth + 1, pos,
(residual_max == std::numeric_limits<int64_t>::min()
? std::numeric_limits<int64_t>::min()
: CapSub(new_min, residual_max)),
(residual_min == std::numeric_limits<int64_t>::max()
? std::numeric_limits<int64_t>::min()
: CapSub(new_max, residual_min)));
}
// TODO(user) : Is the diameter optimization (see reference
// above, rule 5) useful?
}
void LeafChanged(int term_index) {
IntVar* const var = vars_[term_index];
PushUp(term_index, CapSub(var->Min(), var->OldMin()),
CapSub(var->OldMax(), var->Max()));
EnqueueDelayedDemon(sum_demon_); // TODO(user): Is this needed?
}
void PushUp(int position, int64_t delta_min, int64_t delta_max) {
DCHECK_GE(delta_max, 0);
DCHECK_GE(delta_min, 0);
if (CapAdd(delta_min, delta_max) == 0) {
// This may happen if the computation of old min/max has under/overflowed
// resulting in no actual change in min and max.
return;
}
bool delta_corrupted = false;
for (int depth = MaxDepth(); depth >= 0; --depth) {
if (Min(depth, position) != std::numeric_limits<int64_t>::min() &&
Max(depth, position) != std::numeric_limits<int64_t>::max() &&
delta_min != std::numeric_limits<int64_t>::max() &&
delta_max != std::numeric_limits<int64_t>::max() &&
!delta_corrupted) { // No overflow.
ReduceRange(depth, position, delta_min, delta_max);
} else if (depth == MaxDepth()) { // Leaf.
SetRange(depth, position, vars_[position]->Min(),
vars_[position]->Max());
delta_corrupted = true;
} else { // Recompute.
int64_t sum_min = 0;
int64_t sum_max = 0;
SafeComputeNode(depth, position, &sum_min, &sum_max);
if (sum_min == std::numeric_limits<int64_t>::min() &&
sum_max == std::numeric_limits<int64_t>::max()) {
return; // Nothing to do upward.
}
SetRange(depth, position, sum_min, sum_max);
delta_corrupted = true;
}
position = Parent(position);
}
DCHECK_EQ(0, position);
target_var_->SetRange(RootMin(), RootMax());
}
std::string DebugString() const override {
return DebugStringInternal("Sum");
}
void Accept(ModelVisitor* const visitor) const override {
AcceptInternal(ModelVisitor::kSumEqual, visitor);
}
private:
bool CheckInternalState() {
for (int i = 0; i < vars_.size(); ++i) {
CheckLeaf(i, vars_[i]->Min(), vars_[i]->Max());
}
// Check up.
for (int i = MaxDepth() - 1; i >= 0; --i) {
for (int j = 0; j < Width(i); ++j) {
int64_t sum_min = 0;
int64_t sum_max = 0;
SafeComputeNode(i, j, &sum_min, &sum_max);
CheckNode(i, j, sum_min, sum_max);
}
}
return true;
}
void CheckLeaf(int position, int64_t var_min, int64_t var_max) {
CheckNode(MaxDepth(), position, var_min, var_max);
}
void CheckNode(int depth, int position, int64_t node_min, int64_t node_max) {
DCHECK_EQ(Min(depth, position), node_min);
DCHECK_EQ(Max(depth, position), node_max);
}
Demon* sum_demon_;
};
// ---------- Min Array ----------
// This constraint implements min(vars) == min_var.
class MinConstraint : public TreeArrayConstraint {
public:
MinConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const min_var)
: TreeArrayConstraint(solver, vars, min_var), min_demon_(nullptr) {}
~MinConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &MinConstraint::LeafChanged, "LeafChanged", i);
vars_[i]->WhenRange(demon);
}
min_demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &MinConstraint::MinVarChanged, "MinVarChanged"));
target_var_->WhenRange(min_demon_);
}
void InitialPropagate() override {
// Copy vars to leaf nodes.
for (int i = 0; i < vars_.size(); ++i) {
InitLeaf(i, vars_[i]->Min(), vars_[i]->Max());
}
// Compute up.
for (int i = MaxDepth() - 1; i >= 0; --i) {
for (int j = 0; j < Width(i); ++j) {
int64_t min_min = std::numeric_limits<int64_t>::max();
int64_t min_max = std::numeric_limits<int64_t>::max();
const int block_start = ChildStart(j);
const int block_end = ChildEnd(i, j);
for (int k = block_start; k <= block_end; ++k) {
min_min = std::min(min_min, Min(i + 1, k));
min_max = std::min(min_max, Max(i + 1, k));
}
InitNode(i, j, min_min, min_max);
}
}
// Propagate to min_var.
target_var_->SetRange(RootMin(), RootMax());
// Push down.
MinVarChanged();
}
void MinVarChanged() {
PushDown(0, 0, target_var_->Min(), target_var_->Max());
}
void PushDown(int depth, int position, int64_t new_min, int64_t new_max) {
// Nothing to do?
if (new_min <= Min(depth, position) && new_max >= Max(depth, position)) {
return;
}
// Leaf node -> push to leaf var.
if (IsLeaf(depth)) {
vars_[position]->SetRange(new_min, new_max);
return;
}
const int64_t node_min = Min(depth, position);
const int64_t node_max = Max(depth, position);
int candidate = -1;
int active = 0;
const int block_start = ChildStart(position);
const int block_end = ChildEnd(depth, position);
if (new_max < node_max) {
// Look if only one candidat to push the max down.
for (int i = block_start; i <= block_end; ++i) {
if (Min(depth + 1, i) <= new_max) {
if (active++ >= 1) {
break;
}
candidate = i;
}
}
if (active == 0) {
solver()->Fail();
}
}
if (node_min < new_min) {
for (int i = block_start; i <= block_end; ++i) {
if (i == candidate && active == 1) {
PushDown(depth + 1, i, new_min, new_max);
} else {
PushDown(depth + 1, i, new_min, Max(depth + 1, i));
}
}
} else if (active == 1) {
PushDown(depth + 1, candidate, Min(depth + 1, candidate), new_max);
}
}
// TODO(user): Regroup code between Min and Max constraints.
void LeafChanged(int term_index) {
IntVar* const var = vars_[term_index];
SetRange(MaxDepth(), term_index, var->Min(), var->Max());
const int parent_depth = MaxDepth() - 1;
const int parent = Parent(term_index);
const int64_t old_min = var->OldMin();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
if ((old_min == Min(parent_depth, parent) && old_min != var_min) ||
var_max < Max(parent_depth, parent)) {
// Can influence the parent bounds.
PushUp(term_index);
}
}
void PushUp(int position) {
int depth = MaxDepth();
while (depth > 0) {
const int parent = Parent(position);
const int parent_depth = depth - 1;
int64_t min_min = std::numeric_limits<int64_t>::max();
int64_t min_max = std::numeric_limits<int64_t>::max();
const int block_start = ChildStart(parent);
const int block_end = ChildEnd(parent_depth, parent);
for (int k = block_start; k <= block_end; ++k) {
min_min = std::min(min_min, Min(depth, k));
min_max = std::min(min_max, Max(depth, k));
}
if (min_min > Min(parent_depth, parent) ||
min_max < Max(parent_depth, parent)) {
SetRange(parent_depth, parent, min_min, min_max);
} else {
break;
}
depth = parent_depth;
position = parent;
}
if (depth == 0) { // We have pushed all the way up.
target_var_->SetRange(RootMin(), RootMax());
}
MinVarChanged();
}
std::string DebugString() const override {
return DebugStringInternal("Min");
}
void Accept(ModelVisitor* const visitor) const override {
AcceptInternal(ModelVisitor::kMinEqual, visitor);
}
private:
Demon* min_demon_;
};
class SmallMinConstraint : public Constraint {
public:
SmallMinConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const target_var)
: Constraint(solver),
vars_(vars),
target_var_(target_var),
computed_min_(0),
computed_max_(0) {}
~SmallMinConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
if (!vars_[i]->Bound()) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &SmallMinConstraint::VarChanged, "VarChanged",
vars_[i]);
vars_[i]->WhenRange(demon);
}
}
Demon* const mdemon = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &SmallMinConstraint::MinVarChanged, "MinVarChanged"));
target_var_->WhenRange(mdemon);
}
void InitialPropagate() override {
int64_t min_min = std::numeric_limits<int64_t>::max();
int64_t min_max = std::numeric_limits<int64_t>::max();
for (IntVar* const var : vars_) {
min_min = std::min(min_min, var->Min());
min_max = std::min(min_max, var->Max());
}
computed_min_.SetValue(solver(), min_min);
computed_max_.SetValue(solver(), min_max);
// Propagate to min_var.
target_var_->SetRange(min_min, min_max);
// Push down.
MinVarChanged();
}
std::string DebugString() const override {
return absl::StrFormat("SmallMin(%s) == %s",
JoinDebugStringPtr(vars_, ", "),
target_var_->DebugString());
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(ModelVisitor::kMinEqual, this);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
vars_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
target_var_);
visitor->EndVisitConstraint(ModelVisitor::kMinEqual, this);
}
private:
void VarChanged(IntVar* var) {
const int64_t old_min = var->OldMin();
const int64_t var_min = var->Min();
const int64_t var_max = var->Max();
if ((old_min == computed_min_.Value() && old_min != var_min) ||
var_max < computed_max_.Value()) {
// Can influence the min var bounds.
int64_t min_min = std::numeric_limits<int64_t>::max();
int64_t min_max = std::numeric_limits<int64_t>::max();
for (IntVar* const var : vars_) {
min_min = std::min(min_min, var->Min());
min_max = std::min(min_max, var->Max());
}
if (min_min > computed_min_.Value() || min_max < computed_max_.Value()) {
computed_min_.SetValue(solver(), min_min);
computed_max_.SetValue(solver(), min_max);
target_var_->SetRange(computed_min_.Value(), computed_max_.Value());
}
}
MinVarChanged();
}
void MinVarChanged() {
const int64_t new_min = target_var_->Min();
const int64_t new_max = target_var_->Max();
// Nothing to do?
if (new_min <= computed_min_.Value() && new_max >= computed_max_.Value()) {
return;
}
IntVar* candidate = nullptr;
int active = 0;
if (new_max < computed_max_.Value()) {
// Look if only one candidate to push the max down.
for (IntVar* const var : vars_) {
if (var->Min() <= new_max) {
if (active++ >= 1) {
break;
}
candidate = var;
}
}
if (active == 0) {
solver()->Fail();
}
}
if (computed_min_.Value() < new_min) {
if (active == 1) {
candidate->SetRange(new_min, new_max);
} else {
for (IntVar* const var : vars_) {
var->SetMin(new_min);
}
}
} else if (active == 1) {
candidate->SetMax(new_max);
}
}
std::vector<IntVar*> vars_;
IntVar* const target_var_;
Rev<int64_t> computed_min_;
Rev<int64_t> computed_max_;
};
// ---------- Max Array ----------
// This constraint implements max(vars) == max_var.
class MaxConstraint : public TreeArrayConstraint {
public:
MaxConstraint(Solver* const solver, const std::vector<IntVar*>& vars,
IntVar* const max_var)
: TreeArrayConstraint(solver, vars, max_var), max_demon_(nullptr) {}
~MaxConstraint() override {}
void Post() override {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const demon = MakeConstraintDemon1(
solver(), this, &MaxConstraint::LeafChanged, "LeafChanged", i);
vars_[i]->WhenRange(demon);
}
max_demon_ = solver()->RegisterDemon(MakeDelayedConstraintDemon0(
solver(), this, &MaxConstraint::MaxVarChanged, "MaxVarChanged"));
target_var_->WhenRange(max_demon_);
}
void InitialPropagate() override {
// Copy vars to leaf nodes.
for (int i = 0; i < vars_.size(); ++i) {
InitLeaf(i, vars_[i]->Min(), vars_[i]->Max());
}
// Compute up.
for (int i = MaxDepth() - 1; i >= 0; --i) {
for (int j = 0; j < Width(i); ++j) {
int64_t max_min = std::numeric_limits<int64_t>::min();
int64_t max_max = std::numeric_limits<int64_t>::min();
const int block_start = ChildStart(j);
const int block_end = ChildEnd(i, j);
for (int k = block_start; k <= block_end; ++k) {
max_min = std::max(max_min, Min(i + 1, k));
max_max = std::max(max_max, Max(i + 1, k));
}
InitNode(i, j, max_min, max_max);
}
}
// Propagate to min_var.
target_var_->SetRange(RootMin(), RootMax());
// Push down.
MaxVarChanged();
}
void MaxVarChanged() {
PushDown(0, 0, target_var_->Min(), target_var_->Max());
}
void PushDown(int depth, int position, int64_t new_min, int64_t new_max) {
// Nothing to do?
if (new_min <= Min(depth, position) && new_max >= Max(depth, position)) {
return;
}
// Leaf node -> push to leaf var.
if (IsLeaf(depth)) {
vars_[position]->SetRange(new_min, new_max);
return;
}
const int64_t node_min = Min(depth, position);
const int64_t node_max = Max(depth, position);