forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjunctive.cc
1814 lines (1617 loc) · 68.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-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 "ortools/sat/disjunctive.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/log/check.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/sat/all_different.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/intervals.h"
#include "ortools/sat/model.h"
#include "ortools/sat/precedences.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/theta_tree.h"
#include "ortools/sat/timetable.h"
#include "ortools/util/sort.h"
#include "ortools/util/strong_integers.h"
namespace operations_research {
namespace sat {
void AddDisjunctive(const std::vector<IntervalVariable>& intervals,
Model* model) {
// Depending on the parameters, create all pair of conditional precedences.
// TODO(user): create them dynamically instead?
const auto& params = *model->GetOrCreate<SatParameters>();
if (intervals.size() <=
params.max_size_to_create_precedence_literals_in_disjunctive() &&
params.use_strong_propagation_in_disjunctive()) {
AddDisjunctiveWithBooleanPrecedencesOnly(intervals, model);
}
bool is_all_different = true;
IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
for (const IntervalVariable var : intervals) {
if (repository->IsOptional(var) || repository->MinSize(var) != 1 ||
repository->MaxSize(var) != 1) {
is_all_different = false;
break;
}
}
if (is_all_different) {
std::vector<AffineExpression> starts;
starts.reserve(intervals.size());
for (const IntervalVariable interval : intervals) {
starts.push_back(repository->Start(interval));
}
model->Add(AllDifferentOnBounds(starts));
return;
}
auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
if (intervals.size() > 2 && params.use_combined_no_overlap()) {
model->GetOrCreate<CombinedDisjunctive<true>>()->AddNoOverlap(intervals);
model->GetOrCreate<CombinedDisjunctive<false>>()->AddNoOverlap(intervals);
return;
}
SchedulingConstraintHelper* helper = repository->GetOrCreateHelper(
intervals, /*register_as_disjunctive_helper=*/true);
// Experiments to use the timetable only to propagate the disjunctive.
if (/*DISABLES_CODE*/ (false)) {
const AffineExpression one(IntegerValue(1));
std::vector<AffineExpression> demands(intervals.size(), one);
SchedulingDemandHelper* demands_helper =
repository->GetOrCreateDemandHelper(helper, demands);
TimeTablingPerTask* timetable =
new TimeTablingPerTask(one, helper, demands_helper, model);
timetable->RegisterWith(watcher);
model->TakeOwnership(timetable);
return;
}
if (intervals.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.
if (!params.use_strong_propagation_in_disjunctive()) {
// This one will not propagate anything if we added all precedence
// literals since the linear propagator will already do that in that case.
DisjunctiveSimplePrecedences* simple_precedences =
new DisjunctiveSimplePrecedences(helper, model);
const int id = simple_precedences->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 1);
model->TakeOwnership(simple_precedences);
}
{
// Only one direction is needed by this one.
DisjunctiveOverloadChecker* overload_checker =
new DisjunctiveOverloadChecker(helper, model);
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, model);
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, model);
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, model);
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 (params.use_precedences_in_disjunctive_constraint() &&
!params.use_combined_no_overlap()) {
for (const bool time_direction : {true, false}) {
DisjunctivePrecedences* precedences =
new DisjunctivePrecedences(time_direction, helper, model);
const int id = precedences->RegisterWith(watcher);
watcher->SetPropagatorPriority(id, 5);
model->TakeOwnership(precedences);
}
}
}
void AddDisjunctiveWithBooleanPrecedencesOnly(
const std::vector<IntervalVariable>& intervals, Model* model) {
auto* repo = model->GetOrCreate<IntervalsRepository>();
for (int i = 0; i < intervals.size(); ++i) {
for (int j = i + 1; j < intervals.size(); ++j) {
repo->CreateDisjunctivePrecedenceLiteral(intervals[i], intervals[j]);
}
}
}
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::AddShiftedStartMinEntry(const SchedulingConstraintHelper& helper,
int t) {
const IntegerValue dmin = helper.SizeMin(t);
AddEntry({t, std::max(helper.StartMin(t), helper.EndMin(t) - dmin), dmin});
}
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) {
for (int j = i; j + 1 < size; ++j) {
sorted_tasks_[j] = sorted_tasks_[j + 1];
}
sorted_tasks_.pop_back();
break;
}
}
optimized_restart_ = sorted_tasks_.size();
sorted_tasks_.push_back(e);
DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
}
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.size_min;
} else {
end_min += e.size_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.size_min;
} else {
end_min += e.size_min;
}
}
return end_min;
}
bool DisjunctiveWithTwoItems::Propagate() {
DCHECK_EQ(helper_->NumTasks(), 2);
if (!helper_->SynchronizeAndSetTimeDirection(true)) return false;
// 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 sizes.
//
// TODO(user): For optional interval whose presence in unknown and without
// optional variable, the end-min may not be propagated to at least (start_min
// + size_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) {
const int id = watcher->Register(this);
helper_->WatchAllTasks(id);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
return id;
}
template <bool time_direction>
CombinedDisjunctive<time_direction>::CombinedDisjunctive(Model* model)
: helper_(model->GetOrCreate<AllIntervalsHelper>()) {
task_to_disjunctives_.resize(helper_->NumTasks());
auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
const int id = watcher->Register(this);
helper_->WatchAllTasks(id);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
}
template <bool time_direction>
void CombinedDisjunctive<time_direction>::AddNoOverlap(
absl::Span<const 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() {
if (!helper_->SynchronizeAndSetTimeDirection(time_direction)) return false;
const auto& task_by_increasing_end_min = helper_->TaskByIncreasingEndMin();
const auto& task_by_negated_start_max =
helper_->TaskByIncreasingNegatedStartMax();
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_negated_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 size_min = helper_->SizeMin(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, size_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 absl::Span<const 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].size_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 size_min = helper_->SizeMin(t);
for (const int d_index : task_to_disjunctives_[t]) {
// TODO(user): Refactor the code to use the same algo as in
// DisjunctiveDetectablePrecedences, it is superior and do not need
// this function.
task_sets_[d_index].NotifyEntryIsNowLastIfPresent(
{t, shifted_smin, size_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() {
stats_.OnPropagate();
if (!helper_->SynchronizeAndSetTimeDirection(/*is_forward=*/true)) {
++stats_.num_conflicts;
return false;
}
// We use this to detect precedence between task that must cause a push.
TaskTime task_with_max_end_min = {0, kMinIntegerValue};
// 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.
IntegerValue window_end = kMinIntegerValue;
IntegerValue relevant_end;
int window_size = 0;
int relevant_size = 0;
TaskTime* const window = window_.get();
for (const auto [task, presence_lit, start_min] :
helper_->TaskByIncreasingShiftedStartMin()) {
if (helper_->IsAbsent(presence_lit)) continue;
// Nothing to do with overload checking, but almost free to do that here.
const IntegerValue size_min = helper_->SizeMin(task);
const IntegerValue end_min = start_min + size_min;
const IntegerValue start_max = helper_->StartMax(task);
if (start_max < task_with_max_end_min.time &&
helper_->IsPresent(presence_lit) && size_min > 0) {
// We have a detectable precedence that must cause a push.
//
// Remarks: If we added all precedence literals + linear relation, this
// propagation would have been done by the linear propagator, but if we
// didn't add such relations yet, it is beneficial to detect that here!
//
// TODO(user): Actually, we just infered a "not last" so we could check
// for relevant_size > 2 potential propagation?
//
// TODO(user): Can we detect and propagate all such relations easily and
// do a pass before this maybe? On a related note, because this
// propagator is not instantiated in both direction, we might miss some
// easy propag.
const int to_push = task_with_max_end_min.task_index;
helper_->ClearReason();
helper_->AddPresenceReason(task);
helper_->AddReasonForBeingBefore(task, to_push);
helper_->AddEndMinReason(task, end_min);
if (!helper_->IncreaseStartMin(to_push, end_min)) {
++stats_.num_conflicts;
return false;
}
// TODO(user): Shall we keep propagating? we know the prefix didn't
// change, so we could be faster here. On another hand, it might be
// better to propagate all the linear constraints before returning
// here.
++stats_.num_propagations;
stats_.EndWithoutConflicts();
return true;
}
// Note that we need to do that AFTER the block above.
if (end_min > task_with_max_end_min.time) {
task_with_max_end_min = {task, end_min};
}
// Extend window.
if (start_min < window_end) {
window[window_size++] = {task, start_min};
if (window_end > start_max) {
window_end += size_min;
relevant_size = window_size;
relevant_end = window_end;
} else {
window_end += size_min;
}
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.
if (relevant_size > 0 && !PropagateSubwindow(relevant_size, relevant_end)) {
++stats_.num_conflicts;
return false;
}
// Start of the next window.
window_size = 0;
window[window_size++] = {task, start_min};
window_end = start_min + size_min;
relevant_size = 0;
}
// Process last window.
if (relevant_size > 0 && !PropagateSubwindow(relevant_size, relevant_end)) {
++stats_.num_conflicts;
return false;
}
stats_.EndWithoutConflicts();
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(
int relevant_size, IntegerValue global_window_end) {
// Set up theta tree and task_by_increasing_end_max_.
int num_events = 0;
task_by_increasing_end_max_.clear();
for (int i = 0; i < relevant_size; ++i) {
// No point adding a task if its end_max is too large.
const TaskTime& task_time = window_[i];
const int task = task_time.task_index;
// We use the shifted end-max.
const IntegerValue end_max =
helper_->StartMax(task) + helper_->SizeMin(task);
if (end_max < global_window_end) {
window_[num_events] = task_time;
task_to_event_[task] = num_events;
task_by_increasing_end_max_.push_back({task, end_max});
++num_events;
}
}
if (num_events <= 1) return true;
theta_tree_.Reset(num_events);
// Introduce events by increasing end_max, check for overloads.
// If end_max is the same, we want to add high start-min first.
absl::c_reverse(task_by_increasing_end_max_);
absl::c_stable_sort(task_by_increasing_end_max_);
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_->SizeMin(current_task);
if (helper_->IsPresent(current_task)) {
// TODO(user): Add max energy deduction for variable
// sizes 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 < num_events; 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_->AddShiftedEndMaxReason(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;
// If tasks shares the same presence literal, it is possible that we
// already pushed this task absence.
if (!helper_->IsAbsent(optional_task)) {
const IntegerValue optional_size_min = helper_->SizeMin(optional_task);
const IntegerValue window_start = window_[critical_event].time;
const IntegerValue window_end =
current_end + optional_size_min - available_energy - 1;
for (int event = critical_event; event < num_events; 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_->AddShiftedEndMaxReason(task, window_end);
}
}
helper_->AddEnergyAfterReason(optional_task, optional_size_min,
window_start);
helper_->AddShiftedEndMaxReason(optional_task, window_end);
++stats_.num_propagations;
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);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
helper_->WatchAllTasks(id);
return id;
}
int DisjunctiveSimplePrecedences::RegisterWith(GenericLiteralWatcher* watcher) {
const int id = watcher->Register(this);
helper_->WatchAllTasks(id);
watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
return id;
}
bool DisjunctiveSimplePrecedences::Propagate() {
stats_.OnPropagate();
const bool current_direction = helper_->CurrentTimeIsForward();
for (const bool direction : {current_direction, !current_direction}) {
if (!helper_->SynchronizeAndSetTimeDirection(direction)) {
++stats_.num_conflicts;
return false;
}
if (!PropagateOneDirection()) {
++stats_.num_conflicts;
return false;
}
}
stats_.EndWithoutConflicts();
return true;
}
bool DisjunctiveSimplePrecedences::Push(TaskTime before, int t) {
const int t_before = before.task_index;
DCHECK_NE(t_before, t);
helper_->ClearReason();
helper_->AddPresenceReason(t_before);
helper_->AddReasonForBeingBefore(t_before, t);
helper_->AddEndMinReason(t_before, before.time);
if (!helper_->IncreaseStartMin(t, before.time)) {
return false;
}
++stats_.num_propagations;
return true;
}
bool DisjunctiveSimplePrecedences::PropagateOneDirection() {
// We will loop in a decreasing way here.
// And add tasks that are present to the task_set_.
absl::Span<const TaskTime> task_by_negated_start_max =
helper_->TaskByIncreasingNegatedStartMax();
// We just keep amongst all the task before current_end_min, the one with the
// highesh end-min.
TaskTime best_task_before = {-1, kMinIntegerValue};
// We will loop in an increasing way here and consume task from beginning.
absl::Span<const TaskTime> task_by_increasing_end_min =
helper_->TaskByIncreasingEndMin();
for (; !task_by_increasing_end_min.empty();) {
// Skip absent task.
if (helper_->IsAbsent(task_by_increasing_end_min.front().task_index)) {
task_by_increasing_end_min.remove_prefix(1);
continue;
}
// Consider all task with a start_max < current_end_min.
int blocking_task = -1;
IntegerValue blocking_start_max;
IntegerValue current_end_min = task_by_increasing_end_min.front().time;
for (; true; task_by_negated_start_max.remove_suffix(1)) {
if (task_by_negated_start_max.empty()) {
// Small optim: this allows to process all remaining task rather than
// looping around are retesting this for all remaining tasks.
current_end_min = kMaxIntegerValue;
break;
}
const auto [t, negated_start_max] = task_by_negated_start_max.back();
const IntegerValue start_max = -negated_start_max;
if (current_end_min <= start_max) break;
if (!helper_->IsPresent(t)) continue;
// If t has a mandatory part, and extend further than current_end_min
// then we can push it first. All tasks for which their push is delayed
// are necessarily after this "blocking task".
//
// This idea is introduced in "Linear-Time Filtering Algorithms for the
// Disjunctive Constraints" Hamed Fahimi, Claude-Guy Quimper.
const IntegerValue end_min = helper_->EndMin(t);
if (blocking_task == -1 && end_min >= current_end_min) {
DCHECK_LT(start_max, end_min) << " task should have mandatory part: "
<< helper_->TaskDebugString(t);
blocking_task = t;
blocking_start_max = start_max;
current_end_min = end_min;
} else if (blocking_task != -1 && blocking_start_max < end_min) {
// Conflict! the task is after the blocking_task but also before.
helper_->ClearReason();
helper_->AddPresenceReason(blocking_task);
helper_->AddPresenceReason(t);
helper_->AddReasonForBeingBefore(blocking_task, t);
helper_->AddReasonForBeingBefore(t, blocking_task);
return helper_->ReportConflict();
} else if (end_min > best_task_before.time) {
best_task_before = {t, end_min};
}
}
// If we have a blocking task. We need to propagate it first.
if (blocking_task != -1) {
DCHECK(!helper_->IsAbsent(blocking_task));
if (best_task_before.time > helper_->StartMin(blocking_task)) {
if (!Push(best_task_before, blocking_task)) return false;
}
// Update best_task_before.
//
// Note that we want the blocking task here as it is the only one
// guaranteed to be before all the task we push below. If we are not in a
// propagation loop, it should also be the best.
const IntegerValue end_min = helper_->EndMin(blocking_task);
best_task_before = {blocking_task, end_min};
}
// Lets propagate all task after best_task_before.
for (; !task_by_increasing_end_min.empty();
task_by_increasing_end_min.remove_prefix(1)) {
const auto [t, end_min] = task_by_increasing_end_min.front();
if (end_min > current_end_min) break;
if (t == blocking_task) continue; // Already done.
// Lets propagate current_task.
if (best_task_before.time > helper_->StartMin(t)) {
// Corner case if a previous push caused a subsequent task to be absent.
if (helper_->IsAbsent(t)) continue;
if (!Push(best_task_before, t)) return false;
}
}
}
return true;
}
bool DisjunctiveDetectablePrecedences::Propagate() {
stats_.OnPropagate();
if (!helper_->SynchronizeAndSetTimeDirection(time_direction_)) {
++stats_.num_conflicts;
return false;
}
// Compute the "rank" of each task.
const auto by_shifted_smin = helper_->TaskByIncreasingShiftedStartMin();
int rank = -1;
IntegerValue window_end = kMinIntegerValue;
for (const auto [task, presence_lit, start_min] : by_shifted_smin) {
if (!helper_->IsPresent(presence_lit)) {
ranks_[task] = -1;
continue;
}
const IntegerValue size_min = helper_->SizeMin(task);
if (start_min < window_end) {
ranks_[task] = rank;
window_end += size_min;
} else {
ranks_[task] = ++rank;
window_end = start_min + size_min;
}
}
if (!PropagateWithRanks()) {
++stats_.num_conflicts;
return false;
}
stats_.EndWithoutConflicts();
return true;
}
// 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.
bool DisjunctiveDetectablePrecedences::Push(IntegerValue task_set_end_min,
int t) {
const int critical_index = task_set_.GetCriticalIndex();
const absl::Span<const 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_if_present =
helper_->ShiftedStartMin(t) + helper_->SizeMin(t);
const IntegerValue window_start = sorted_tasks[critical_index].start_min;
IntegerValue min_slack = kMaxIntegerValue;
bool all_already_before = true;
IntegerValue energy_of_task_before = 0;
for (int i = critical_index; i < sorted_tasks.size(); ++i) {
const int ct = sorted_tasks[i].task;
DCHECK_NE(ct, t);
helper_->AddPresenceReason(ct);
// Heuristic, if some tasks are known to be after the first one,
// we just add the min-size as a reason.
if (i > critical_index && helper_->GetCurrentMinDistanceBetweenTasks(
sorted_tasks[critical_index].task, ct,
/*add_reason_if_after=*/true) >= 0) {
helper_->AddSizeMinReason(ct);
} else {
helper_->AddEnergyAfterReason(ct, sorted_tasks[i].size_min, window_start);
}
// We only need the reason for being before if we don't already have
// a static precedence between the tasks.
const IntegerValue dist = helper_->GetCurrentMinDistanceBetweenTasks(
ct, t, /*add_reason_if_after=*/true);
if (dist >= 0) {
energy_of_task_before += sorted_tasks[i].size_min;
min_slack = std::min(min_slack, dist);
} else {
all_already_before = false;
helper_->AddStartMaxReason(ct, end_min_if_present - 1);
}
}
// We only need the end-min of t if not all the task are already known
// to be before.
IntegerValue new_start_min = task_set_end_min;
if (all_already_before) {
// We can actually push further!
// And we don't need other reason except the precedences.
new_start_min += min_slack;
} else {
helper_->AddEndMinReason(t, end_min_if_present);
}
// In some situation, we can push the task further.
// TODO(user): We can also reduce the reason in this case.
if (min_slack != kMaxIntegerValue &&
window_start + energy_of_task_before + min_slack > new_start_min) {
new_start_min = window_start + energy_of_task_before + min_slack;
}
// Process detected precedence.
if (helper_->CurrentDecisionLevel() == 0 && helper_->IsPresent(t)) {
for (int i = critical_index; i < sorted_tasks.size(); ++i) {
if (!helper_->PropagatePrecedence(sorted_tasks[i].task, t)) {
return false;
}
}
}
// 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.
++stats_.num_propagations;
if (!helper_->IncreaseStartMin(t, new_start_min)) {
return false;
}
return true;
}
bool DisjunctiveDetectablePrecedences::PropagateWithRanks() {
// We will "consume" tasks from here.
absl::Span<const TaskTime> task_by_increasing_end_min =
helper_->TaskByIncreasingEndMin();
absl::Span<const TaskTime> task_by_negated_start_max =
helper_->TaskByIncreasingNegatedStartMax();
// We will stop using ranks as soon as we propagated something. This allow to
// be sure this propagate as much as possible in a single pass and seems to
// help slightly.
int highest_rank = 0;
bool some_propagation = false;
// 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();
to_add_.clear();
IntegerValue task_set_end_min = kMinIntegerValue;
for (; !task_by_increasing_end_min.empty();) {
// Consider all task with a start_max < current_end_min.
int blocking_task = -1;
IntegerValue blocking_start_max;
IntegerValue current_end_min = task_by_increasing_end_min.front().time;
for (; true; task_by_negated_start_max.remove_suffix(1)) {
if (task_by_negated_start_max.empty()) {
// Small optim: this allows to process all remaining task rather than