forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
resource.cc
2695 lines (2419 loc) · 97.5 KB
/
resource.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.
// This file contains implementations of several resource constraints.
// The implemented constraints are:
// * Disjunctive: forces a set of intervals to be non-overlapping
// * Cumulative: forces a set of intervals with associated demands to be such
// that the sum of demands of the intervals containing any given integer
// does not exceed a capacity.
// In addition, it implements the SequenceVar that allows ranking decisions
// on a set of interval variables.
#include <algorithm>
#include <cstdint>
#include <functional>
#include <limits>
#include <queue>
#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 "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/util/bitset.h"
#include "ortools/util/monoid_operation_tree.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/string_array.h"
namespace operations_research {
namespace {
// ----- Comparison functions -----
// TODO(user): Tie breaking.
// Comparison methods, used by the STL sort.
template <class Task>
bool StartMinLessThan(Task* const w1, Task* const w2) {
return (w1->interval->StartMin() < w2->interval->StartMin());
}
// A comparator that sorts the tasks by their effective earliest start time when
// using the shortest duration possible. This comparator can be used when
// sorting the tasks before they are inserted to a Theta-tree.
template <class Task>
bool ShortestDurationStartMinLessThan(Task* const w1, Task* const w2) {
return w1->interval->EndMin() - w1->interval->DurationMin() <
w2->interval->EndMin() - w2->interval->DurationMin();
}
template <class Task>
bool StartMaxLessThan(Task* const w1, Task* const w2) {
return (w1->interval->StartMax() < w2->interval->StartMax());
}
template <class Task>
bool EndMinLessThan(Task* const w1, Task* const w2) {
return (w1->interval->EndMin() < w2->interval->EndMin());
}
template <class Task>
bool EndMaxLessThan(Task* const w1, Task* const w2) {
return (w1->interval->EndMax() < w2->interval->EndMax());
}
bool IntervalStartMinLessThan(IntervalVar* i1, IntervalVar* i2) {
return i1->StartMin() < i2->StartMin();
}
// ----- Wrappers around intervals -----
// A DisjunctiveTask is a non-preemptive task sharing a disjunctive resource.
// That is, it corresponds to an interval, and this interval cannot overlap with
// any other interval of a DisjunctiveTask sharing the same resource.
// It is indexed, that is it is aware of its position in a reference array.
struct DisjunctiveTask {
explicit DisjunctiveTask(IntervalVar* const interval_)
: interval(interval_), index(-1) {}
std::string DebugString() const { return interval->DebugString(); }
IntervalVar* interval;
int index;
};
// A CumulativeTask is a non-preemptive task sharing a cumulative resource.
// That is, it corresponds to an interval and a demand. The sum of demands of
// all cumulative tasks CumulativeTasks sharing a resource of capacity c those
// intervals contain any integer t cannot exceed c.
// It is indexed, that is it is aware of its position in a reference array.
struct CumulativeTask {
CumulativeTask(IntervalVar* const interval_, int64_t demand_)
: interval(interval_), demand(demand_), index(-1) {}
int64_t EnergyMin() const { return interval->DurationMin() * demand; }
int64_t DemandMin() const { return demand; }
void WhenAnything(Demon* const demon) { interval->WhenAnything(demon); }
std::string DebugString() const {
return absl::StrFormat("Task{ %s, demand: %d }", interval->DebugString(),
demand);
}
IntervalVar* interval;
int64_t demand;
int index;
};
// A VariableCumulativeTask is a non-preemptive task sharing a
// cumulative resource. That is, it corresponds to an interval and a
// demand. The sum of demands of all cumulative tasks
// VariableCumulativeTasks sharing a resource of capacity c whose
// intervals contain any integer t cannot exceed c. It is indexed,
// that is it is aware of its position in a reference array.
struct VariableCumulativeTask {
VariableCumulativeTask(IntervalVar* const interval_, IntVar* demand_)
: interval(interval_), demand(demand_), index(-1) {}
int64_t EnergyMin() const { return interval->DurationMin() * demand->Min(); }
int64_t DemandMin() const { return demand->Min(); }
void WhenAnything(Demon* const demon) {
interval->WhenAnything(demon);
demand->WhenRange(demon);
}
std::string DebugString() const {
return absl::StrFormat("Task{ %s, demand: %s }", interval->DebugString(),
demand->DebugString());
}
IntervalVar* const interval;
IntVar* const demand;
int index;
};
// ---------- Theta-Trees ----------
// This is based on Petr Vilim (public) PhD work.
// All names comes from his work. See http://vilim.eu/petr.
// Node of a Theta-tree
struct ThetaNode {
// Identity element
ThetaNode()
: total_processing(0), total_ect(std::numeric_limits<int64_t>::min()) {}
// Single interval element
explicit ThetaNode(const IntervalVar* const interval)
: total_processing(interval->DurationMin()),
total_ect(interval->EndMin()) {
// NOTE(user): Petr Vilim's thesis assumes that all tasks in the
// scheduling problem have fixed duration and that propagation already
// updated the bounds of the start/end times accordingly.
// The problem in this case is that the recursive formula for computing
// total_ect was only proved for the case where the duration is fixed; in
// our case, we use StartMin() + DurationMin() for the earliest completion
// time of a task, which should not break any assumptions, but may give
// bounds that are too loose.
}
void Compute(const ThetaNode& left, const ThetaNode& right) {
total_processing = CapAdd(left.total_processing, right.total_processing);
total_ect = std::max(CapAdd(left.total_ect, right.total_processing),
right.total_ect);
}
bool IsIdentity() const {
return total_processing == 0LL &&
total_ect == std::numeric_limits<int64_t>::min();
}
std::string DebugString() const {
return absl::StrCat("ThetaNode{ p = ", total_processing,
", e = ", total_ect < 0LL ? -1LL : total_ect, " }");
}
int64_t total_processing;
int64_t total_ect;
};
// A theta-tree is a container for a set of intervals supporting the following
// operations:
// * Insertions and deletion in O(log size_), with size_ the maximal number of
// tasks the tree may contain;
// * Querying the following quantity in O(1):
// Max_{subset S of the set of contained intervals} (
// Min_{i in S}(i.StartMin) + Sum_{i in S}(i.DurationMin) )
class ThetaTree : public MonoidOperationTree<ThetaNode> {
public:
explicit ThetaTree(int size) : MonoidOperationTree<ThetaNode>(size) {}
int64_t Ect() const { return result().total_ect; }
void Insert(const DisjunctiveTask* const task) {
Set(task->index, ThetaNode(task->interval));
}
void Remove(const DisjunctiveTask* const task) { Reset(task->index); }
bool IsInserted(const DisjunctiveTask* const task) const {
return !GetOperand(task->index).IsIdentity();
}
};
// ----------------- Lambda Theta Tree -----------------------
// Lambda-theta-node
// These nodes are cumulative lambda theta-node. This is reflected in the
// terminology. They can also be used in the disjunctive case, and this incurs
// no performance penalty.
struct LambdaThetaNode {
// Special value for task indices meaning 'no such task'.
static const int kNone;
// Identity constructor
LambdaThetaNode()
: energy(0LL),
energetic_end_min(std::numeric_limits<int64_t>::min()),
energy_opt(0LL),
argmax_energy_opt(kNone),
energetic_end_min_opt(std::numeric_limits<int64_t>::min()),
argmax_energetic_end_min_opt(kNone) {}
// Constructor for a single cumulative task in the Theta set
LambdaThetaNode(int64_t capacity, const CumulativeTask& task)
: energy(task.EnergyMin()),
energetic_end_min(CapAdd(capacity * task.interval->StartMin(), energy)),
energy_opt(energy),
argmax_energy_opt(kNone),
energetic_end_min_opt(energetic_end_min),
argmax_energetic_end_min_opt(kNone) {}
// Constructor for a single cumulative task in the Lambda set
LambdaThetaNode(int64_t capacity, const CumulativeTask& task, int index)
: energy(0LL),
energetic_end_min(std::numeric_limits<int64_t>::min()),
energy_opt(task.EnergyMin()),
argmax_energy_opt(index),
energetic_end_min_opt(capacity * task.interval->StartMin() +
energy_opt),
argmax_energetic_end_min_opt(index) {
DCHECK_GE(index, 0);
}
// Constructor for a single cumulative task in the Theta set
LambdaThetaNode(int64_t capacity, const VariableCumulativeTask& task)
: energy(task.EnergyMin()),
energetic_end_min(CapAdd(capacity * task.interval->StartMin(), energy)),
energy_opt(energy),
argmax_energy_opt(kNone),
energetic_end_min_opt(energetic_end_min),
argmax_energetic_end_min_opt(kNone) {}
// Constructor for a single cumulative task in the Lambda set
LambdaThetaNode(int64_t capacity, const VariableCumulativeTask& task,
int index)
: energy(0LL),
energetic_end_min(std::numeric_limits<int64_t>::min()),
energy_opt(task.EnergyMin()),
argmax_energy_opt(index),
energetic_end_min_opt(capacity * task.interval->StartMin() +
energy_opt),
argmax_energetic_end_min_opt(index) {
DCHECK_GE(index, 0);
}
// Constructor for a single interval in the Theta set
explicit LambdaThetaNode(const IntervalVar* const interval)
: energy(interval->DurationMin()),
energetic_end_min(interval->EndMin()),
energy_opt(interval->DurationMin()),
argmax_energy_opt(kNone),
energetic_end_min_opt(interval->EndMin()),
argmax_energetic_end_min_opt(kNone) {}
// Constructor for a single interval in the Lambda set
// 'index' is the index of the given interval in the est vector
LambdaThetaNode(const IntervalVar* const interval, int index)
: energy(0LL),
energetic_end_min(std::numeric_limits<int64_t>::min()),
energy_opt(interval->DurationMin()),
argmax_energy_opt(index),
energetic_end_min_opt(interval->EndMin()),
argmax_energetic_end_min_opt(index) {
DCHECK_GE(index, 0);
}
// Sets this LambdaThetaNode to the result of the natural binary operations
// over the two given operands, corresponding to the following set operations:
// Theta = left.Theta union right.Theta
// Lambda = left.Lambda union right.Lambda
//
// No set operation actually occur: we only maintain the relevant quantities
// associated with such sets.
void Compute(const LambdaThetaNode& left, const LambdaThetaNode& right) {
energy = CapAdd(left.energy, right.energy);
energetic_end_min = std::max(right.energetic_end_min,
CapAdd(left.energetic_end_min, right.energy));
const int64_t energy_left_opt = CapAdd(left.energy_opt, right.energy);
const int64_t energy_right_opt = CapAdd(left.energy, right.energy_opt);
if (energy_left_opt > energy_right_opt) {
energy_opt = energy_left_opt;
argmax_energy_opt = left.argmax_energy_opt;
} else {
energy_opt = energy_right_opt;
argmax_energy_opt = right.argmax_energy_opt;
}
const int64_t ect1 = right.energetic_end_min_opt;
const int64_t ect2 = CapAdd(left.energetic_end_min, right.energy_opt);
const int64_t ect3 = CapAdd(left.energetic_end_min_opt, right.energy);
if (ect1 >= ect2 && ect1 >= ect3) { // ect1 max
energetic_end_min_opt = ect1;
argmax_energetic_end_min_opt = right.argmax_energetic_end_min_opt;
} else if (ect2 >= ect1 && ect2 >= ect3) { // ect2 max
energetic_end_min_opt = ect2;
argmax_energetic_end_min_opt = right.argmax_energy_opt;
} else { // ect3 max
energetic_end_min_opt = ect3;
argmax_energetic_end_min_opt = left.argmax_energetic_end_min_opt;
}
// The processing time, with one grey interval, should be no less than
// without any grey interval.
DCHECK(energy_opt >= energy);
// If there is no responsible grey interval for the processing time,
// the processing time with a grey interval should equal the one
// without.
DCHECK((argmax_energy_opt != kNone) || (energy_opt == energy));
}
// Amount of resource consumed by the Theta set, in units of demand X time.
// This is energy(Theta).
int64_t energy;
// Max_{subset S of Theta} (capacity * start_min(S) + energy(S))
int64_t energetic_end_min;
// Max_{i in Lambda} (energy(Theta union {i}))
int64_t energy_opt;
// The argmax in energy_opt_. It is the index of the chosen task in the Lambda
// set, if any, or kNone if none.
int argmax_energy_opt;
// Max_{subset S of Theta, i in Lambda}
// (capacity * start_min(S union {i}) + energy(S union {i}))
int64_t energetic_end_min_opt;
// The argmax in energetic_end_min_opt_. It is the index of the chosen task in
// the Lambda set, if any, or kNone if none.
int argmax_energetic_end_min_opt;
};
const int LambdaThetaNode::kNone = -1;
// Disjunctive Lambda-Theta tree
class DisjunctiveLambdaThetaTree : public MonoidOperationTree<LambdaThetaNode> {
public:
explicit DisjunctiveLambdaThetaTree(int size)
: MonoidOperationTree<LambdaThetaNode>(size) {}
void Insert(const DisjunctiveTask& task) {
Set(task.index, LambdaThetaNode(task.interval));
}
void Grey(const DisjunctiveTask& task) {
const int index = task.index;
Set(index, LambdaThetaNode(task.interval, index));
}
int64_t Ect() const { return result().energetic_end_min; }
int64_t EctOpt() const { return result().energetic_end_min_opt; }
int ResponsibleOpt() const { return result().argmax_energetic_end_min_opt; }
};
// A cumulative lambda-theta tree
class CumulativeLambdaThetaTree : public MonoidOperationTree<LambdaThetaNode> {
public:
CumulativeLambdaThetaTree(int size, int64_t capacity_max)
: MonoidOperationTree<LambdaThetaNode>(size),
capacity_max_(capacity_max) {}
void Init(int64_t capacity_max) {
Clear();
capacity_max_ = capacity_max;
}
void Insert(const CumulativeTask& task) {
Set(task.index, LambdaThetaNode(capacity_max_, task));
}
void Grey(const CumulativeTask& task) {
const int index = task.index;
Set(index, LambdaThetaNode(capacity_max_, task, index));
}
void Insert(const VariableCumulativeTask& task) {
Set(task.index, LambdaThetaNode(capacity_max_, task));
}
void Grey(const VariableCumulativeTask& task) {
const int index = task.index;
Set(index, LambdaThetaNode(capacity_max_, task, index));
}
int64_t energetic_end_min() const { return result().energetic_end_min; }
int64_t energetic_end_min_opt() const {
return result().energetic_end_min_opt;
}
int64_t Ect() const {
return MathUtil::CeilOfRatio(energetic_end_min(), capacity_max_);
}
int64_t EctOpt() const {
return MathUtil::CeilOfRatio(result().energetic_end_min_opt, capacity_max_);
}
int argmax_energetic_end_min_opt() const {
return result().argmax_energetic_end_min_opt;
}
private:
int64_t capacity_max_;
};
// -------------- Not Last -----------------------------------------
// A class that implements the 'Not-Last' propagation algorithm for the unary
// resource constraint.
class NotLast {
public:
NotLast(Solver* solver, const std::vector<IntervalVar*>& intervals,
bool mirror, bool strict);
~NotLast() { gtl::STLDeleteElements(&by_start_min_); }
bool Propagate();
private:
ThetaTree theta_tree_;
std::vector<DisjunctiveTask*> by_start_min_;
std::vector<DisjunctiveTask*> by_end_max_;
std::vector<DisjunctiveTask*> by_start_max_;
std::vector<int64_t> new_lct_;
const bool strict_;
};
NotLast::NotLast(Solver* const solver,
const std::vector<IntervalVar*>& intervals, bool mirror,
bool strict)
: theta_tree_(intervals.size()),
by_start_min_(intervals.size()),
by_end_max_(intervals.size()),
by_start_max_(intervals.size()),
new_lct_(intervals.size(), -1LL),
strict_(strict) {
// Populate the different vectors.
for (int i = 0; i < intervals.size(); ++i) {
IntervalVar* const underlying =
mirror ? solver->MakeMirrorInterval(intervals[i]) : intervals[i];
IntervalVar* const relaxed = solver->MakeIntervalRelaxedMin(underlying);
by_start_min_[i] = new DisjunctiveTask(relaxed);
by_end_max_[i] = by_start_min_[i];
by_start_max_[i] = by_start_min_[i];
}
}
bool NotLast::Propagate() {
// ---- Init ----
std::sort(by_start_max_.begin(), by_start_max_.end(),
StartMaxLessThan<DisjunctiveTask>);
std::sort(by_end_max_.begin(), by_end_max_.end(),
EndMaxLessThan<DisjunctiveTask>);
// Update start min positions
std::sort(by_start_min_.begin(), by_start_min_.end(),
StartMinLessThan<DisjunctiveTask>);
for (int i = 0; i < by_start_min_.size(); ++i) {
by_start_min_[i]->index = i;
}
theta_tree_.Clear();
for (int i = 0; i < by_start_min_.size(); ++i) {
new_lct_[i] = by_start_min_[i]->interval->EndMax();
}
// --- Execute ----
int j = 0;
for (DisjunctiveTask* const twi : by_end_max_) {
while (j < by_start_max_.size() &&
twi->interval->EndMax() > by_start_max_[j]->interval->StartMax()) {
if (j > 0 && theta_tree_.Ect() > by_start_max_[j]->interval->StartMax()) {
const int64_t new_end_max = by_start_max_[j - 1]->interval->StartMax();
new_lct_[by_start_max_[j]->index] =
std::min(new_lct_[by_start_max_[j]->index], new_end_max);
}
theta_tree_.Insert(by_start_max_[j]);
j++;
}
const bool inserted = theta_tree_.IsInserted(twi);
if (inserted) {
theta_tree_.Remove(twi);
}
const int64_t ect_theta_less_i = theta_tree_.Ect();
if (inserted) {
theta_tree_.Insert(twi);
}
if (ect_theta_less_i > twi->interval->StartMax() && j > 0) {
const int64_t new_end_max = by_start_max_[j - 1]->interval->StartMax();
if (new_end_max < new_lct_[twi->index]) {
new_lct_[twi->index] = new_end_max;
}
}
}
// Apply modifications
bool modified = false;
for (int i = 0; i < by_start_min_.size(); ++i) {
IntervalVar* const var = by_start_min_[i]->interval;
if ((strict_ || var->DurationMin() > 0) && var->EndMax() > new_lct_[i]) {
modified = true;
var->SetEndMax(new_lct_[i]);
}
}
return modified;
}
// ------ Edge finder + detectable precedences -------------
// A class that implements two propagation algorithms: edge finding and
// detectable precedences. These algorithms both push intervals to the right,
// which is why they are grouped together.
class EdgeFinderAndDetectablePrecedences {
public:
EdgeFinderAndDetectablePrecedences(Solver* solver,
const std::vector<IntervalVar*>& intervals,
bool mirror, bool strict);
~EdgeFinderAndDetectablePrecedences() {
gtl::STLDeleteElements(&by_start_min_);
}
int64_t size() const { return by_start_min_.size(); }
IntervalVar* interval(int index) { return by_start_min_[index]->interval; }
void UpdateEst();
void OverloadChecking();
bool DetectablePrecedences();
bool EdgeFinder();
private:
Solver* const solver_;
// --- All the following member variables are essentially used as local ones:
// no invariant is maintained about them, except for the fact that the vectors
// always contains all the considered intervals, so any function that wants to
// use them must first sort them in the right order.
// All of these vectors store the same set of objects. Therefore, at
// destruction time, STLDeleteElements should be called on only one of them.
// It does not matter which one.
ThetaTree theta_tree_;
std::vector<DisjunctiveTask*> by_end_min_;
std::vector<DisjunctiveTask*> by_start_min_;
std::vector<DisjunctiveTask*> by_end_max_;
std::vector<DisjunctiveTask*> by_start_max_;
// new_est_[i] is the new start min for interval est_[i]->interval.
std::vector<int64_t> new_est_;
// new_lct_[i] is the new end max for interval est_[i]->interval.
std::vector<int64_t> new_lct_;
DisjunctiveLambdaThetaTree lt_tree_;
const bool strict_;
};
EdgeFinderAndDetectablePrecedences::EdgeFinderAndDetectablePrecedences(
Solver* const solver, const std::vector<IntervalVar*>& intervals,
bool mirror, bool strict)
: solver_(solver),
theta_tree_(intervals.size()),
lt_tree_(intervals.size()),
strict_(strict) {
// Populate of the array of intervals
for (IntervalVar* const interval : intervals) {
IntervalVar* const underlying =
mirror ? solver->MakeMirrorInterval(interval) : interval;
IntervalVar* const relaxed = solver->MakeIntervalRelaxedMax(underlying);
DisjunctiveTask* const task = new DisjunctiveTask(relaxed);
by_end_min_.push_back(task);
by_start_min_.push_back(task);
by_end_max_.push_back(task);
by_start_max_.push_back(task);
new_est_.push_back(std::numeric_limits<int64_t>::min());
}
}
void EdgeFinderAndDetectablePrecedences::UpdateEst() {
std::sort(by_start_min_.begin(), by_start_min_.end(),
ShortestDurationStartMinLessThan<DisjunctiveTask>);
for (int i = 0; i < size(); ++i) {
by_start_min_[i]->index = i;
}
}
void EdgeFinderAndDetectablePrecedences::OverloadChecking() {
// Initialization.
UpdateEst();
std::sort(by_end_max_.begin(), by_end_max_.end(),
EndMaxLessThan<DisjunctiveTask>);
theta_tree_.Clear();
for (DisjunctiveTask* const task : by_end_max_) {
theta_tree_.Insert(task);
if (theta_tree_.Ect() > task->interval->EndMax()) {
solver_->Fail();
}
}
}
bool EdgeFinderAndDetectablePrecedences::DetectablePrecedences() {
// Initialization.
UpdateEst();
new_est_.assign(size(), std::numeric_limits<int64_t>::min());
// Propagate in one direction
std::sort(by_end_min_.begin(), by_end_min_.end(),
EndMinLessThan<DisjunctiveTask>);
std::sort(by_start_max_.begin(), by_start_max_.end(),
StartMaxLessThan<DisjunctiveTask>);
theta_tree_.Clear();
int j = 0;
for (DisjunctiveTask* const task_i : by_end_min_) {
if (j < size()) {
DisjunctiveTask* task_j = by_start_max_[j];
while (task_i->interval->EndMin() > task_j->interval->StartMax()) {
theta_tree_.Insert(task_j);
j++;
if (j == size()) break;
task_j = by_start_max_[j];
}
}
const int64_t esti = task_i->interval->StartMin();
bool inserted = theta_tree_.IsInserted(task_i);
if (inserted) {
theta_tree_.Remove(task_i);
}
const int64_t oesti = theta_tree_.Ect();
if (inserted) {
theta_tree_.Insert(task_i);
}
if (oesti > esti) {
new_est_[task_i->index] = oesti;
} else {
new_est_[task_i->index] = std::numeric_limits<int64_t>::min();
}
}
// Apply modifications
bool modified = false;
for (int i = 0; i < size(); ++i) {
IntervalVar* const var = by_start_min_[i]->interval;
if (new_est_[i] != std::numeric_limits<int64_t>::min() &&
(strict_ || var->DurationMin() > 0)) {
modified = true;
by_start_min_[i]->interval->SetStartMin(new_est_[i]);
}
}
return modified;
}
bool EdgeFinderAndDetectablePrecedences::EdgeFinder() {
// Initialization.
UpdateEst();
for (int i = 0; i < size(); ++i) {
new_est_[i] = by_start_min_[i]->interval->StartMin();
}
// Push in one direction.
std::sort(by_end_max_.begin(), by_end_max_.end(),
EndMaxLessThan<DisjunctiveTask>);
lt_tree_.Clear();
for (int i = 0; i < size(); ++i) {
lt_tree_.Insert(*by_start_min_[i]);
DCHECK_EQ(i, by_start_min_[i]->index);
}
for (int j = size() - 2; j >= 0; --j) {
lt_tree_.Grey(*by_end_max_[j + 1]);
DisjunctiveTask* const twj = by_end_max_[j];
// We should have checked for overloading earlier.
DCHECK_LE(lt_tree_.Ect(), twj->interval->EndMax());
while (lt_tree_.EctOpt() > twj->interval->EndMax()) {
const int i = lt_tree_.ResponsibleOpt();
DCHECK_GE(i, 0);
if (lt_tree_.Ect() > new_est_[i]) {
new_est_[i] = lt_tree_.Ect();
}
lt_tree_.Reset(i);
}
}
// Apply modifications.
bool modified = false;
for (int i = 0; i < size(); ++i) {
IntervalVar* const var = by_start_min_[i]->interval;
if (var->StartMin() < new_est_[i] && (strict_ || var->DurationMin() > 0)) {
modified = true;
var->SetStartMin(new_est_[i]);
}
}
return modified;
}
// --------- Disjunctive Constraint ----------
// ----- Propagation on ranked activities -----
class RankedPropagator : public Constraint {
public:
RankedPropagator(Solver* const solver, const std::vector<IntVar*>& nexts,
const std::vector<IntervalVar*>& intervals,
const std::vector<IntVar*>& slacks,
DisjunctiveConstraint* const disjunctive)
: Constraint(solver),
nexts_(nexts),
intervals_(intervals),
slacks_(slacks),
disjunctive_(disjunctive),
partial_sequence_(intervals.size()),
previous_(intervals.size() + 2, 0) {}
~RankedPropagator() override {}
void Post() override {
Demon* const delayed =
solver()->MakeDelayedConstraintInitialPropagateCallback(this);
for (int i = 0; i < intervals_.size(); ++i) {
nexts_[i]->WhenBound(delayed);
intervals_[i]->WhenAnything(delayed);
slacks_[i]->WhenRange(delayed);
}
nexts_.back()->WhenBound(delayed);
}
void InitialPropagate() override {
PropagateNexts();
PropagateSequence();
}
void PropagateNexts() {
Solver* const s = solver();
const int ranked_first = partial_sequence_.NumFirstRanked();
const int ranked_last = partial_sequence_.NumLastRanked();
const int sentinel =
ranked_last == 0
? nexts_.size()
: partial_sequence_[intervals_.size() - ranked_last] + 1;
int first = 0;
int counter = 0;
while (nexts_[first]->Bound()) {
DCHECK_NE(first, nexts_[first]->Min());
first = nexts_[first]->Min();
if (first == sentinel) {
return;
}
if (++counter > ranked_first) {
DCHECK(intervals_[first - 1]->MayBePerformed());
partial_sequence_.RankFirst(s, first - 1);
VLOG(2) << "RankFirst " << first - 1 << " -> "
<< partial_sequence_.DebugString();
}
}
previous_.assign(previous_.size(), -1);
for (int i = 0; i < nexts_.size(); ++i) {
if (nexts_[i]->Bound()) {
previous_[nexts_[i]->Min()] = i;
}
}
int last = previous_.size() - 1;
counter = 0;
while (previous_[last] != -1) {
last = previous_[last];
if (++counter > ranked_last) {
partial_sequence_.RankLast(s, last - 1);
VLOG(2) << "RankLast " << last - 1 << " -> "
<< partial_sequence_.DebugString();
}
}
}
void PropagateSequence() {
const int last_position = intervals_.size() - 1;
const int first_sentinel = partial_sequence_.NumFirstRanked();
const int last_sentinel = last_position - partial_sequence_.NumLastRanked();
// Propagates on ranked first from left to right.
for (int i = 0; i < first_sentinel - 1; ++i) {
IntervalVar* const interval = RankedInterval(i);
IntervalVar* const next_interval = RankedInterval(i + 1);
IntVar* const slack = RankedSlack(i);
const int64_t transition_time = RankedTransitionTime(i, i + 1);
next_interval->SetStartRange(
CapAdd(interval->StartMin(), CapAdd(slack->Min(), transition_time)),
CapAdd(interval->StartMax(), CapAdd(slack->Max(), transition_time)));
}
// Propagates on ranked last from right to left.
for (int i = last_position; i > last_sentinel + 1; --i) {
IntervalVar* const interval = RankedInterval(i - 1);
IntervalVar* const next_interval = RankedInterval(i);
IntVar* const slack = RankedSlack(i - 1);
const int64_t transition_time = RankedTransitionTime(i - 1, i);
interval->SetStartRange(CapSub(next_interval->StartMin(),
CapAdd(slack->Max(), transition_time)),
CapSub(next_interval->StartMax(),
CapAdd(slack->Min(), transition_time)));
}
// Propagate across.
IntervalVar* const first_interval =
first_sentinel > 0 ? RankedInterval(first_sentinel - 1) : nullptr;
IntVar* const first_slack =
first_sentinel > 0 ? RankedSlack(first_sentinel - 1) : nullptr;
IntervalVar* const last_interval = last_sentinel < last_position
? RankedInterval(last_sentinel + 1)
: nullptr;
// Nothing to do afterwards, exiting.
if (first_interval == nullptr && last_interval == nullptr) {
return;
}
// Propagates to the middle part.
// This assumes triangular inequality in the transition times.
for (int i = first_sentinel; i <= last_sentinel; ++i) {
IntervalVar* const interval = RankedInterval(i);
IntVar* const slack = RankedSlack(i);
if (interval->MayBePerformed()) {
const bool performed = interval->MustBePerformed();
if (first_interval != nullptr) {
const int64_t transition_time =
RankedTransitionTime(first_sentinel - 1, i);
interval->SetStartRange(
CapAdd(first_interval->StartMin(),
CapAdd(first_slack->Min(), transition_time)),
CapAdd(first_interval->StartMax(),
CapAdd(first_slack->Max(), transition_time)));
if (performed) {
first_interval->SetStartRange(
CapSub(interval->StartMin(),
CapAdd(first_slack->Max(), transition_time)),
CapSub(interval->StartMax(),
CapAdd(first_slack->Min(), transition_time)));
}
}
if (last_interval != nullptr) {
const int64_t transition_time =
RankedTransitionTime(i, last_sentinel + 1);
interval->SetStartRange(
CapSub(last_interval->StartMin(),
CapAdd(slack->Max(), transition_time)),
CapSub(last_interval->StartMax(),
CapAdd(slack->Min(), transition_time)));
if (performed) {
last_interval->SetStartRange(
CapAdd(interval->StartMin(),
CapAdd(slack->Min(), transition_time)),
CapAdd(interval->StartMax(),
CapAdd(slack->Max(), transition_time)));
}
}
}
}
// TODO(user): cache transition on ranked intervals in a vector.
// Propagates on ranked first from right to left.
for (int i = std::min(first_sentinel - 2, last_position - 1); i >= 0; --i) {
IntervalVar* const interval = RankedInterval(i);
IntervalVar* const next_interval = RankedInterval(i + 1);
IntVar* const slack = RankedSlack(i);
const int64_t transition_time = RankedTransitionTime(i, i + 1);
interval->SetStartRange(CapSub(next_interval->StartMin(),
CapAdd(slack->Max(), transition_time)),
CapSub(next_interval->StartMax(),
CapAdd(slack->Min(), transition_time)));
}
// Propagates on ranked last from left to right.
for (int i = last_sentinel + 1; i < last_position - 1; ++i) {
IntervalVar* const interval = RankedInterval(i);
IntervalVar* const next_interval = RankedInterval(i + 1);
IntVar* const slack = RankedSlack(i);
const int64_t transition_time = RankedTransitionTime(i, i + 1);
next_interval->SetStartRange(
CapAdd(interval->StartMin(), CapAdd(slack->Min(), transition_time)),
CapAdd(interval->StartMax(), CapAdd(slack->Max(), transition_time)));
}
// TODO(user) : Propagate on slacks.
}
IntervalVar* RankedInterval(int i) const {
const int index = partial_sequence_[i];
return intervals_[index];
}
IntVar* RankedSlack(int i) const {
const int index = partial_sequence_[i];
return slacks_[index];
}
int64_t RankedTransitionTime(int before, int after) const {
const int before_index = partial_sequence_[before];
const int after_index = partial_sequence_[after];
return disjunctive_->TransitionTime(before_index, after_index);
}
std::string DebugString() const override {
return absl::StrFormat(
"RankedPropagator([%s], nexts = [%s], intervals = [%s])",
partial_sequence_.DebugString(), JoinDebugStringPtr(nexts_, ", "),
JoinDebugStringPtr(intervals_, ", "));
}
void Accept(ModelVisitor* const visitor) const override {
LOG(FATAL) << "Not yet implemented";
// TODO(user): IMPLEMENT ME.
}
private:
std::vector<IntVar*> nexts_;
std::vector<IntervalVar*> intervals_;
std::vector<IntVar*> slacks_;
DisjunctiveConstraint* const disjunctive_;
RevPartialSequence partial_sequence_;
std::vector<int> previous_;
};
// A class that stores several propagators for the sequence constraint, and
// calls them until a fixpoint is reached.
class FullDisjunctiveConstraint : public DisjunctiveConstraint {
public:
FullDisjunctiveConstraint(Solver* const s,
const std::vector<IntervalVar*>& intervals,
const std::string& name, bool strict)
: DisjunctiveConstraint(s, intervals, name),
sequence_var_(nullptr),
straight_(s, intervals, false, strict),
mirror_(s, intervals, true, strict),
straight_not_last_(s, intervals, false, strict),
mirror_not_last_(s, intervals, true, strict),
strict_(strict) {}
// This type is neither copyable nor movable.
FullDisjunctiveConstraint(const FullDisjunctiveConstraint&) = delete;
FullDisjunctiveConstraint& operator=(const FullDisjunctiveConstraint&) =
delete;
~FullDisjunctiveConstraint() override {}
void Post() override {
Demon* const d = MakeDelayedConstraintDemon0(
solver(), this, &FullDisjunctiveConstraint::InitialPropagate,
"InitialPropagate");
for (int32_t i = 0; i < straight_.size(); ++i) {
straight_.interval(i)->WhenAnything(d);
}
}
void InitialPropagate() override {
bool all_optional_or_unperformed = true;
for (const IntervalVar* const interval : intervals_) {
if (interval->MustBePerformed()) {
all_optional_or_unperformed = false;
break;
}
}
if (all_optional_or_unperformed) { // Nothing to deduce
return;
}
bool all_times_fixed = true;
for (const IntervalVar* const interval : intervals_) {
if (interval->MayBePerformed() &&
(interval->StartMin() != interval->StartMax() ||
interval->DurationMin() != interval->DurationMax() ||
interval->EndMin() != interval->EndMax())) {
all_times_fixed = false;
break;
}