forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
disjunctive.cc
1357 lines (1216 loc) · 52.5 KB
/
disjunctive.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/disjunctive.h"
#include <memory>
#include "ortools/base/iterator_adaptors.h"
#include "ortools/base/logging.h"
#include "ortools/sat/all_different.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/timetable.h"
#include "ortools/util/sort.h"
namespace operations_research {
namespace sat {
std::function<void(Model*)> Disjunctive(
const std::vector<IntervalVariable>& vars) {
return [=](Model* model) {
bool is_all_different = true;
IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
for (const IntervalVariable var : vars) {
if (repository->IsOptional(var) || repository->MinSize(var) != 1 ||
repository->MaxSize(var) != 1) {
is_all_different = false;
break;
}
}
if (is_all_different) {
std::vector<IntegerVariable> starts;
starts.reserve(vars.size());
for (const IntervalVariable var : vars) {
starts.push_back(model->Get(StartVar(var)));
}
model->Add(AllDifferentOnBounds(starts));
return;
}
auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
const auto& sat_parameters = *model->GetOrCreate<SatParameters>();
if (vars.size() > 2 && sat_parameters.use_combined_no_overlap()) {
model->GetOrCreate<CombinedDisjunctive<true>>()->AddNoOverlap(vars);
model->GetOrCreate<CombinedDisjunctive<false>>()->AddNoOverlap(vars);
return;
}
SchedulingConstraintHelper* helper =
new SchedulingConstraintHelper(vars, model);
model->TakeOwnership(helper);
// Experiments to use the timetable only to propagate the disjunctive.
if (/*DISABLES_CODE*/ (false)) {
const IntegerVariable capacity = model->Add(ConstantIntegerVariable(1));
std::vector<IntegerVariable> demands(vars.size(), capacity);
TimeTablingPerTask* timetable = new TimeTablingPerTask(
demands, capacity, model->GetOrCreate<IntegerTrail>(), helper);
timetable->RegisterWith(watcher);
model->TakeOwnership(timetable);
return;
}
if (vars.size() == 2) {
DisjunctiveWithTwoItems* propagator = new DisjunctiveWithTwoItems(helper);
propagator->RegisterWith(watcher);
model->TakeOwnership(propagator);
} else {
// We decided to create the propagators in this particular order, but it
// shouldn't matter much because of the different priorities used.
{
// Only one direction is needed by this one.
DisjunctiveOverloadChecker* overload_checker =
new DisjunctiveOverloadChecker(helper);
const int id = overload_checker->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 1);
model->TakeOwnership(overload_checker);
}
for (const bool time_direction : {true, false}) {
DisjunctiveDetectablePrecedences* detectable_precedences =
new DisjunctiveDetectablePrecedences(time_direction, helper);
const int id = detectable_precedences->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 2);
model->TakeOwnership(detectable_precedences);
}
for (const bool time_direction : {true, false}) {
DisjunctiveNotLast* not_last =
new DisjunctiveNotLast(time_direction, helper);
const int id = not_last->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 3);
model->TakeOwnership(not_last);
}
for (const bool time_direction : {true, false}) {
DisjunctiveEdgeFinding* edge_finding =
new DisjunctiveEdgeFinding(time_direction, helper);
const int id = edge_finding->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 4);
model->TakeOwnership(edge_finding);
}
}
// Note that we keep this one even when there is just two intervals. This is
// because it might push a variable that is after both of the intervals
// using the fact that they are in disjunction.
if (sat_parameters.use_precedences_in_disjunctive_constraint() &&
!sat_parameters.use_combined_no_overlap()) {
for (const bool time_direction : {true, false}) {
DisjunctivePrecedences* precedences = new DisjunctivePrecedences(
time_direction, helper, model->GetOrCreate<IntegerTrail>(),
model->GetOrCreate<PrecedencesPropagator>());
const int id = precedences->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 5);
model->TakeOwnership(precedences);
}
}
};
}
std::function<void(Model*)> DisjunctiveWithBooleanPrecedencesOnly(
const std::vector<IntervalVariable>& vars) {
return [=](Model* model) {
SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
PrecedencesPropagator* precedences =
model->GetOrCreate<PrecedencesPropagator>();
for (int i = 0; i < vars.size(); ++i) {
for (int j = 0; j < i; ++j) {
const BooleanVariable boolean_var = sat_solver->NewBooleanVariable();
const Literal i_before_j = Literal(boolean_var, true);
const Literal j_before_i = i_before_j.Negated();
precedences->AddConditionalPrecedence(repository->EndVar(vars[i]),
repository->StartVar(vars[j]),
i_before_j);
precedences->AddConditionalPrecedence(repository->EndVar(vars[j]),
repository->StartVar(vars[i]),
j_before_i);
}
}
};
}
std::function<void(Model*)> DisjunctiveWithBooleanPrecedences(
const std::vector<IntervalVariable>& vars) {
return [=](Model* model) {
model->Add(DisjunctiveWithBooleanPrecedencesOnly(vars));
model->Add(Disjunctive(vars));
};
}
void TaskSet::AddEntry(const Entry& e) {
int j = sorted_tasks_.size();
sorted_tasks_.push_back(e);
while (j > 0 && sorted_tasks_[j - 1].start_min > e.start_min) {
sorted_tasks_[j] = sorted_tasks_[j - 1];
--j;
}
sorted_tasks_[j] = e;
DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
// If the task is added after optimized_restart_, we know that we don't need
// to scan the task before optimized_restart_ in the next ComputeEndMin().
if (j <= optimized_restart_) optimized_restart_ = 0;
}
void TaskSet::NotifyEntryIsNowLastIfPresent(const Entry& e) {
const int size = sorted_tasks_.size();
for (int i = 0;; ++i) {
if (i == size) return;
if (sorted_tasks_[i].task == e.task) {
sorted_tasks_.erase(sorted_tasks_.begin() + i);
break;
}
}
optimized_restart_ = sorted_tasks_.size();
sorted_tasks_.push_back(e);
DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
}
void TaskSet::RemoveEntryWithIndex(int index) {
sorted_tasks_.erase(sorted_tasks_.begin() + index);
optimized_restart_ = 0;
}
IntegerValue TaskSet::ComputeEndMin() const {
DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
const int size = sorted_tasks_.size();
IntegerValue end_min = kMinIntegerValue;
for (int i = optimized_restart_; i < size; ++i) {
const Entry& e = sorted_tasks_[i];
if (e.start_min >= end_min) {
optimized_restart_ = i;
end_min = e.start_min + e.duration_min;
} else {
end_min += e.duration_min;
}
}
return end_min;
}
IntegerValue TaskSet::ComputeEndMin(int task_to_ignore,
int* critical_index) const {
// The order in which we process tasks with the same start-min doesn't matter.
DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
bool ignored = false;
const int size = sorted_tasks_.size();
IntegerValue end_min = kMinIntegerValue;
// If the ignored task is last and was the start of the critical block, then
// we need to reset optimized_restart_.
if (optimized_restart_ + 1 == size &&
sorted_tasks_[optimized_restart_].task == task_to_ignore) {
optimized_restart_ = 0;
}
for (int i = optimized_restart_; i < size; ++i) {
const Entry& e = sorted_tasks_[i];
if (e.task == task_to_ignore) {
ignored = true;
continue;
}
if (e.start_min >= end_min) {
*critical_index = i;
if (!ignored) optimized_restart_ = i;
end_min = e.start_min + e.duration_min;
} else {
end_min += e.duration_min;
}
}
return end_min;
}
bool DisjunctiveWithTwoItems::Propagate() {
DCHECK_EQ(helper_->NumTasks(), 2);
// We can't propagate anything if one of the interval is absent for sure.
if (helper_->IsAbsent(0) || helper_->IsAbsent(1)) return true;
// Note that this propagation also take care of the "overload checker" part.
// It also propagates as much as possible, even in the presence of task with
// variable durations.
//
// TODO(user): For optional interval whose presense in unknown and without
// optional variable, the end-min may not be propagated to at least (start_min
// + duration_min). Consider that into the computation so we may decide the
// interval forced absence? Same for the start-max.
int task_before = 0;
int task_after = 1;
if (helper_->StartMax(0) < helper_->EndMin(1)) {
// Task 0 must be before task 1.
} else if (helper_->StartMax(1) < helper_->EndMin(0)) {
// Task 1 must be before task 0.
std::swap(task_before, task_after);
} else {
return true;
}
if (helper_->IsPresent(task_before)) {
const IntegerValue end_min_before = helper_->EndMin(task_before);
if (helper_->StartMin(task_after) < end_min_before) {
// Reason for precedences if both present.
helper_->ClearReason();
helper_->AddReasonForBeingBefore(task_before, task_after);
// Reason for the bound push.
helper_->AddPresenceReason(task_before);
helper_->AddEndMinReason(task_before, end_min_before);
if (!helper_->IncreaseStartMin(task_after, end_min_before)) {
return false;
}
}
}
if (helper_->IsPresent(task_after)) {
const IntegerValue start_max_after = helper_->StartMax(task_after);
if (helper_->EndMax(task_before) > start_max_after) {
// Reason for precedences if both present.
helper_->ClearReason();
helper_->AddReasonForBeingBefore(task_before, task_after);
// Reason for the bound push.
helper_->AddPresenceReason(task_after);
helper_->AddStartMaxReason(task_after, start_max_after);
if (!helper_->DecreaseEndMax(task_before, start_max_after)) {
return false;
}
}
}
return true;
}
int DisjunctiveWithTwoItems::RegisterWith(GenericLiteralWatcher* watcher) {
// This propagator reach the fix point in one pass.
const int id = watcher->Register(this);
helper_->WatchAllTasks(id, watcher);
return id;
}
template <bool time_direction>
CombinedDisjunctive<time_direction>::CombinedDisjunctive(Model* model)
: helper_(model->GetOrCreate<AllIntervalsHelper>()) {
helper_->SetTimeDirection(time_direction);
task_to_disjunctives_.resize(helper_->NumTasks());
auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
const int id = watcher->Register(this);
helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/true,
/*watch_end_max=*/false);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
}
template <bool time_direction>
void CombinedDisjunctive<time_direction>::AddNoOverlap(
const std::vector<IntervalVariable>& vars) {
const int index = task_sets_.size();
task_sets_.emplace_back(vars.size());
end_mins_.push_back(kMinIntegerValue);
for (const IntervalVariable var : vars) {
task_to_disjunctives_[var.value()].push_back(index);
}
}
template <bool time_direction>
bool CombinedDisjunctive<time_direction>::Propagate() {
helper_->SetTimeDirection(time_direction);
const auto& task_by_increasing_end_min = helper_->TaskByIncreasingEndMin();
const auto& task_by_decreasing_start_max =
helper_->TaskByDecreasingStartMax();
for (auto& task_set : task_sets_) task_set.Clear();
end_mins_.assign(end_mins_.size(), kMinIntegerValue);
IntegerValue max_of_end_min = kMinIntegerValue;
const int num_tasks = helper_->NumTasks();
task_is_added_.assign(num_tasks, false);
int queue_index = num_tasks - 1;
for (const auto task_time : task_by_increasing_end_min) {
const int t = task_time.task_index;
const IntegerValue end_min = task_time.time;
if (helper_->IsAbsent(t)) continue;
// Update all task sets.
while (queue_index >= 0) {
const auto to_insert = task_by_decreasing_start_max[queue_index];
const int task_index = to_insert.task_index;
const IntegerValue start_max = to_insert.time;
if (end_min <= start_max) break;
if (helper_->IsPresent(task_index)) {
task_is_added_[task_index] = true;
const IntegerValue shifted_smin = helper_->ShiftedStartMin(task_index);
const IntegerValue duration_min = helper_->DurationMin(task_index);
for (const int d_index : task_to_disjunctives_[task_index]) {
// TODO(user): AddEntry() and ComputeEndMin() could be combined.
task_sets_[d_index].AddEntry(
{task_index, shifted_smin, duration_min});
end_mins_[d_index] = task_sets_[d_index].ComputeEndMin();
max_of_end_min = std::max(max_of_end_min, end_mins_[d_index]);
}
}
--queue_index;
}
// Find out amongst the disjunctives in which t appear, the one with the
// largest end_min, ignoring t itself. This will be the new start min for t.
IntegerValue new_start_min = helper_->StartMin(t);
if (new_start_min >= max_of_end_min) continue;
int best_critical_index = 0;
int best_d_index = -1;
if (task_is_added_[t]) {
for (const int d_index : task_to_disjunctives_[t]) {
if (new_start_min >= end_mins_[d_index]) continue;
int critical_index = 0;
const IntegerValue end_min_of_critical_tasks =
task_sets_[d_index].ComputeEndMin(/*task_to_ignore=*/t,
&critical_index);
DCHECK_LE(end_min_of_critical_tasks, max_of_end_min);
if (end_min_of_critical_tasks > new_start_min) {
new_start_min = end_min_of_critical_tasks;
best_d_index = d_index;
best_critical_index = critical_index;
}
}
} else {
// If the task t was not added, then there is no task to ignore and
// end_mins_[d_index] is up to date.
for (const int d_index : task_to_disjunctives_[t]) {
if (end_mins_[d_index] > new_start_min) {
new_start_min = end_mins_[d_index];
best_d_index = d_index;
}
}
if (best_d_index != -1) {
const IntegerValue end_min_of_critical_tasks =
task_sets_[best_d_index].ComputeEndMin(/*task_to_ignore=*/t,
&best_critical_index);
CHECK_EQ(end_min_of_critical_tasks, new_start_min);
}
}
// Do we push something?
if (best_d_index == -1) continue;
// Same reason as DisjunctiveDetectablePrecedences.
// TODO(user): Maybe factor out the code? It does require a function with a
// lot of arguments though.
helper_->ClearReason();
const std::vector<TaskSet::Entry>& sorted_tasks =
task_sets_[best_d_index].SortedTasks();
const IntegerValue window_start =
sorted_tasks[best_critical_index].start_min;
for (int i = best_critical_index; i < sorted_tasks.size(); ++i) {
const int ct = sorted_tasks[i].task;
if (ct == t) continue;
helper_->AddPresenceReason(ct);
helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
window_start);
helper_->AddStartMaxReason(ct, end_min - 1);
}
helper_->AddEndMinReason(t, end_min);
if (!helper_->IncreaseStartMin(t, new_start_min)) {
return false;
}
// We need to reorder t inside task_set_. Note that if t is in the set,
// it means that the task is present and that IncreaseStartMin() did push
// its start (by opposition to an optional interval where the push might
// not happen if its start is not optional).
if (task_is_added_[t]) {
const IntegerValue shifted_smin = helper_->ShiftedStartMin(t);
const IntegerValue duration_min = helper_->DurationMin(t);
for (const int d_index : task_to_disjunctives_[t]) {
task_sets_[d_index].NotifyEntryIsNowLastIfPresent(
{t, shifted_smin, duration_min});
end_mins_[d_index] = task_sets_[d_index].ComputeEndMin();
max_of_end_min = std::max(max_of_end_min, end_mins_[d_index]);
}
}
}
return true;
}
bool DisjunctiveOverloadChecker::Propagate() {
helper_->SetTimeDirection(/*is_forward=*/true);
// Split problem into independent part.
//
// Many propagators in this file use the same approach, we start by processing
// the task by increasing start-min, packing everything to the left. We then
// process each "independent" set of task separately. A task is independent
// from the one before it, if its start-min wasn't pushed.
//
// This way, we get one or more window [window_start, window_end] so that for
// all task in the window, [start_min, end_min] is inside the window, and the
// end min of any set of task to the left is <= window_start, and the
// start_min of any task to the right is >= end_min.
window_.clear();
IntegerValue window_end = kMinIntegerValue;
IntegerValue relevant_end;
int relevant_size = 0;
for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
const int task = task_time.task_index;
if (helper_->IsAbsent(task)) continue;
const IntegerValue start_min = task_time.time;
if (start_min < window_end) {
window_.push_back(task_time);
window_end += helper_->DurationMin(task);
if (window_end > helper_->EndMax(task)) {
relevant_size = window_.size();
relevant_end = window_end;
}
continue;
}
// Process current window.
// We don't need to process the end of the window (after relevant_size)
// because these interval can be greedily assembled in a feasible solution.
window_.resize(relevant_size);
if (relevant_size > 0 && !PropagateSubwindow(relevant_end)) {
return false;
}
// Start of the next window.
window_.clear();
window_.push_back(task_time);
window_end = start_min + helper_->DurationMin(task);
relevant_size = 0;
}
// Process last window.
window_.resize(relevant_size);
if (relevant_size > 0 && !PropagateSubwindow(relevant_end)) {
return false;
}
return true;
}
// TODO(user): Improve the Overload Checker using delayed insertion.
// We insert events at the cost of O(log n) per insertion, and this is where
// the algorithm spends most of its time, thus it is worth improving.
// We can insert an arbitrary set of tasks at the cost of O(n) for the whole
// set. This is useless for the overload checker as is since we need to check
// overload after every insertion, but we could use an upper bound of the
// theta envelope to save us from checking the actual value.
bool DisjunctiveOverloadChecker::PropagateSubwindow(
IntegerValue global_window_end) {
// Set up theta tree and task_by_increasing_end_max_.
const int window_size = window_.size();
theta_tree_.Reset(window_size);
task_by_increasing_end_max_.clear();
for (int i = 0; i < window_size; ++i) {
// No point adding a task if its end_max is too large.
const int task = window_[i].task_index;
const IntegerValue end_max = helper_->EndMax(task);
if (end_max < global_window_end) {
task_to_event_[task] = i;
task_by_increasing_end_max_.push_back({task, end_max});
}
}
// Introduce events by increasing end_max, check for overloads.
std::sort(task_by_increasing_end_max_.begin(),
task_by_increasing_end_max_.end());
for (const auto task_time : task_by_increasing_end_max_) {
const int current_task = task_time.task_index;
// We filtered absent task while constructing the subwindow, but it is
// possible that as we propagate task absence below, other task also become
// absent (if they share the same presence Boolean).
if (helper_->IsAbsent(current_task)) continue;
DCHECK_NE(task_to_event_[current_task], -1);
{
const int current_event = task_to_event_[current_task];
const IntegerValue energy_min = helper_->DurationMin(current_task);
if (helper_->IsPresent(current_task)) {
// TODO(user,user): Add max energy deduction for variable
// durations by putting the energy_max here and modifying the code
// dealing with the optional envelope greater than current_end below.
theta_tree_.AddOrUpdateEvent(current_event, window_[current_event].time,
energy_min, energy_min);
} else {
theta_tree_.AddOrUpdateOptionalEvent(
current_event, window_[current_event].time, energy_min);
}
}
const IntegerValue current_end = task_time.time;
if (theta_tree_.GetEnvelope() > current_end) {
// Explain failure with tasks in critical interval.
helper_->ClearReason();
const int critical_event =
theta_tree_.GetMaxEventWithEnvelopeGreaterThan(current_end);
const IntegerValue window_start = window_[critical_event].time;
const IntegerValue window_end =
theta_tree_.GetEnvelopeOf(critical_event) - 1;
for (int event = critical_event; event < window_size; event++) {
const IntegerValue energy_min = theta_tree_.EnergyMin(event);
if (energy_min > 0) {
const int task = window_[event].task_index;
helper_->AddPresenceReason(task);
helper_->AddEnergyAfterReason(task, energy_min, window_start);
helper_->AddEndMaxReason(task, window_end);
}
}
return helper_->ReportConflict();
}
// Exclude all optional tasks that would overload an interval ending here.
while (theta_tree_.GetOptionalEnvelope() > current_end) {
// Explain exclusion with tasks present in the critical interval.
// TODO(user): This could be done lazily, like most of the loop to
// compute the reasons in this file.
helper_->ClearReason();
int critical_event;
int optional_event;
IntegerValue available_energy;
theta_tree_.GetEventsWithOptionalEnvelopeGreaterThan(
current_end, &critical_event, &optional_event, &available_energy);
const int optional_task = window_[optional_event].task_index;
const IntegerValue optional_duration_min =
helper_->DurationMin(optional_task);
const IntegerValue window_start = window_[critical_event].time;
const IntegerValue window_end =
current_end + optional_duration_min - available_energy - 1;
for (int event = critical_event; event < window_size; event++) {
const IntegerValue energy_min = theta_tree_.EnergyMin(event);
if (energy_min > 0) {
const int task = window_[event].task_index;
helper_->AddPresenceReason(task);
helper_->AddEnergyAfterReason(task, energy_min, window_start);
helper_->AddEndMaxReason(task, window_end);
}
}
helper_->AddEnergyAfterReason(optional_task, optional_duration_min,
window_start);
helper_->AddEndMaxReason(optional_task, window_end);
// If tasks shares the same presence literal, it is possible that we
// already pushed this task absence.
if (!helper_->IsAbsent(optional_task)) {
if (!helper_->PushTaskAbsence(optional_task)) return false;
}
theta_tree_.RemoveEvent(optional_event);
}
}
return true;
}
int DisjunctiveOverloadChecker::RegisterWith(GenericLiteralWatcher* watcher) {
// This propagator reach the fix point in one pass.
const int id = watcher->Register(this);
helper_->SetTimeDirection(/*is_forward=*/true);
helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/false,
/*watch_end_max=*/true);
return id;
}
bool DisjunctiveDetectablePrecedences::Propagate() {
helper_->SetTimeDirection(time_direction_);
to_propagate_.clear();
processed_.assign(helper_->NumTasks(), false);
// Split problem into independent part.
//
// The "independent" window can be processed separately because for each of
// them, a task [start-min, end-min] is in the window [window_start,
// window_end]. So any task to the left of the window cannot push such
// task start_min, and any task to the right of the window will have a
// start_max >= end_min, so wouldn't be in detectable precedence.
window_.clear();
IntegerValue window_end = kMinIntegerValue;
IntegerValue window_max_of_end_min = kMinIntegerValue;
for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
const int task = task_time.task_index;
if (helper_->IsAbsent(task)) continue;
// TODO(user): It should actually be the real start_min here not the shifted
// one. Otherwise we might miss some propagation. Try to unit-test this!
const IntegerValue start_min = task_time.time;
if (start_min < window_end) {
const IntegerValue duration_min = helper_->DurationMin(task);
const IntegerValue end_min = helper_->EndMin(task);
window_.push_back({task, end_min});
window_end += duration_min;
window_max_of_end_min = std::max(window_max_of_end_min, end_min);
continue;
}
// Process current window.
if (window_.size() > 1 && !PropagateSubwindow(window_max_of_end_min)) {
return false;
}
// Start of the next window.
window_.clear();
const IntegerValue duration_min = helper_->DurationMin(task);
const IntegerValue end_min = helper_->EndMin(task);
window_.push_back({task, end_min});
window_end = start_min + duration_min;
window_max_of_end_min = end_min;
}
if (window_.size() > 1 && !PropagateSubwindow(window_max_of_end_min)) {
return false;
}
return true;
}
bool DisjunctiveDetectablePrecedences::PropagateSubwindow(
IntegerValue max_end_min) {
task_by_increasing_start_max_.clear();
for (const TaskTime entry : window_) {
const int task = entry.task_index;
const IntegerValue start_max = helper_->StartMax(task);
if (start_max < max_end_min && helper_->IsPresent(task)) {
task_by_increasing_start_max_.push_back({task, start_max});
}
}
if (task_by_increasing_start_max_.empty()) return true;
std::sort(task_by_increasing_start_max_.begin(),
task_by_increasing_start_max_.end());
// The window is already sorted by shifted_start_min, so there is likely a
// good correlation, hence the incremental sort.
//
// TODO(user): Instead of end-min, we should use end-min if present. Same in
// other places.
auto& task_by_increasing_end_min = window_;
IncrementalSort(task_by_increasing_end_min.begin(),
task_by_increasing_end_min.end());
// Invariant: need_update is false implies that task_set_end_min is equal to
// task_set_.ComputeEndMin().
//
// TODO(user): Maybe it is just faster to merge ComputeEndMin() with
// AddEntry().
task_set_.Clear();
bool need_update = false;
IntegerValue task_set_end_min = kMinIntegerValue;
int queue_index = 0;
int blocking_task = -1;
const int queue_size = task_by_increasing_start_max_.size();
for (const auto task_time : task_by_increasing_end_min) {
const int current_task = task_time.task_index;
DCHECK(!helper_->IsAbsent(current_task));
for (; queue_index < queue_size; ++queue_index) {
const auto to_insert = task_by_increasing_start_max_[queue_index];
const IntegerValue start_max = to_insert.time;
const IntegerValue current_end_min = task_time.time;
if (current_end_min <= start_max) break;
const int t = to_insert.task_index;
DCHECK(helper_->IsPresent(t));
// If t has not been processed yet, it has a mandatory part, and rather
// than adding it right away to task_set, we will delay all propagation
// until current_task is equal to this "blocking task".
//
// This idea is introduced in "Linear-Time Filtering Algorithms for the
// Disjunctive Constraints" Hamed Fahimi, Claude-Guy Quimper.
//
// Experiments seems to indicate that it is slighlty faster rather than
// having to ignore one of the task already inserted into task_set_ when
// we have tasks with mandatory parts. It also open-up more option for the
// data structure used in task_set_.
if (!processed_[t]) {
if (blocking_task != -1) {
// We have two blocking tasks, which means they are in conflict.
helper_->ClearReason();
helper_->AddPresenceReason(blocking_task);
helper_->AddPresenceReason(t);
helper_->AddReasonForBeingBefore(blocking_task, t);
helper_->AddReasonForBeingBefore(t, blocking_task);
return helper_->ReportConflict();
}
DCHECK_LT(start_max, helper_->EndMin(t));
DCHECK(to_propagate_.empty());
blocking_task = t;
to_propagate_.push_back(t);
} else {
need_update = true;
task_set_.AddEntry(
{t, helper_->ShiftedStartMin(t), helper_->DurationMin(t)});
}
}
// If we have a blocking task, we delay the propagation until current_task
// is the blocking task.
if (blocking_task != current_task) {
to_propagate_.push_back(current_task);
if (blocking_task != -1) continue;
}
for (const int t : to_propagate_) {
DCHECK(!processed_[t]);
processed_[t] = true;
if (need_update) {
need_update = false;
task_set_end_min = task_set_.ComputeEndMin();
}
// task_set_ contains all the tasks that must be executed before t. They
// are in "detectable precedence" because their start_max is smaller than
// the end-min of t like so:
// [(the task t)
// (a task in task_set_)]
// From there, we deduce that the start-min of t is greater or equal to
// the end-min of the critical tasks.
//
// Note that this works as well when IsPresent(t) is false.
if (task_set_end_min > helper_->StartMin(t)) {
const int critical_index = task_set_.GetCriticalIndex();
const std::vector<TaskSet::Entry>& sorted_tasks =
task_set_.SortedTasks();
helper_->ClearReason();
// We need:
// - StartMax(ct) < EndMin(t) for the detectable precedence.
// - StartMin(ct) >= window_start for the value of task_set_end_min.
const IntegerValue end_min = helper_->EndMin(t);
const IntegerValue window_start =
sorted_tasks[critical_index].start_min;
for (int i = critical_index; i < sorted_tasks.size(); ++i) {
const int ct = sorted_tasks[i].task;
DCHECK_NE(ct, t);
helper_->AddPresenceReason(ct);
helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
window_start);
helper_->AddStartMaxReason(ct, end_min - 1);
}
// Add the reason for t (we only need the end-min).
helper_->AddEndMinReason(t, end_min);
// This augment the start-min of t. Note that t is not in task set
// yet, so we will use this updated start if we ever add it there.
if (!helper_->IncreaseStartMin(t, task_set_end_min)) {
return false;
}
}
if (t == blocking_task) {
// Insert the blocking_task. Note that because we just pushed it,
// it will be last in task_set_ and also the only reason used to push
// any of the subsequent tasks. In particular, the reason will be valid
// even though task_set might contains tasks with a start_max greater or
// equal to the end_min of the task we push.
need_update = true;
blocking_task = -1;
task_set_.AddEntry(
{t, helper_->ShiftedStartMin(t), helper_->DurationMin(t)});
}
}
to_propagate_.clear();
}
return true;
}
int DisjunctiveDetectablePrecedences::RegisterWith(
GenericLiteralWatcher* watcher) {
const int id = watcher->Register(this);
helper_->SetTimeDirection(time_direction_);
helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/true,
/*watch_end_max=*/false);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
return id;
}
bool DisjunctivePrecedences::Propagate() {
helper_->SetTimeDirection(time_direction_);
window_.clear();
IntegerValue window_end = kMinIntegerValue;
for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
const int task = task_time.task_index;
if (!helper_->IsPresent(task)) continue;
const IntegerValue start_min = task_time.time;
if (start_min < window_end) {
window_.push_back(task_time);
window_end += helper_->DurationMin(task);
continue;
}
if (window_.size() > 1 && !PropagateSubwindow()) {
return false;
}
// Start of the next window.
window_.clear();
window_.push_back(task_time);
window_end = start_min + helper_->DurationMin(task);
}
if (window_.size() > 1 && !PropagateSubwindow()) {
return false;
}
return true;
}
bool DisjunctivePrecedences::PropagateSubwindow() {
index_to_end_vars_.clear();
for (const auto task_time : window_) {
const int task = task_time.task_index;
index_to_end_vars_.push_back(helper_->EndVars()[task]);
}
precedences_->ComputePrecedences(index_to_end_vars_, &before_);
const int size = before_.size();
for (int i = 0; i < size;) {
const IntegerVariable var = before_[i].var;
DCHECK_NE(var, kNoIntegerVariable);
task_set_.Clear();
const int initial_i = i;
IntegerValue min_offset = before_[i].offset;
for (; i < size && before_[i].var == var; ++i) {
const TaskTime task_time = window_[before_[i].index];
min_offset = std::min(min_offset, before_[i].offset);
// The task are actually in sorted order, so we do not need to call
// task_set_.Sort(). This property is DCHECKed.
task_set_.AddUnsortedEntry({task_time.task_index, task_time.time,
helper_->DurationMin(task_time.task_index)});
}
DCHECK_GE(task_set_.SortedTasks().size(), 2);
if (integer_trail_->IsCurrentlyIgnored(var)) continue;
// TODO(user): Only use the min_offset of the critical task? Or maybe do a
// more general computation to find by how much we can push var?
const IntegerValue new_lb = task_set_.ComputeEndMin() + min_offset;
if (new_lb > integer_trail_->LowerBound(var)) {
const std::vector<TaskSet::Entry>& sorted_tasks = task_set_.SortedTasks();
helper_->ClearReason();
// Fill task_to_arc_index_ since we need it for the reason.
// Note that we do not care about the initial content of this vector.
for (int j = initial_i; j < i; ++j) {
const int task = window_[before_[j].index].task_index;
task_to_arc_index_[task] = before_[j].arc_index;
}
const int critical_index = task_set_.GetCriticalIndex();
const IntegerValue window_start = sorted_tasks[critical_index].start_min;
for (int i = critical_index; i < sorted_tasks.size(); ++i) {
const int ct = sorted_tasks[i].task;
helper_->AddPresenceReason(ct);
helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
window_start);
precedences_->AddPrecedenceReason(task_to_arc_index_[ct], min_offset,
helper_->MutableLiteralReason(),
helper_->MutableIntegerReason());
}
// TODO(user): If var is actually a start-min of an interval, we
// could push the end-min and check the interval consistency right away.
if (!helper_->PushIntegerLiteral(
IntegerLiteral::GreaterOrEqual(var, new_lb))) {
return false;
}
}
}
return true;
}
int DisjunctivePrecedences::RegisterWith(GenericLiteralWatcher* watcher) {
// This propagator reach the fixed point in one go.
const int id = watcher->Register(this);
helper_->SetTimeDirection(time_direction_);
helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/false,
/*watch_end_max=*/false);
return id;
}
bool DisjunctiveNotLast::Propagate() {
helper_->SetTimeDirection(time_direction_);
const auto& task_by_decreasing_start_max =
helper_->TaskByDecreasingStartMax();
const auto& task_by_increasing_shifted_start_min =
helper_->TaskByIncreasingShiftedStartMin();
// Split problem into independent part.
//
// The situation is trickier here, and we use two windows:
// - The classical "start_min_window_" as in the other propagator.
// - A second window, that includes all the task with a start_max inside
// [window_start, window_end].
//
// Now, a task from the second window can be detected to be "not last" by only
// looking at the task in the first window. Tasks to the left do not cause
// issue for the task to be last, and tasks to the right will not lower the
// end-min of the task under consideration.
int queue_index = task_by_decreasing_start_max.size() - 1;
const int num_tasks = task_by_increasing_shifted_start_min.size();
for (int i = 0; i < num_tasks;) {
start_min_window_.clear();
IntegerValue window_end = kMinIntegerValue;
for (; i < num_tasks; ++i) {
const TaskTime task_time = task_by_increasing_shifted_start_min[i];
const int task = task_time.task_index;
if (!helper_->IsPresent(task)) continue;
const IntegerValue start_min = task_time.time;
if (start_min_window_.empty()) {
start_min_window_.push_back(task_time);
window_end = start_min + helper_->DurationMin(task);
} else if (start_min < window_end) {
start_min_window_.push_back(task_time);
window_end += helper_->DurationMin(task);
} else {
break;
}
}
// Add to start_max_window_ all the task whose start_max
// fall into [window_start, window_end).
start_max_window_.clear();
for (; queue_index >= 0; queue_index--) {
const auto task_time = task_by_decreasing_start_max[queue_index];
// Note that we add task whose presence is still unknown here.