-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathintervals.cc
1264 lines (1127 loc) · 46.7 KB
/
intervals.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/intervals.h"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/strong_vector.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_expr.h"
#include "ortools/sat/linear_constraint.h"
#include "ortools/sat/model.h"
#include "ortools/sat/precedences.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/util/sort.h"
#include "ortools/util/strong_integers.h"
namespace operations_research {
namespace sat {
IntervalVariable IntervalsRepository::CreateInterval(IntegerVariable start,
IntegerVariable end,
IntegerVariable size,
IntegerValue fixed_size,
LiteralIndex is_present) {
return CreateInterval(AffineExpression(start), AffineExpression(end),
size == kNoIntegerVariable
? AffineExpression(fixed_size)
: AffineExpression(size),
is_present, /*add_linear_relation=*/true);
}
IntervalVariable IntervalsRepository::CreateInterval(AffineExpression start,
AffineExpression end,
AffineExpression size,
LiteralIndex is_present,
bool add_linear_relation) {
// Create the interval.
const IntervalVariable i(starts_.size());
starts_.push_back(start);
ends_.push_back(end);
sizes_.push_back(size);
is_present_.push_back(is_present);
std::vector<Literal> enforcement_literals;
if (is_present != kNoLiteralIndex) {
enforcement_literals.push_back(Literal(is_present));
}
if (add_linear_relation) {
LinearConstraintBuilder builder(model_, IntegerValue(0), IntegerValue(0));
builder.AddTerm(Start(i), IntegerValue(1));
builder.AddTerm(Size(i), IntegerValue(1));
builder.AddTerm(End(i), IntegerValue(-1));
LoadConditionalLinearConstraint(enforcement_literals, builder.Build(),
model_);
}
return i;
}
void IntervalsRepository::CreateDisjunctivePrecedenceLiteral(
IntervalVariable a, IntervalVariable b) {
if (disjunctive_precedences_.contains({a, b})) return;
std::vector<Literal> enforcement_literals;
if (IsOptional(a)) enforcement_literals.push_back(PresenceLiteral(a));
if (IsOptional(b)) enforcement_literals.push_back(PresenceLiteral(b));
if (sat_solver_->CurrentDecisionLevel() == 0) {
int new_size = 0;
for (const Literal l : enforcement_literals) {
// We can ignore always absent interval, and skip the literal of the
// interval that are now always present.
if (assignment_.LiteralIsTrue(l)) continue;
if (assignment_.LiteralIsFalse(l)) return;
enforcement_literals[new_size++] = l;
}
enforcement_literals.resize(new_size);
}
const AffineExpression start_a = Start(a);
const AffineExpression end_a = End(a);
const AffineExpression start_b = Start(b);
const AffineExpression end_b = End(b);
// task_a is always before task_b ?
if (integer_trail_->UpperBound(start_a) < integer_trail_->LowerBound(end_b)) {
AddConditionalAffinePrecedence(enforcement_literals, end_a, start_b,
model_);
return;
}
// task_b is always before task_a ?
if (integer_trail_->UpperBound(start_b) < integer_trail_->LowerBound(end_a)) {
AddConditionalAffinePrecedence(enforcement_literals, end_b, start_a,
model_);
return;
}
// Create a new literal.
const BooleanVariable boolean_var = sat_solver_->NewBooleanVariable();
const Literal a_before_b = Literal(boolean_var, true);
disjunctive_precedences_.insert({{a, b}, a_before_b});
disjunctive_precedences_.insert({{b, a}, a_before_b.Negated()});
// Also insert it in precedences.
// TODO(user): also add the reverse like start_b + 1 <= end_a if negated?
precedences_.insert({{end_a, start_b}, a_before_b});
precedences_.insert({{end_b, start_a}, a_before_b.Negated()});
enforcement_literals.push_back(a_before_b);
AddConditionalAffinePrecedence(enforcement_literals, end_a, start_b, model_);
enforcement_literals.pop_back();
enforcement_literals.push_back(a_before_b.Negated());
AddConditionalAffinePrecedence(enforcement_literals, end_b, start_a, model_);
enforcement_literals.pop_back();
// Force the value of boolean_var in case the precedence is not active. This
// avoids duplicate solutions when enumerating all possible solutions.
for (const Literal l : enforcement_literals) {
implications_->AddBinaryClause(l, a_before_b);
}
}
bool IntervalsRepository::CreatePrecedenceLiteral(IntervalVariable a,
IntervalVariable b) {
const AffineExpression x = End(a);
const AffineExpression y = Start(b);
if (precedences_.contains({x, y})) return false;
// We want l => x <= y and not(l) => x > y <=> y + 1 <= x
// Do not create l if the relation is always true or false.
if (integer_trail_->UpperBound(x) <= integer_trail_->LowerBound(y)) {
return false;
}
if (integer_trail_->LowerBound(x) > integer_trail_->UpperBound(y)) {
return false;
}
// Create a new literal.
const BooleanVariable boolean_var = sat_solver_->NewBooleanVariable();
const Literal x_before_y = Literal(boolean_var, true);
// TODO(user): Also add {{y_plus_one, x}, x_before_y.Negated()} ?
precedences_.insert({{x, y}, x_before_y});
AffineExpression y_plus_one = y;
y_plus_one.constant += 1;
AddConditionalAffinePrecedence({x_before_y}, x, y, model_);
AddConditionalAffinePrecedence({x_before_y.Negated()}, y_plus_one, x, model_);
return true;
}
LiteralIndex IntervalsRepository::GetPrecedenceLiteral(
IntervalVariable a, IntervalVariable b) const {
const AffineExpression x = End(a);
const AffineExpression y = Start(b);
const auto it = precedences_.find({x, y});
if (it != precedences_.end()) return it->second.Index();
return kNoLiteralIndex;
}
// TODO(user): Ideally we should sort the vector of variables, but right now
// we cannot since we often use this with a parallel vector of demands. So this
// "sorting" should happen in the presolver so we can share as much as possible.
SchedulingConstraintHelper* IntervalsRepository::GetOrCreateHelper(
const std::vector<IntervalVariable>& variables,
bool register_as_disjunctive_helper) {
const auto it = helper_repository_.find(variables);
if (it != helper_repository_.end()) return it->second;
SchedulingConstraintHelper* helper =
new SchedulingConstraintHelper(variables, model_);
helper_repository_[variables] = helper;
model_->TakeOwnership(helper);
if (register_as_disjunctive_helper) {
disjunctive_helpers_.push_back(helper);
}
return helper;
}
SchedulingDemandHelper* IntervalsRepository::GetOrCreateDemandHelper(
SchedulingConstraintHelper* helper,
absl::Span<const AffineExpression> demands) {
const std::pair<SchedulingConstraintHelper*, std::vector<AffineExpression>>
key = {helper,
std::vector<AffineExpression>(demands.begin(), demands.end())};
const auto it = demand_helper_repository_.find(key);
if (it != demand_helper_repository_.end()) return it->second;
SchedulingDemandHelper* demand_helper =
new SchedulingDemandHelper(demands, helper, model_);
model_->TakeOwnership(demand_helper);
demand_helper_repository_[key] = demand_helper;
return demand_helper;
}
void IntervalsRepository::InitAllDecomposedEnergies() {
for (const auto& it : demand_helper_repository_) {
it.second->InitDecomposedEnergies();
}
}
SchedulingConstraintHelper::SchedulingConstraintHelper(
const std::vector<IntervalVariable>& tasks, Model* model)
: model_(model),
trail_(model->GetOrCreate<Trail>()),
sat_solver_(model->GetOrCreate<SatSolver>()),
integer_trail_(model->GetOrCreate<IntegerTrail>()),
watcher_(model->GetOrCreate<GenericLiteralWatcher>()),
precedence_relations_(model->GetOrCreate<PrecedenceRelations>()),
interval_variables_(tasks),
capacity_(tasks.size()),
cached_size_min_(new IntegerValue[capacity_]),
cached_start_min_(new IntegerValue[capacity_]),
cached_end_min_(new IntegerValue[capacity_]),
cached_negated_start_max_(new IntegerValue[capacity_]),
cached_negated_end_max_(new IntegerValue[capacity_]),
cached_shifted_start_min_(new IntegerValue[capacity_]),
cached_negated_shifted_end_max_(new IntegerValue[capacity_]) {
starts_.clear();
ends_.clear();
minus_ends_.clear();
minus_starts_.clear();
sizes_.clear();
reason_for_presence_.clear();
auto* repository = model->GetOrCreate<IntervalsRepository>();
for (const IntervalVariable i : tasks) {
if (repository->IsOptional(i)) {
reason_for_presence_.push_back(repository->PresenceLiteral(i).Index());
} else {
reason_for_presence_.push_back(kNoLiteralIndex);
}
sizes_.push_back(repository->Size(i));
starts_.push_back(repository->Start(i));
ends_.push_back(repository->End(i));
minus_starts_.push_back(repository->Start(i).Negated());
minus_ends_.push_back(repository->End(i).Negated());
}
RegisterWith(model->GetOrCreate<GenericLiteralWatcher>());
InitSortedVectors();
if (!SynchronizeAndSetTimeDirection(true)) {
model->GetOrCreate<SatSolver>()->NotifyThatModelIsUnsat();
}
}
SchedulingConstraintHelper::SchedulingConstraintHelper(int num_tasks,
Model* model)
: model_(model),
trail_(model->GetOrCreate<Trail>()),
sat_solver_(model->GetOrCreate<SatSolver>()),
integer_trail_(model->GetOrCreate<IntegerTrail>()),
precedence_relations_(model->GetOrCreate<PrecedenceRelations>()),
capacity_(num_tasks),
cached_size_min_(new IntegerValue[capacity_]),
cached_start_min_(new IntegerValue[capacity_]),
cached_end_min_(new IntegerValue[capacity_]),
cached_negated_start_max_(new IntegerValue[capacity_]),
cached_negated_end_max_(new IntegerValue[capacity_]),
cached_shifted_start_min_(new IntegerValue[capacity_]),
cached_negated_shifted_end_max_(new IntegerValue[capacity_]) {
starts_.resize(num_tasks);
CHECK_EQ(NumTasks(), num_tasks);
}
bool SchedulingConstraintHelper::Propagate() {
recompute_all_cache_ = true;
for (const int id : propagator_ids_) watcher_->CallOnNextPropagate(id);
return true;
}
bool SchedulingConstraintHelper::IncrementalPropagate(
const std::vector<int>& watch_indices) {
for (const int t : watch_indices) recompute_cache_.Set(t);
for (const int id : propagator_ids_) watcher_->CallOnNextPropagate(id);
return true;
}
void SchedulingConstraintHelper::RegisterWith(GenericLiteralWatcher* watcher) {
const int id = watcher->Register(this);
const int num_tasks = starts_.size();
for (int t = 0; t < num_tasks; ++t) {
watcher->WatchIntegerVariable(sizes_[t].var, id, t);
watcher->WatchIntegerVariable(starts_[t].var, id, t);
watcher->WatchIntegerVariable(ends_[t].var, id, t);
}
watcher->SetPropagatorPriority(id, 0);
}
bool SchedulingConstraintHelper::UpdateCachedValues(int t) {
if (IsAbsent(t)) return true;
IntegerValue smin = integer_trail_->LowerBound(starts_[t]);
IntegerValue smax = integer_trail_->UpperBound(starts_[t]);
IntegerValue emin = integer_trail_->LowerBound(ends_[t]);
IntegerValue emax = integer_trail_->UpperBound(ends_[t]);
// We take the max for the corner case where the size of an optional interval
// is used elsewhere and has a domain with negative value.
//
// TODO(user): maybe we should just disallow size with a negative domain, but
// is is harder to enforce if we have a linear expression for size.
IntegerValue dmin =
std::max(IntegerValue(0), integer_trail_->LowerBound(sizes_[t]));
IntegerValue dmax = integer_trail_->UpperBound(sizes_[t]);
// Detect first if we have a conflict using the relation start + size = end.
if (dmax < 0) {
ClearReason();
AddSizeMaxReason(t, dmax);
return PushTaskAbsence(t);
}
if (smin + dmin - emax > 0) {
ClearReason();
AddStartMinReason(t, smin);
AddSizeMinReason(t, dmin);
AddEndMaxReason(t, emax);
return PushTaskAbsence(t);
}
if (smax + dmax - emin < 0) {
ClearReason();
AddStartMaxReason(t, smax);
AddSizeMaxReason(t, dmax);
AddEndMinReason(t, emin);
return PushTaskAbsence(t);
}
// Sometimes, for optional interval with non-optional bounds, this propagation
// give tighter bounds. We always consider the value assuming
// the interval is present.
//
// Note that this is also useful in case not everything was propagated. Note
// also that since there is no conflict, we reach the fix point in one pass.
smin = std::max(smin, emin - dmax);
smax = std::min(smax, emax - dmin);
dmin = std::max(dmin, emin - smax);
emin = std::max(emin, smin + dmin);
emax = std::min(emax, smax + dmax);
if (emin != cached_end_min_[t]) {
recompute_energy_profile_ = true;
}
// We might only want to do that if the value changed, but I am not sure it
// is worth the test.
recompute_by_start_max_ = true;
recompute_by_end_min_ = true;
cached_start_min_[t] = smin;
cached_end_min_[t] = emin;
cached_negated_start_max_[t] = -smax;
cached_negated_end_max_[t] = -emax;
cached_size_min_[t] = dmin;
// Note that we use the cached value here for EndMin()/StartMax().
const IntegerValue new_shifted_start_min = emin - dmin;
if (new_shifted_start_min != cached_shifted_start_min_[t]) {
recompute_energy_profile_ = true;
recompute_shifted_start_min_ = true;
cached_shifted_start_min_[t] = new_shifted_start_min;
}
const IntegerValue new_negated_shifted_end_max = -(smax + dmin);
if (new_negated_shifted_end_max != cached_negated_shifted_end_max_[t]) {
recompute_negated_shifted_end_max_ = true;
cached_negated_shifted_end_max_[t] = new_negated_shifted_end_max;
}
return true;
}
bool SchedulingConstraintHelper::ResetFromSubset(
const SchedulingConstraintHelper& other, absl::Span<const int> tasks) {
current_time_direction_ = other.current_time_direction_;
const int num_tasks = tasks.size();
interval_variables_.resize(num_tasks);
starts_.resize(num_tasks);
ends_.resize(num_tasks);
minus_ends_.resize(num_tasks);
minus_starts_.resize(num_tasks);
sizes_.resize(num_tasks);
reason_for_presence_.resize(num_tasks);
for (int i = 0; i < num_tasks; ++i) {
const int t = tasks[i];
interval_variables_[i] = other.interval_variables_[t];
starts_[i] = other.starts_[t];
ends_[i] = other.ends_[t];
minus_ends_[i] = other.minus_ends_[t];
minus_starts_[i] = other.minus_starts_[t];
sizes_[i] = other.sizes_[t];
reason_for_presence_[i] = other.reason_for_presence_[t];
}
InitSortedVectors();
return SynchronizeAndSetTimeDirection(true);
}
void SchedulingConstraintHelper::InitSortedVectors() {
const int num_tasks = starts_.size();
recompute_all_cache_ = true;
recompute_cache_.Resize(num_tasks);
for (int t = 0; t < num_tasks; ++t) {
recompute_cache_.Set(t);
}
// Make sure all the cached_* arrays can hold enough data.
CHECK_LE(num_tasks, capacity_);
task_by_increasing_start_min_.resize(num_tasks);
task_by_increasing_end_min_.resize(num_tasks);
task_by_increasing_negated_start_max_.resize(num_tasks);
task_by_decreasing_end_max_.resize(num_tasks);
task_by_increasing_shifted_start_min_.resize(num_tasks);
task_by_negated_shifted_end_max_.resize(num_tasks);
for (int t = 0; t < num_tasks; ++t) {
task_by_increasing_start_min_[t].task_index = t;
task_by_increasing_end_min_[t].task_index = t;
task_by_increasing_negated_start_max_[t].task_index = t;
task_by_decreasing_end_max_[t].task_index = t;
task_by_increasing_shifted_start_min_[t].task_index = t;
task_by_increasing_shifted_start_min_[t].presence_lit =
reason_for_presence_[t];
task_by_negated_shifted_end_max_[t].task_index = t;
task_by_negated_shifted_end_max_[t].presence_lit = reason_for_presence_[t];
}
recompute_by_start_max_ = true;
recompute_by_end_min_ = true;
recompute_energy_profile_ = true;
recompute_shifted_start_min_ = true;
recompute_negated_shifted_end_max_ = true;
}
void SchedulingConstraintHelper::SetTimeDirection(bool is_forward) {
if (current_time_direction_ != is_forward) {
current_time_direction_ = is_forward;
std::swap(starts_, minus_ends_);
std::swap(ends_, minus_starts_);
std::swap(task_by_increasing_start_min_, task_by_decreasing_end_max_);
std::swap(task_by_increasing_end_min_,
task_by_increasing_negated_start_max_);
std::swap(recompute_by_end_min_, recompute_by_start_max_);
std::swap(task_by_increasing_shifted_start_min_,
task_by_negated_shifted_end_max_);
recompute_energy_profile_ = true;
std::swap(cached_start_min_, cached_negated_end_max_);
std::swap(cached_end_min_, cached_negated_start_max_);
std::swap(cached_shifted_start_min_, cached_negated_shifted_end_max_);
std::swap(recompute_shifted_start_min_, recompute_negated_shifted_end_max_);
}
}
bool SchedulingConstraintHelper::SynchronizeAndSetTimeDirection(
bool is_forward) {
SetTimeDirection(is_forward);
// If there was any backtracks since the last time this was called, we
// recompute our cache.
if (sat_solver_->num_backtracks() != saved_num_backtracks_) {
recompute_all_cache_ = true;
saved_num_backtracks_ = sat_solver_->num_backtracks();
}
if (recompute_all_cache_) {
for (int t = 0; t < recompute_cache_.size(); ++t) {
if (!UpdateCachedValues(t)) return false;
}
} else {
for (const int t : recompute_cache_) {
if (!UpdateCachedValues(t)) return false;
}
}
recompute_cache_.ClearAll();
recompute_all_cache_ = false;
return true;
}
// TODO(user): be more precise when we know a and b are in disjunction.
// we really just need start_b > start_a, or even >= if duration is non-zero.
IntegerValue SchedulingConstraintHelper::GetCurrentMinDistanceBetweenTasks(
int a, int b, bool add_reason_if_after) {
const AffineExpression before = ends_[a];
const AffineExpression after = starts_[b];
if (before.var == kNoIntegerVariable || before.coeff != 1 ||
after.var == kNoIntegerVariable || after.coeff != 1) {
return kMinIntegerValue;
}
// We take the max of the level zero offset and the one coming from a
// conditional precedence at true.
const IntegerValue conditional_offset =
precedence_relations_->GetConditionalOffset(before.var, after.var);
const IntegerValue known = integer_trail_->LevelZeroLowerBound(after.var) -
integer_trail_->LevelZeroUpperBound(before.var);
const IntegerValue offset = std::max(conditional_offset, known);
const IntegerValue needed_offset = before.constant - after.constant;
const IntegerValue distance = offset - needed_offset;
if (add_reason_if_after && distance >= 0 && known < conditional_offset) {
for (const Literal l : precedence_relations_->GetConditionalEnforcements(
before.var, after.var)) {
literal_reason_.push_back(l.Negated());
}
}
return distance;
}
// Note that we could call this at a positive level to propagate any literal
// associated to task a before task b. However we only call this for task that
// are in detectable precedence, which means the normal precedence or linear
// propagator should have already propagated that Boolean too.
bool SchedulingConstraintHelper::PropagatePrecedence(int a, int b) {
CHECK(IsPresent(a));
CHECK(IsPresent(b));
CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
const AffineExpression before = ends_[a];
const AffineExpression after = starts_[b];
if (after.coeff != 1) return true;
if (before.coeff != 1) return true;
if (after.var == kNoIntegerVariable) return true;
if (before.var == kNoIntegerVariable) return true;
const IntegerValue offset = before.constant - after.constant;
if (precedence_relations_->Add(before.var, after.var, offset)) {
VLOG(2) << "new relation " << TaskDebugString(a)
<< " <= " << TaskDebugString(b);
// TODO(user): Adding new constraint during propagation might not be the
// best idea as it can create some complication.
AddWeightedSumLowerOrEqual({}, {before.var, after.var},
{int64_t{1}, int64_t{-1}}, -offset.value(),
model_);
if (model_->GetOrCreate<SatSolver>()->ModelIsUnsat()) return false;
}
return true;
}
absl::Span<const TaskTime>
SchedulingConstraintHelper::TaskByIncreasingStartMin() {
for (TaskTime& ref : task_by_increasing_start_min_) {
ref.time = StartMin(ref.task_index);
}
IncrementalSort(task_by_increasing_start_min_.begin(),
task_by_increasing_start_min_.end());
return task_by_increasing_start_min_;
}
absl::Span<const TaskTime>
SchedulingConstraintHelper::TaskByIncreasingEndMin() {
if (!recompute_by_end_min_) return task_by_increasing_end_min_;
for (TaskTime& ref : task_by_increasing_end_min_) {
ref.time = EndMin(ref.task_index);
}
IncrementalSort(task_by_increasing_end_min_.begin(),
task_by_increasing_end_min_.end());
recompute_by_end_min_ = false;
return task_by_increasing_end_min_;
}
absl::Span<const TaskTime>
SchedulingConstraintHelper::TaskByIncreasingNegatedStartMax() {
if (!recompute_by_start_max_) return task_by_increasing_negated_start_max_;
for (TaskTime& ref : task_by_increasing_negated_start_max_) {
ref.time = cached_negated_start_max_[ref.task_index];
}
IncrementalSort(task_by_increasing_negated_start_max_.begin(),
task_by_increasing_negated_start_max_.end());
recompute_by_start_max_ = false;
return task_by_increasing_negated_start_max_;
}
absl::Span<const TaskTime>
SchedulingConstraintHelper::TaskByDecreasingEndMax() {
for (TaskTime& ref : task_by_decreasing_end_max_) {
ref.time = EndMax(ref.task_index);
}
IncrementalSort(task_by_decreasing_end_max_.begin(),
task_by_decreasing_end_max_.end(), std::greater<TaskTime>());
return task_by_decreasing_end_max_;
}
absl::Span<const CachedTaskBounds>
SchedulingConstraintHelper::TaskByIncreasingShiftedStartMin() {
if (recompute_shifted_start_min_) {
recompute_shifted_start_min_ = false;
bool is_sorted = true;
IntegerValue previous = kMinIntegerValue;
for (CachedTaskBounds& ref : task_by_increasing_shifted_start_min_) {
ref.time = ShiftedStartMin(ref.task_index);
is_sorted = is_sorted && ref.time >= previous;
previous = ref.time;
}
if (is_sorted) return task_by_increasing_shifted_start_min_;
IncrementalSort(task_by_increasing_shifted_start_min_.begin(),
task_by_increasing_shifted_start_min_.end());
}
return task_by_increasing_shifted_start_min_;
}
// TODO(user): Avoid recomputing it if nothing changed.
const std::vector<SchedulingConstraintHelper::ProfileEvent>&
SchedulingConstraintHelper::GetEnergyProfile() {
if (energy_profile_.empty()) {
const int num_tasks = NumTasks();
for (int t = 0; t < num_tasks; ++t) {
energy_profile_.push_back(
{cached_shifted_start_min_[t], t, /*is_first=*/true});
energy_profile_.push_back({cached_end_min_[t], t, /*is_first=*/false});
}
} else {
if (!recompute_energy_profile_) return energy_profile_;
for (ProfileEvent& ref : energy_profile_) {
const int t = ref.task;
if (ref.is_first) {
ref.time = cached_shifted_start_min_[t];
} else {
ref.time = cached_end_min_[t];
}
}
}
IncrementalSort(energy_profile_.begin(), energy_profile_.end());
recompute_energy_profile_ = false;
return energy_profile_;
}
// Produces a relaxed reason for StartMax(before) < EndMin(after).
void SchedulingConstraintHelper::AddReasonForBeingBefore(int before,
int after) {
AddOtherReason(before);
AddOtherReason(after);
// The reason will be a linear expression greater than a value. Note that all
// coeff must be positive, and we will use the variable lower bound.
std::vector<IntegerVariable> vars;
std::vector<IntegerValue> coeffs;
// Reason for StartMax(before).
const IntegerValue smax_before = StartMax(before);
if (smax_before >= integer_trail_->UpperBound(starts_[before])) {
if (starts_[before].var != kNoIntegerVariable) {
vars.push_back(NegationOf(starts_[before].var));
coeffs.push_back(starts_[before].coeff);
}
} else {
if (ends_[before].var != kNoIntegerVariable) {
vars.push_back(NegationOf(ends_[before].var));
coeffs.push_back(ends_[before].coeff);
}
if (sizes_[before].var != kNoIntegerVariable) {
vars.push_back(sizes_[before].var);
coeffs.push_back(sizes_[before].coeff);
}
}
// Reason for EndMin(after);
const IntegerValue emin_after = EndMin(after);
if (emin_after <= integer_trail_->LowerBound(ends_[after])) {
if (ends_[after].var != kNoIntegerVariable) {
vars.push_back(ends_[after].var);
coeffs.push_back(ends_[after].coeff);
}
} else {
if (starts_[after].var != kNoIntegerVariable) {
vars.push_back(starts_[after].var);
coeffs.push_back(starts_[after].coeff);
}
if (sizes_[after].var != kNoIntegerVariable) {
vars.push_back(sizes_[after].var);
coeffs.push_back(sizes_[after].coeff);
}
}
DCHECK_LT(smax_before, emin_after);
const IntegerValue slack = emin_after - smax_before - 1;
integer_trail_->AppendRelaxedLinearReason(slack, coeffs, vars,
&integer_reason_);
}
bool SchedulingConstraintHelper::PushIntegerLiteral(IntegerLiteral lit) {
CHECK(other_helper_ == nullptr);
return integer_trail_->Enqueue(lit, literal_reason_, integer_reason_);
}
bool SchedulingConstraintHelper::PushIntegerLiteralIfTaskPresent(
int t, IntegerLiteral lit) {
if (IsAbsent(t)) return true;
AddOtherReason(t);
ImportOtherReasons();
if (IsOptional(t)) {
return integer_trail_->ConditionalEnqueue(
PresenceLiteral(t), lit, &literal_reason_, &integer_reason_);
}
return integer_trail_->Enqueue(lit, literal_reason_, integer_reason_);
}
// We also run directly the precedence propagator for this variable so that when
// we push an interval start for example, we have a chance to push its end.
bool SchedulingConstraintHelper::PushIntervalBound(int t, IntegerLiteral lit) {
if (!PushIntegerLiteralIfTaskPresent(t, lit)) return false;
if (IsAbsent(t)) return true;
if (!UpdateCachedValues(t)) return false;
recompute_cache_.Clear(t);
return true;
}
bool SchedulingConstraintHelper::IncreaseStartMin(int t, IntegerValue value) {
if (starts_[t].var == kNoIntegerVariable) {
if (value > starts_[t].constant) return PushTaskAbsence(t);
return true;
}
return PushIntervalBound(t, starts_[t].GreaterOrEqual(value));
}
bool SchedulingConstraintHelper::IncreaseEndMin(int t, IntegerValue value) {
if (ends_[t].var == kNoIntegerVariable) {
if (value > ends_[t].constant) return PushTaskAbsence(t);
return true;
}
return PushIntervalBound(t, ends_[t].GreaterOrEqual(value));
}
bool SchedulingConstraintHelper::DecreaseEndMax(int t, IntegerValue value) {
if (ends_[t].var == kNoIntegerVariable) {
if (value < ends_[t].constant) return PushTaskAbsence(t);
return true;
}
return PushIntervalBound(t, ends_[t].LowerOrEqual(value));
}
bool SchedulingConstraintHelper::PushLiteral(Literal l) {
integer_trail_->EnqueueLiteral(l, literal_reason_, integer_reason_);
return true;
}
bool SchedulingConstraintHelper::PushTaskAbsence(int t) {
if (IsAbsent(t)) return true;
if (!IsOptional(t)) return ReportConflict();
AddOtherReason(t);
if (IsPresent(t)) {
literal_reason_.push_back(Literal(reason_for_presence_[t]).Negated());
return ReportConflict();
}
ImportOtherReasons();
integer_trail_->EnqueueLiteral(Literal(reason_for_presence_[t]).Negated(),
literal_reason_, integer_reason_);
return true;
}
bool SchedulingConstraintHelper::PushTaskPresence(int t) {
DCHECK_NE(reason_for_presence_[t], kNoLiteralIndex);
DCHECK(!IsPresent(t));
AddOtherReason(t);
if (IsAbsent(t)) {
literal_reason_.push_back(Literal(reason_for_presence_[t]));
return ReportConflict();
}
ImportOtherReasons();
integer_trail_->EnqueueLiteral(Literal(reason_for_presence_[t]),
literal_reason_, integer_reason_);
return true;
}
bool SchedulingConstraintHelper::ReportConflict() {
ImportOtherReasons();
return integer_trail_->ReportConflict(literal_reason_, integer_reason_);
}
void SchedulingConstraintHelper::WatchAllTasks(int id, bool watch_max_side) {
// In all cases, we watch presence literals since this class is not waked up
// when those changes.
const int num_tasks = starts_.size();
for (int t = 0; t < num_tasks; ++t) {
if (!IsPresent(t) && !IsAbsent(t)) {
watcher_->WatchLiteral(Literal(reason_for_presence_[t]), id);
}
}
// If everything is watched, it is slighlty more efficient to enqueue the
// propagator when the helper Propagate() is called. This result in less
// entries in our watched lists.
if (watch_max_side) {
propagator_ids_.push_back(id);
return;
}
// We only watch "min" side.
for (int t = 0; t < num_tasks; ++t) {
watcher_->WatchLowerBound(starts_[t], id);
watcher_->WatchLowerBound(ends_[t], id);
watcher_->WatchLowerBound(sizes_[t], id);
}
}
void SchedulingConstraintHelper::AddOtherReason(int t) {
if (other_helper_ == nullptr || already_added_to_other_reasons_[t]) return;
already_added_to_other_reasons_[t] = true;
const int mapped_t = map_to_other_helper_[t];
other_helper_->AddStartMaxReason(mapped_t, event_for_other_helper_);
other_helper_->AddEndMinReason(mapped_t, event_for_other_helper_ + 1);
}
void SchedulingConstraintHelper::ImportOtherReasons() {
if (other_helper_ != nullptr) ImportOtherReasons(*other_helper_);
}
void SchedulingConstraintHelper::ImportOtherReasons(
const SchedulingConstraintHelper& other_helper) {
literal_reason_.insert(literal_reason_.end(),
other_helper.literal_reason_.begin(),
other_helper.literal_reason_.end());
integer_reason_.insert(integer_reason_.end(),
other_helper.integer_reason_.begin(),
other_helper.integer_reason_.end());
}
std::string SchedulingConstraintHelper::TaskDebugString(int t) const {
return absl::StrCat("t=", t, " is_present=", IsPresent(t), " size=[",
SizeMin(t).value(), ",", SizeMax(t).value(), "]",
" start=[", StartMin(t).value(), ",", StartMax(t).value(),
"]", " end=[", EndMin(t).value(), ",", EndMax(t).value(),
"]");
}
IntegerValue SchedulingConstraintHelper::GetMinOverlap(int t,
IntegerValue start,
IntegerValue end) const {
return std::min(std::min(end - start, SizeMin(t)),
std::min(EndMin(t) - start, end - StartMax(t)));
}
IntegerValue ComputeEnergyMinInWindow(
IntegerValue start_min, IntegerValue start_max, IntegerValue end_min,
IntegerValue end_max, IntegerValue size_min, IntegerValue demand_min,
absl::Span<const LiteralValueValue> filtered_energy,
IntegerValue window_start, IntegerValue window_end) {
if (window_end <= window_start) return IntegerValue(0);
// Returns zero if the interval do not necessarily overlap.
if (end_min <= window_start) return IntegerValue(0);
if (start_max >= window_end) return IntegerValue(0);
const IntegerValue window_size = window_end - window_start;
const IntegerValue simple_energy_min =
demand_min * std::min({end_min - window_start, window_end - start_max,
size_min, window_size});
if (filtered_energy.empty()) return simple_energy_min;
IntegerValue result = kMaxIntegerValue;
for (const auto [lit, fixed_size, fixed_demand] : filtered_energy) {
const IntegerValue alt_end_min = std::max(end_min, start_min + fixed_size);
const IntegerValue alt_start_max =
std::min(start_max, end_max - fixed_size);
const IntegerValue energy_min =
fixed_demand *
std::min({alt_end_min - window_start, window_end - alt_start_max,
fixed_size, window_size});
result = std::min(result, energy_min);
}
if (result == kMaxIntegerValue) return simple_energy_min;
return std::max(simple_energy_min, result);
}
SchedulingDemandHelper::SchedulingDemandHelper(
absl::Span<const AffineExpression> demands,
SchedulingConstraintHelper* helper, Model* model)
: integer_trail_(model->GetOrCreate<IntegerTrail>()),
product_decomposer_(model->GetOrCreate<ProductDecomposer>()),
sat_solver_(model->GetOrCreate<SatSolver>()),
assignment_(model->GetOrCreate<SatSolver>()->Assignment()),
demands_(demands.begin(), demands.end()),
helper_(helper) {
const int num_tasks = helper->NumTasks();
linearized_energies_.resize(num_tasks);
decomposed_energies_.resize(num_tasks);
cached_energies_min_.resize(num_tasks, kMinIntegerValue);
cached_energies_max_.resize(num_tasks, kMaxIntegerValue);
energy_is_quadratic_.resize(num_tasks, false);
// We try to init decomposed energies. This is needed for the cuts that are
// created after we call InitAllDecomposedEnergies().
InitDecomposedEnergies();
}
void SchedulingDemandHelper::InitDecomposedEnergies() {
// For the special case were demands is empty.
const int num_tasks = helper_->NumTasks();
if (demands_.size() != num_tasks) return;
for (int t = 0; t < num_tasks; ++t) {
const AffineExpression size = helper_->Sizes()[t];
const AffineExpression demand = demands_[t];
decomposed_energies_[t] = product_decomposer_->TryToDecompose(size, demand);
}
}
IntegerValue SchedulingDemandHelper::SimpleEnergyMin(int t) const {
if (demands_.empty()) return kMinIntegerValue;
return DemandMin(t) * helper_->SizeMin(t);
}
IntegerValue SchedulingDemandHelper::LinearEnergyMin(int t) const {
if (!linearized_energies_[t].has_value()) return kMinIntegerValue;
return linearized_energies_[t]->Min(*integer_trail_);
}
IntegerValue SchedulingDemandHelper::DecomposedEnergyMin(int t) const {
if (decomposed_energies_[t].empty()) return kMinIntegerValue;
IntegerValue result = kMaxIntegerValue;
for (const auto [lit, fixed_size, fixed_demand] : decomposed_energies_[t]) {
if (assignment_.LiteralIsTrue(lit)) {
return fixed_size * fixed_demand;
}
if (assignment_.LiteralIsFalse(lit)) continue;
result = std::min(result, fixed_size * fixed_demand);
}
DCHECK_NE(result, kMaxIntegerValue);
return result;
}
IntegerValue SchedulingDemandHelper::SimpleEnergyMax(int t) const {
if (demands_.empty()) return kMaxIntegerValue;
return DemandMax(t) * helper_->SizeMax(t);
}
IntegerValue SchedulingDemandHelper::LinearEnergyMax(int t) const {
if (!linearized_energies_[t].has_value()) return kMaxIntegerValue;
return linearized_energies_[t]->Max(*integer_trail_);
}
IntegerValue SchedulingDemandHelper::DecomposedEnergyMax(int t) const {
if (decomposed_energies_[t].empty()) return kMaxIntegerValue;
IntegerValue result = kMinIntegerValue;
for (const auto [lit, fixed_size, fixed_demand] : decomposed_energies_[t]) {
if (assignment_.LiteralIsTrue(lit)) {
return fixed_size * fixed_demand;
}
if (assignment_.LiteralIsFalse(lit)) continue;
result = std::max(result, fixed_size * fixed_demand);
}
DCHECK_NE(result, kMinIntegerValue);
return result;
}
void SchedulingDemandHelper::CacheAllEnergyValues() {
const int num_tasks = cached_energies_min_.size();
const bool is_at_level_zero = sat_solver_->CurrentDecisionLevel() == 0;
for (int t = 0; t < num_tasks; ++t) {
// Try to reduce the size of the decomposed energy vector.
if (is_at_level_zero) {
int new_size = 0;
for (int i = 0; i < decomposed_energies_[t].size(); ++i) {
if (assignment_.LiteralIsFalse(decomposed_energies_[t][i].literal)) {
continue;
}
decomposed_energies_[t][new_size++] = decomposed_energies_[t][i];
}
decomposed_energies_[t].resize(new_size);
}
cached_energies_min_[t] = std::max(
{SimpleEnergyMin(t), LinearEnergyMin(t), DecomposedEnergyMin(t)});
CHECK_NE(cached_energies_min_[t], kMinIntegerValue);
energy_is_quadratic_[t] =
decomposed_energies_[t].empty() && !demands_.empty() &&
!integer_trail_->IsFixed(demands_[t]) && !helper_->SizeIsFixed(t);
cached_energies_max_[t] = std::min(
{SimpleEnergyMax(t), LinearEnergyMax(t), DecomposedEnergyMax(t)});
CHECK_NE(cached_energies_max_[t], kMaxIntegerValue);