forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
interval.cc
2470 lines (2169 loc) · 80.3 KB
/
interval.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.
#include <algorithm>
#include <cstdint>
#include <limits>
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "ortools/base/logging.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"
#if defined(_MSC_VER)
#pragma warning(disable : 4351 4355 4804 4805)
#endif
namespace operations_research {
// Generic code for start/end/duration expressions.
// This is not done in a superclass as this is not compatible with the current
// class hierarchy.
// ----- Expression builders ------
IntExpr* BuildStartExpr(IntervalVar* var);
IntExpr* BuildDurationExpr(IntervalVar* var);
IntExpr* BuildEndExpr(IntervalVar* var);
IntExpr* BuildSafeStartExpr(IntervalVar* var, int64_t unperformed_value);
IntExpr* BuildSafeDurationExpr(IntervalVar* var, int64_t unperformed_value);
IntExpr* BuildSafeEndExpr(IntervalVar* var, int64_t unperformed_value);
void LinkVarExpr(Solver* s, IntExpr* expr, IntVar* var);
// It's good to have the two extreme values being symmetrical around zero: it
// makes mirroring easier.
const int64_t IntervalVar::kMaxValidValue =
std::numeric_limits<int64_t>::max() >> 2;
const int64_t IntervalVar::kMinValidValue = -kMaxValidValue;
namespace {
enum IntervalField { START, DURATION, END };
IntervalVar* NullInterval() { return nullptr; }
// ----- MirrorIntervalVar -----
class MirrorIntervalVar : public IntervalVar {
public:
MirrorIntervalVar(Solver* const s, IntervalVar* const t)
: IntervalVar(s, "Mirror<" + t->name() + ">"), t_(t) {}
// This type is neither copyable nor movable.
MirrorIntervalVar(const MirrorIntervalVar&) = delete;
MirrorIntervalVar& operator=(const MirrorIntervalVar&) = delete;
~MirrorIntervalVar() override {}
// These methods query, set and watch the start position of the
// interval var.
int64_t StartMin() const override { return -t_->EndMax(); }
int64_t StartMax() const override { return -t_->EndMin(); }
void SetStartMin(int64_t m) override { t_->SetEndMax(-m); }
void SetStartMax(int64_t m) override { t_->SetEndMin(-m); }
void SetStartRange(int64_t mi, int64_t ma) override {
t_->SetEndRange(-ma, -mi);
}
int64_t OldStartMin() const override { return -t_->OldEndMax(); }
int64_t OldStartMax() const override { return -t_->OldEndMin(); }
void WhenStartRange(Demon* const d) override { t_->WhenEndRange(d); }
void WhenStartBound(Demon* const d) override { t_->WhenEndBound(d); }
// These methods query, set and watch the duration of the interval var.
int64_t DurationMin() const override { return t_->DurationMin(); }
int64_t DurationMax() const override { return t_->DurationMax(); }
void SetDurationMin(int64_t m) override { t_->SetDurationMin(m); }
void SetDurationMax(int64_t m) override { t_->SetDurationMax(m); }
void SetDurationRange(int64_t mi, int64_t ma) override {
t_->SetDurationRange(mi, ma);
}
int64_t OldDurationMin() const override { return t_->OldDurationMin(); }
int64_t OldDurationMax() const override { return t_->OldDurationMax(); }
void WhenDurationRange(Demon* const d) override { t_->WhenDurationRange(d); }
void WhenDurationBound(Demon* const d) override { t_->WhenDurationBound(d); }
// These methods query, set and watch the end position of the interval var.
int64_t EndMin() const override { return -t_->StartMax(); }
int64_t EndMax() const override { return -t_->StartMin(); }
void SetEndMin(int64_t m) override { t_->SetStartMax(-m); }
void SetEndMax(int64_t m) override { t_->SetStartMin(-m); }
void SetEndRange(int64_t mi, int64_t ma) override {
t_->SetStartRange(-ma, -mi);
}
int64_t OldEndMin() const override { return -t_->OldStartMax(); }
int64_t OldEndMax() const override { return -t_->OldStartMin(); }
void WhenEndRange(Demon* const d) override { t_->WhenStartRange(d); }
void WhenEndBound(Demon* const d) override { t_->WhenStartBound(d); }
// These methods query, set and watches the performed status of the
// interval var.
bool MustBePerformed() const override { return t_->MustBePerformed(); }
bool MayBePerformed() const override { return t_->MayBePerformed(); }
void SetPerformed(bool val) override { t_->SetPerformed(val); }
bool WasPerformedBound() const override { return t_->WasPerformedBound(); }
void WhenPerformedBound(Demon* const d) override {
t_->WhenPerformedBound(d);
}
void Accept(ModelVisitor* const visitor) const override {
visitor->VisitIntervalVariable(this, ModelVisitor::kMirrorOperation, 0, t_);
}
std::string DebugString() const override {
return absl::StrFormat("MirrorInterval(%s)", t_->DebugString());
}
IntExpr* StartExpr() override {
return solver()->MakeOpposite(t_->EndExpr());
}
IntExpr* DurationExpr() override { return t_->DurationExpr(); }
IntExpr* EndExpr() override {
return solver()->MakeOpposite(t_->StartExpr());
}
IntExpr* PerformedExpr() override { return t_->PerformedExpr(); }
// These methods create expressions encapsulating the start, end
// and duration of the interval var. If the interval var is
// unperformed, they will return the unperformed_value.
IntExpr* SafeStartExpr(int64_t unperformed_value) override {
return solver()->MakeOpposite(t_->SafeEndExpr(-unperformed_value));
}
IntExpr* SafeDurationExpr(int64_t unperformed_value) override {
return t_->SafeDurationExpr(unperformed_value);
}
IntExpr* SafeEndExpr(int64_t unperformed_value) override {
return solver()->MakeOpposite(t_->SafeStartExpr(-unperformed_value));
}
private:
IntervalVar* const t_;
};
// An IntervalVar that passes all function calls to an underlying interval
// variable as long as it is not prohibited, and that interprets prohibited
// intervals as intervals of duration 0 that must be executed between
// [kMinValidValue and kMaxValidValue].
//
// Such interval variables have a very similar behavior to others.
// Invariants such as StartMin() + DurationMin() <= EndMin() that are maintained
// for traditional interval variables are maintained for instances of
// AlwaysPerformedIntervalVarWrapper. However, there is no monotonicity of the
// values returned by the start/end getters. For example, during a given
// propagation, three successive calls to StartMin could return,
// in this order, 1, 2, and kMinValidValue.
//
// This class exists so that we can easily implement the
// IntervalVarRelaxedMax and IntervalVarRelaxedMin classes below.
class AlwaysPerformedIntervalVarWrapper : public IntervalVar {
public:
explicit AlwaysPerformedIntervalVarWrapper(IntervalVar* const t)
: IntervalVar(t->solver(),
absl::StrFormat("AlwaysPerformed<%s>", t->name())),
t_(t),
start_expr_(nullptr),
duration_expr_(nullptr),
end_expr_(nullptr) {}
// This type is neither copyable nor movable.
AlwaysPerformedIntervalVarWrapper(const AlwaysPerformedIntervalVarWrapper&) =
delete;
AlwaysPerformedIntervalVarWrapper& operator=(
const AlwaysPerformedIntervalVarWrapper&) = delete;
~AlwaysPerformedIntervalVarWrapper() override {}
int64_t StartMin() const override {
return MayUnderlyingBePerformed() ? t_->StartMin() : kMinValidValue;
}
int64_t StartMax() const override {
return MayUnderlyingBePerformed() ? t_->StartMax() : kMaxValidValue;
}
void SetStartMin(int64_t m) override { t_->SetStartMin(m); }
void SetStartMax(int64_t m) override { t_->SetStartMax(m); }
void SetStartRange(int64_t mi, int64_t ma) override {
t_->SetStartRange(mi, ma);
}
int64_t OldStartMin() const override {
return MayUnderlyingBePerformed() ? t_->OldStartMin() : kMinValidValue;
}
int64_t OldStartMax() const override {
return MayUnderlyingBePerformed() ? t_->OldStartMax() : kMaxValidValue;
}
void WhenStartRange(Demon* const d) override { t_->WhenStartRange(d); }
void WhenStartBound(Demon* const d) override { t_->WhenStartBound(d); }
int64_t DurationMin() const override {
return MayUnderlyingBePerformed() ? t_->DurationMin() : 0LL;
}
int64_t DurationMax() const override {
return MayUnderlyingBePerformed() ? t_->DurationMax() : 0LL;
}
void SetDurationMin(int64_t m) override { t_->SetDurationMin(m); }
void SetDurationMax(int64_t m) override { t_->SetDurationMax(m); }
void SetDurationRange(int64_t mi, int64_t ma) override {
t_->SetDurationRange(mi, ma);
}
int64_t OldDurationMin() const override {
return MayUnderlyingBePerformed() ? t_->OldDurationMin() : 0LL;
}
int64_t OldDurationMax() const override {
return MayUnderlyingBePerformed() ? t_->OldDurationMax() : 0LL;
}
void WhenDurationRange(Demon* const d) override { t_->WhenDurationRange(d); }
void WhenDurationBound(Demon* const d) override { t_->WhenDurationBound(d); }
int64_t EndMin() const override {
return MayUnderlyingBePerformed() ? t_->EndMin() : kMinValidValue;
}
int64_t EndMax() const override {
return MayUnderlyingBePerformed() ? t_->EndMax() : kMaxValidValue;
}
void SetEndMin(int64_t m) override { t_->SetEndMin(m); }
void SetEndMax(int64_t m) override { t_->SetEndMax(m); }
void SetEndRange(int64_t mi, int64_t ma) override { t_->SetEndRange(mi, ma); }
int64_t OldEndMin() const override {
return MayUnderlyingBePerformed() ? t_->OldEndMin() : kMinValidValue;
}
int64_t OldEndMax() const override {
return MayUnderlyingBePerformed() ? t_->OldEndMax() : kMaxValidValue;
}
void WhenEndRange(Demon* const d) override { t_->WhenEndRange(d); }
void WhenEndBound(Demon* const d) override { t_->WhenEndBound(d); }
bool MustBePerformed() const override { return true; }
bool MayBePerformed() const override { return true; }
void SetPerformed(bool val) override {
// An AlwaysPerformedIntervalVarWrapper interval variable is always
// performed. So setting it to be performed does not change anything,
// and setting it not to be performed is inconsistent and should cause
// a failure.
if (!val) {
solver()->Fail();
}
}
bool WasPerformedBound() const override { return true; }
void WhenPerformedBound(Demon* const d) override {
t_->WhenPerformedBound(d);
}
IntExpr* StartExpr() override {
if (start_expr_ == nullptr) {
solver()->SaveValue(reinterpret_cast<void**>(&start_expr_));
start_expr_ = BuildStartExpr(this);
}
return start_expr_;
}
IntExpr* DurationExpr() override {
if (duration_expr_ == nullptr) {
solver()->SaveValue(reinterpret_cast<void**>(&duration_expr_));
duration_expr_ = BuildDurationExpr(this);
}
return duration_expr_;
}
IntExpr* EndExpr() override {
if (end_expr_ == nullptr) {
solver()->SaveValue(reinterpret_cast<void**>(&end_expr_));
end_expr_ = BuildEndExpr(this);
}
return end_expr_;
}
IntExpr* PerformedExpr() override { return solver()->MakeIntConst(1); }
IntExpr* SafeStartExpr(int64_t unperformed_value) override {
return StartExpr();
}
IntExpr* SafeDurationExpr(int64_t unperformed_value) override {
return DurationExpr();
}
IntExpr* SafeEndExpr(int64_t unperformed_value) override { return EndExpr(); }
protected:
IntervalVar* underlying() const { return t_; }
bool MayUnderlyingBePerformed() const {
return underlying()->MayBePerformed();
}
private:
IntervalVar* const t_;
IntExpr* start_expr_;
IntExpr* duration_expr_;
IntExpr* end_expr_;
};
// An interval variable that wraps around an underlying one, relaxing the max
// start and end. Relaxing means making unbounded when optional.
//
// More precisely, such an interval variable behaves as follows:
// * When the underlying must be performed, this interval variable behaves
// exactly as the underlying;
// * When the underlying may or may not be performed, this interval variable
// behaves like the underlying, except that it is unbounded on the max side;
// * When the underlying cannot be performed, this interval variable is of
// duration 0 and must be performed in an interval unbounded on both sides.
//
// This class is very useful to implement propagators that may only modify
// the start min or end min.
class IntervalVarRelaxedMax : public AlwaysPerformedIntervalVarWrapper {
public:
explicit IntervalVarRelaxedMax(IntervalVar* const t)
: AlwaysPerformedIntervalVarWrapper(t) {}
~IntervalVarRelaxedMax() override {}
int64_t StartMax() const override {
// It matters to use DurationMin() and not underlying()->DurationMin() here.
return underlying()->MustBePerformed() ? underlying()->StartMax()
: (kMaxValidValue - DurationMin());
}
void SetStartMax(int64_t m) override {
LOG(FATAL)
<< "Calling SetStartMax on a IntervalVarRelaxedMax is not supported, "
<< "as it seems there is no legitimate use case.";
}
int64_t EndMax() const override {
return underlying()->MustBePerformed() ? underlying()->EndMax()
: kMaxValidValue;
}
void SetEndMax(int64_t m) override {
LOG(FATAL)
<< "Calling SetEndMax on a IntervalVarRelaxedMax is not supported, "
<< "as it seems there is no legitimate use case.";
}
void Accept(ModelVisitor* const visitor) const override {
visitor->VisitIntervalVariable(this, ModelVisitor::kRelaxedMaxOperation, 0,
underlying());
}
std::string DebugString() const override {
return absl::StrFormat("IntervalVarRelaxedMax(%s)",
underlying()->DebugString());
}
};
// An interval variable that wraps around an underlying one, relaxing the min
// start and end. Relaxing means making unbounded when optional.
//
// More precisely, such an interval variable behaves as follows:
// * When the underlying must be performed, this interval variable behaves
// exactly as the underlying;
// * When the underlying may or may not be performed, this interval variable
// behaves like the underlying, except that it is unbounded on the min side;
// * When the underlying cannot be performed, this interval variable is of
// duration 0 and must be performed in an interval unbounded on both sides.
//
// This class is very useful to implement propagators that may only modify
// the start max or end max.
class IntervalVarRelaxedMin : public AlwaysPerformedIntervalVarWrapper {
public:
explicit IntervalVarRelaxedMin(IntervalVar* const t)
: AlwaysPerformedIntervalVarWrapper(t) {}
~IntervalVarRelaxedMin() override {}
int64_t StartMin() const override {
return underlying()->MustBePerformed() ? underlying()->StartMin()
: kMinValidValue;
}
void SetStartMin(int64_t m) override {
LOG(FATAL)
<< "Calling SetStartMin on a IntervalVarRelaxedMin is not supported, "
<< "as it seems there is no legitimate use case.";
}
int64_t EndMin() const override {
// It matters to use DurationMin() and not underlying()->DurationMin() here.
return underlying()->MustBePerformed() ? underlying()->EndMin()
: (kMinValidValue + DurationMin());
}
void SetEndMin(int64_t m) override {
LOG(FATAL)
<< "Calling SetEndMin on a IntervalVarRelaxedMin is not supported, "
<< "as it seems there is no legitimate use case.";
}
void Accept(ModelVisitor* const visitor) const override {
visitor->VisitIntervalVariable(this, ModelVisitor::kRelaxedMinOperation, 0,
underlying());
}
std::string DebugString() const override {
return absl::StrFormat("IntervalVarRelaxedMin(%s)",
underlying()->DebugString());
}
};
// ----- BaseIntervalVar -----
class BaseIntervalVar : public IntervalVar {
public:
class Handler : public Demon {
public:
explicit Handler(BaseIntervalVar* const var) : var_(var) {}
~Handler() override {}
void Run(Solver* const s) override { var_->Process(); }
Solver::DemonPriority priority() const override {
return Solver::VAR_PRIORITY;
}
std::string DebugString() const override {
return absl::StrFormat("Handler(%s)", var_->DebugString());
}
private:
BaseIntervalVar* const var_;
};
BaseIntervalVar(Solver* const s, const std::string& name)
: IntervalVar(s, name),
in_process_(false),
handler_(this),
cleaner_([this](Solver* s) { CleanInProcess(); }) {}
~BaseIntervalVar() override {}
virtual void Process() = 0;
virtual void Push() = 0;
void CleanInProcess() { in_process_ = false; }
std::string BaseName() const override { return "IntervalVar"; }
bool InProcess() const { return in_process_; }
protected:
bool in_process_;
Handler handler_;
Solver::Action cleaner_;
};
class RangeVar : public IntExpr {
public:
RangeVar(Solver* const s, BaseIntervalVar* var, int64_t mi, int64_t ma)
: IntExpr(s),
min_(mi),
max_(ma),
var_(var),
postponed_min_(mi),
postponed_max_(ma),
previous_min_(mi),
previous_max_(ma),
cast_var_(nullptr) {}
~RangeVar() override {}
bool Bound() const override { return min_.Value() == max_.Value(); }
int64_t Min() const override { return min_.Value(); }
int64_t Max() const override { return max_.Value(); }
void SetMin(int64_t m) override {
// No Op.
if (m <= min_.Value()) {
return;
}
// Inconsistent value.
if (m > max_.Value()) {
var_->SetPerformed(false);
return;
}
if (var_->InProcess()) {
// In process, postpone modifications.
if (m > postponed_max_) {
var_->SetPerformed(false);
}
if (m > postponed_min_) {
postponed_min_ = m;
}
} else {
// Not in process.
SyncPreviousBounds();
min_.SetValue(solver(), m);
var_->Push();
}
}
int64_t OldMin() const {
DCHECK(var_->InProcess());
return previous_min_;
}
void SetMax(int64_t m) override {
if (m >= max_.Value()) {
return;
}
if (m < min_.Value()) {
var_->SetPerformed(false);
return;
}
if (var_->InProcess()) {
// In process, postpone modifications.
if (m < postponed_min_) {
var_->SetPerformed(false);
}
if (m < postponed_max_) {
postponed_max_ = m;
}
} else {
// Not in process.
SyncPreviousBounds();
max_.SetValue(solver(), m);
var_->Push();
}
}
int64_t OldMax() const { return previous_min_; }
void SetRange(int64_t mi, int64_t ma) override {
if (mi <= min_.Value() && ma >= max_.Value()) {
// No Op.
return;
}
if (mi > max_.Value() || ma < min_.Value() || mi > ma) {
var_->SetPerformed(false);
}
if (var_->InProcess()) {
if (mi > postponed_max_ || ma < postponed_min_) {
var_->SetPerformed(false);
}
if (mi > postponed_min_) {
postponed_min_ = mi;
}
if (ma < postponed_max_) {
postponed_max_ = ma;
}
} else {
// Not in process.
SyncPreviousBounds();
if (mi > min_.Value()) {
min_.SetValue(solver(), mi);
}
if (ma < max_.Value()) {
max_.SetValue(solver(), ma);
}
var_->Push();
}
}
void WhenRange(Demon* const demon) override {
if (!Bound()) {
if (demon->priority() == Solver::DELAYED_PRIORITY) {
delayed_range_demons_.PushIfNotTop(solver(),
solver()->RegisterDemon(demon));
} else {
range_demons_.PushIfNotTop(solver(), solver()->RegisterDemon(demon));
}
}
}
virtual void WhenBound(Demon* const demon) {
if (!Bound()) {
if (demon->priority() == Solver::DELAYED_PRIORITY) {
delayed_bound_demons_.PushIfNotTop(solver(),
solver()->RegisterDemon(demon));
} else {
bound_demons_.PushIfNotTop(solver(), solver()->RegisterDemon(demon));
}
}
}
void UpdatePostponedBounds() {
postponed_min_ = min_.Value();
postponed_max_ = max_.Value();
}
void ProcessDemons() {
if (Bound()) {
ExecuteAll(bound_demons_);
EnqueueAll(delayed_bound_demons_);
}
if (min_.Value() != previous_min_ || max_.Value() != previous_max_) {
ExecuteAll(range_demons_);
EnqueueAll(delayed_range_demons_);
}
}
void UpdatePreviousBounds() {
previous_min_ = min_.Value();
previous_max_ = max_.Value();
}
// TODO(user): Remove this interval field enum.
void ApplyPostponedBounds(IntervalField which) {
if (min_.Value() < postponed_min_ || max_.Value() > postponed_max_) {
switch (which) {
case START:
var_->SetStartRange(std::max(postponed_min_, min_.Value()),
std::min(postponed_max_, max_.Value()));
break;
case DURATION:
var_->SetDurationRange(std::max(postponed_min_, min_.Value()),
std::min(postponed_max_, max_.Value()));
break;
case END:
var_->SetEndRange(std::max(postponed_min_, min_.Value()),
std::min(postponed_max_, max_.Value()));
break;
}
}
}
IntVar* Var() override {
if (cast_var_ == nullptr) {
solver()->SaveValue(reinterpret_cast<void**>(&cast_var_));
cast_var_ = solver()->MakeIntVar(min_.Value(), max_.Value());
LinkVarExpr(solver(), this, cast_var_);
}
return cast_var_;
}
std::string DebugString() const override {
std::string out = absl::StrCat(min_.Value());
if (!Bound()) {
absl::StrAppendFormat(&out, " .. %d", max_.Value());
}
return out;
}
private:
// The previous bounds are maintained lazily and non reversibly.
// When going down in the search tree, the modifications are
// monotonic, thus SyncPreviousBounds is a no-op because they are
// correctly updated at the end of the ProcessDemons() call. After
// a fail, if they are inconsistent, then they will be outside the
// current interval, thus this check.
void SyncPreviousBounds() {
if (previous_min_ > min_.Value()) {
previous_min_ = min_.Value();
}
if (previous_max_ < max_.Value()) {
previous_max_ = max_.Value();
}
}
// The current reversible bounds of the interval.
NumericalRev<int64_t> min_;
NumericalRev<int64_t> max_;
BaseIntervalVar* const var_;
// When in process, the modifications are postponed and stored in
// these 2 fields.
int64_t postponed_min_;
int64_t postponed_max_;
// The previous bounds stores the bounds since the last time
// ProcessDemons() was run. These are maintained lazily.
int64_t previous_min_;
int64_t previous_max_;
// Demons attached to the 'bound' event (min == max).
SimpleRevFIFO<Demon*> bound_demons_;
SimpleRevFIFO<Demon*> delayed_bound_demons_;
// Demons attached to a modification of bounds.
SimpleRevFIFO<Demon*> range_demons_;
SimpleRevFIFO<Demon*> delayed_range_demons_;
IntVar* cast_var_;
}; // class RangeVar
// ----- PerformedVar -----
class PerformedVar : public BooleanVar {
public:
// Optional = true -> var = [0..1], Optional = false -> var = [1].
PerformedVar(Solver* const s, BaseIntervalVar* const var, bool optional)
: BooleanVar(s, ""),
var_(var),
previous_value_(optional ? kUnboundBooleanVarValue : 1),
postponed_value_(optional ? kUnboundBooleanVarValue : 1) {
if (!optional) {
value_ = 1;
}
}
// var = [0] (always unperformed).
PerformedVar(Solver* const s, BaseIntervalVar* var)
: BooleanVar(s, ""), var_(var), previous_value_(0), postponed_value_(0) {
value_ = 1;
}
~PerformedVar() override {}
void SetValue(int64_t v) override {
if ((v & 0xfffffffffffffffe) != 0 || // Not 0 or 1.
(value_ != kUnboundBooleanVarValue && v != value_)) {
solver()->Fail();
}
if (var_->InProcess()) {
if (postponed_value_ != kUnboundBooleanVarValue &&
v != postponed_value_) { // Fail early.
solver()->Fail();
} else {
postponed_value_ = v;
}
} else if (value_ == kUnboundBooleanVarValue) {
previous_value_ = kUnboundBooleanVarValue;
InternalSaveBooleanVarValue(solver(), this);
value_ = static_cast<int>(v);
var_->Push();
}
}
int64_t OldMin() const override { return previous_value_ == 1; }
int64_t OldMax() const override { return previous_value_ != 0; }
void RestoreValue() override {
previous_value_ = kUnboundBooleanVarValue;
value_ = kUnboundBooleanVarValue;
postponed_value_ = kUnboundBooleanVarValue;
}
void Process() {
if (previous_value_ != value_) {
ExecuteAll(bound_demons_);
EnqueueAll(delayed_bound_demons_);
}
}
void UpdatePostponedValue() { postponed_value_ = value_; }
void UpdatePreviousValueAndApplyPostponedValue() {
previous_value_ = value_;
if (value_ != postponed_value_) {
DCHECK_NE(kUnboundBooleanVarValue, postponed_value_);
SetValue(postponed_value_);
}
}
std::string DebugString() const override {
switch (value_) {
case 0:
return "false";
case 1:
return "true";
default:
return "undecided";
}
}
private:
BaseIntervalVar* const var_;
int previous_value_;
int postponed_value_;
};
// ----- FixedDurationIntervalVar -----
class FixedDurationIntervalVar : public BaseIntervalVar {
public:
FixedDurationIntervalVar(Solver* s, int64_t start_min, int64_t start_max,
int64_t duration, bool optional,
const std::string& name);
// Unperformed interval.
FixedDurationIntervalVar(Solver* s, const std::string& name);
~FixedDurationIntervalVar() override {}
int64_t StartMin() const override;
int64_t StartMax() const override;
void SetStartMin(int64_t m) override;
void SetStartMax(int64_t m) override;
void SetStartRange(int64_t mi, int64_t ma) override;
int64_t OldStartMin() const override { return start_.OldMin(); }
int64_t OldStartMax() const override { return start_.OldMax(); }
void WhenStartRange(Demon* const d) override {
if (performed_.Max() == 1) {
start_.WhenRange(d);
}
}
void WhenStartBound(Demon* const d) override {
if (performed_.Max() == 1) {
start_.WhenBound(d);
}
}
int64_t DurationMin() const override;
int64_t DurationMax() const override;
void SetDurationMin(int64_t m) override;
void SetDurationMax(int64_t m) override;
void SetDurationRange(int64_t mi, int64_t ma) override;
int64_t OldDurationMin() const override { return duration_; }
int64_t OldDurationMax() const override { return duration_; }
void WhenDurationRange(Demon* const d) override {}
void WhenDurationBound(Demon* const d) override {}
int64_t EndMin() const override;
int64_t EndMax() const override;
void SetEndMin(int64_t m) override;
void SetEndMax(int64_t m) override;
void SetEndRange(int64_t mi, int64_t ma) override;
int64_t OldEndMin() const override {
return CapAdd(OldStartMin(), duration_);
}
int64_t OldEndMax() const override {
return CapAdd(OldStartMax(), duration_);
}
void WhenEndRange(Demon* const d) override { WhenStartRange(d); }
void WhenEndBound(Demon* const d) override { WhenStartBound(d); }
bool MustBePerformed() const override;
bool MayBePerformed() const override;
void SetPerformed(bool val) override;
bool WasPerformedBound() const override {
return performed_.OldMin() == performed_.OldMax();
}
void WhenPerformedBound(Demon* const d) override { performed_.WhenBound(d); }
void Process() override;
std::string DebugString() const override;
void Accept(ModelVisitor* const visitor) const override {
visitor->VisitIntervalVariable(this, "", 0, NullInterval());
}
IntExpr* StartExpr() override { return &start_; }
IntExpr* DurationExpr() override { return solver()->MakeIntConst(duration_); }
IntExpr* EndExpr() override {
return solver()->MakeSum(StartExpr(), duration_);
}
IntExpr* PerformedExpr() override { return &performed_; }
IntExpr* SafeStartExpr(int64_t unperformed_value) override {
return BuildSafeStartExpr(this, unperformed_value);
}
IntExpr* SafeDurationExpr(int64_t unperformed_value) override {
return BuildSafeDurationExpr(this, unperformed_value);
}
IntExpr* SafeEndExpr(int64_t unperformed_value) override {
return BuildSafeEndExpr(this, unperformed_value);
}
void Push() override;
private:
RangeVar start_;
int64_t duration_;
PerformedVar performed_;
};
FixedDurationIntervalVar::FixedDurationIntervalVar(
Solver* const s, int64_t start_min, int64_t start_max, int64_t duration,
bool optional, const std::string& name)
: BaseIntervalVar(s, name),
start_(s, this, start_min, start_max),
duration_(duration),
performed_(s, this, optional) {}
FixedDurationIntervalVar::FixedDurationIntervalVar(Solver* const s,
const std::string& name)
: BaseIntervalVar(s, name),
start_(s, this, 0, 0),
duration_(0),
performed_(s, this) {}
void FixedDurationIntervalVar::Process() {
CHECK(!in_process_);
in_process_ = true;
start_.UpdatePostponedBounds();
performed_.UpdatePostponedValue();
set_action_on_fail(cleaner_);
if (performed_.Max() == 1) {
start_.ProcessDemons();
}
performed_.Process();
reset_action_on_fail();
CleanInProcess();
start_.UpdatePreviousBounds();
start_.ApplyPostponedBounds(START);
performed_.UpdatePreviousValueAndApplyPostponedValue();
}
int64_t FixedDurationIntervalVar::StartMin() const {
CHECK_EQ(performed_.Max(), 1);
return start_.Min();
}
int64_t FixedDurationIntervalVar::StartMax() const {
CHECK_EQ(performed_.Max(), 1);
return start_.Max();
}
void FixedDurationIntervalVar::SetStartMin(int64_t m) {
if (performed_.Max() == 1) {
start_.SetMin(m);
}
}
void FixedDurationIntervalVar::SetStartMax(int64_t m) {
if (performed_.Max() == 1) {
start_.SetMax(m);
}
}
void FixedDurationIntervalVar::SetStartRange(int64_t mi, int64_t ma) {
if (performed_.Max() == 1) {
start_.SetRange(mi, ma);
}
}
int64_t FixedDurationIntervalVar::DurationMin() const {
CHECK_EQ(performed_.Max(), 1);
return duration_;
}
int64_t FixedDurationIntervalVar::DurationMax() const {
CHECK_EQ(performed_.Max(), 1);
return duration_;
}
void FixedDurationIntervalVar::SetDurationMin(int64_t m) {
if (m > duration_) {
SetPerformed(false);
}
}
void FixedDurationIntervalVar::SetDurationMax(int64_t m) {
if (m < duration_) {
SetPerformed(false);
}
}
void FixedDurationIntervalVar::SetDurationRange(int64_t mi, int64_t ma) {
if (mi > duration_ || ma < duration_ || mi > ma) {
SetPerformed(false);
}
}
int64_t FixedDurationIntervalVar::EndMin() const {
CHECK_EQ(performed_.Max(), 1);
return start_.Min() + duration_;
}
int64_t FixedDurationIntervalVar::EndMax() const {
CHECK_EQ(performed_.Max(), 1);
return CapAdd(start_.Max(), duration_);
}
void FixedDurationIntervalVar::SetEndMin(int64_t m) {
SetStartMin(CapSub(m, duration_));
}
void FixedDurationIntervalVar::SetEndMax(int64_t m) {
SetStartMax(CapSub(m, duration_));
}
void FixedDurationIntervalVar::SetEndRange(int64_t mi, int64_t ma) {
SetStartRange(CapSub(mi, duration_), CapSub(ma, duration_));
}
bool FixedDurationIntervalVar::MustBePerformed() const {
return (performed_.Min() == 1);
}
bool FixedDurationIntervalVar::MayBePerformed() const {
return (performed_.Max() == 1);
}
void FixedDurationIntervalVar::SetPerformed(bool val) {
performed_.SetValue(val);
}
void FixedDurationIntervalVar::Push() {
DCHECK(!in_process_);
EnqueueVar(&handler_);
DCHECK(!in_process_);
}
std::string FixedDurationIntervalVar::DebugString() const {
const std::string& var_name = name();
if (performed_.Max() == 0) {
if (!var_name.empty()) {
return absl::StrFormat("%s(performed = false)", var_name);
} else {
return "IntervalVar(performed = false)";
}
} else {
std::string out;
if (!var_name.empty()) {
out = var_name + "(start = ";
} else {
out = "IntervalVar(start = ";
}
absl::StrAppendFormat(&out, "%s, duration = %d, performed = %s)",
start_.DebugString(), duration_,
performed_.DebugString());
return out;
}
}
// ----- FixedDurationPerformedIntervalVar -----
class FixedDurationPerformedIntervalVar : public BaseIntervalVar {
public:
FixedDurationPerformedIntervalVar(Solver* s, int64_t start_min,