OR-Tools  8.1
timetable.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #include "ortools/sat/timetable.h"
15 
16 #include <algorithm>
17 #include <functional>
18 #include <memory>
19 
20 #include "ortools/base/int_type.h"
21 #include "ortools/base/logging.h"
22 #include "ortools/util/sort.h"
23 
24 namespace operations_research {
25 namespace sat {
26 
28  const std::vector<AffineExpression>& demands, AffineExpression capacity,
29  IntegerTrail* integer_trail, SchedulingConstraintHelper* helper)
30  : num_tasks_(helper->NumTasks()),
31  demands_(demands),
32  capacity_(capacity),
33  integer_trail_(integer_trail),
34  helper_(helper) {
35  // Each task may create at most two profile rectangles. Such pattern appear if
36  // the profile is shaped like the Hanoi tower. The additional space is for
37  // both extremities and the sentinels.
38  profile_.reserve(2 * num_tasks_ + 4);
39 
40  // Reversible set of tasks to consider for propagation.
41  forward_num_tasks_to_sweep_ = num_tasks_;
42  forward_tasks_to_sweep_.resize(num_tasks_);
43  backward_num_tasks_to_sweep_ = num_tasks_;
44  backward_tasks_to_sweep_.resize(num_tasks_);
45 
46  num_profile_tasks_ = 0;
47  profile_tasks_.resize(num_tasks_);
48  positions_in_profile_tasks_.resize(num_tasks_);
49 
50  // Reversible bounds and starting height of the profile.
51  starting_profile_height_ = IntegerValue(0);
52 
53  for (int t = 0; t < num_tasks_; ++t) {
54  forward_tasks_to_sweep_[t] = t;
55  backward_tasks_to_sweep_[t] = t;
56  profile_tasks_[t] = t;
57  positions_in_profile_tasks_[t] = t;
58  }
59 }
60 
62  const int id = watcher->Register(this);
63  helper_->WatchAllTasks(id, watcher);
64  watcher->WatchUpperBound(capacity_.var, id);
65  for (int t = 0; t < num_tasks_; t++) {
66  watcher->WatchLowerBound(demands_[t].var, id);
67  }
68  watcher->RegisterReversibleInt(id, &forward_num_tasks_to_sweep_);
69  watcher->RegisterReversibleInt(id, &backward_num_tasks_to_sweep_);
70  watcher->RegisterReversibleInt(id, &num_profile_tasks_);
71 
72  // Changing the times or pushing task absence migth have side effects on the
73  // other intervals, so we would need to be called again in this case.
75 }
76 
77 // Note that we relly on being called again to reach a fixed point.
79  // This can fail if the profile exceeds the resource capacity.
80  if (!BuildProfile()) return false;
81 
82  // Update the minimum start times.
83  if (!SweepAllTasks(/*is_forward=*/true)) return false;
84 
85  // We reuse the same profile, but reversed, to update the maximum end times.
86  ReverseProfile();
87 
88  // Update the maximum end times (reversed problem).
89  if (!SweepAllTasks(/*is_forward=*/false)) return false;
90 
91  return true;
92 }
93 
94 bool TimeTablingPerTask::BuildProfile() {
95  helper_->SynchronizeAndSetTimeDirection(true); // forward
96 
97  // Update the set of tasks that contribute to the profile. Tasks that were
98  // contributing are still part of the profile so we only need to check the
99  // other tasks.
100  for (int i = num_profile_tasks_; i < num_tasks_; ++i) {
101  const int t1 = profile_tasks_[i];
102  if (helper_->IsPresent(t1) && helper_->StartMax(t1) < helper_->EndMin(t1)) {
103  // Swap values and positions.
104  const int t2 = profile_tasks_[num_profile_tasks_];
105  profile_tasks_[i] = t2;
106  profile_tasks_[num_profile_tasks_] = t1;
107  positions_in_profile_tasks_[t1] = num_profile_tasks_;
108  positions_in_profile_tasks_[t2] = i;
109  num_profile_tasks_++;
110  }
111  }
112 
113  const auto& by_decreasing_start_max = helper_->TaskByDecreasingStartMax();
114  const auto& by_end_min = helper_->TaskByIncreasingEndMin();
115 
116  // Build the profile.
117  // ------------------
118  profile_.clear();
119 
120  // Start and height of the highest profile rectangle.
121  profile_max_height_ = kMinIntegerValue;
122  IntegerValue max_height_start = kMinIntegerValue;
123 
124  // Add a sentinel to simplify the algorithm.
125  profile_.emplace_back(kMinIntegerValue, IntegerValue(0));
126 
127  // Start and height of the currently built profile rectange.
128  IntegerValue current_start = kMinIntegerValue;
129  IntegerValue current_height = starting_profile_height_;
130 
131  // Next start/end of the compulsory parts to be processed. Note that only the
132  // task for which IsInProfile() is true must be considered.
133  int next_start = num_tasks_ - 1;
134  int next_end = 0;
135  while (next_end < num_tasks_) {
136  const IntegerValue old_height = current_height;
137 
138  IntegerValue t = by_end_min[next_end].time;
139  if (next_start >= 0) {
140  t = std::min(t, by_decreasing_start_max[next_start].time);
141  }
142 
143  // Process the starting compulsory parts.
144  while (next_start >= 0 && by_decreasing_start_max[next_start].time == t) {
145  const int task_index = by_decreasing_start_max[next_start].task_index;
146  if (IsInProfile(task_index)) current_height += DemandMin(task_index);
147  --next_start;
148  }
149 
150  // Process the ending compulsory parts.
151  while (next_end < num_tasks_ && by_end_min[next_end].time == t) {
152  const int task_index = by_end_min[next_end].task_index;
153  if (IsInProfile(task_index)) current_height -= DemandMin(task_index);
154  ++next_end;
155  }
156 
157  // Insert a new profile rectangle if any.
158  if (current_height != old_height) {
159  profile_.emplace_back(current_start, old_height);
160  if (current_height > profile_max_height_) {
161  profile_max_height_ = current_height;
162  max_height_start = t;
163  }
164  current_start = t;
165  }
166  }
167 
168  // Build the last profile rectangle.
169  DCHECK_GE(current_height, 0);
170  profile_.emplace_back(current_start, IntegerValue(0));
171 
172  // Add a sentinel to simplify the algorithm.
173  profile_.emplace_back(kMaxIntegerValue, IntegerValue(0));
174 
175  // Increase the capacity variable if required.
176  return IncreaseCapacity(max_height_start, profile_max_height_);
177 }
178 
179 void TimeTablingPerTask::ReverseProfile() {
180  helper_->SynchronizeAndSetTimeDirection(false); // backward
181 
182  // We keep the sentinels inchanged.
183  for (int i = 1; i + 1 < profile_.size(); ++i) {
184  profile_[i].start = -profile_[i + 1].start;
185  }
186  std::reverse(profile_.begin() + 1, profile_.end() - 1);
187 }
188 
189 bool TimeTablingPerTask::SweepAllTasks(bool is_forward) {
190  // Tasks with a lower or equal demand will not be pushed.
191  const IntegerValue demand_threshold(
192  CapSub(CapacityMax().value(), profile_max_height_.value()));
193 
194  // Select the correct members depending on the direction.
195  int& num_tasks =
196  is_forward ? forward_num_tasks_to_sweep_ : backward_num_tasks_to_sweep_;
197  std::vector<int>& tasks =
198  is_forward ? forward_tasks_to_sweep_ : backward_tasks_to_sweep_;
199 
200  // TODO(user): On some problem, a big chunk of the time is spend just checking
201  // these conditions below because it requires indirect memory access to fetch
202  // the demand/size/presence/start ...
203  for (int i = num_tasks - 1; i >= 0; --i) {
204  const int t = tasks[i];
205  if (helper_->IsAbsent(t) ||
206  (helper_->IsPresent(t) && helper_->StartIsFixed(t))) {
207  // This tasks does not have to be considered for propagation in the rest
208  // of the sub-tree. Note that StartIsFixed() depends on the time
209  // direction, it is why we use two lists.
210  std::swap(tasks[i], tasks[--num_tasks]);
211  continue;
212  }
213 
214  // Skip if demand is too low.
215  if (DemandMin(t) <= demand_threshold) {
216  if (DemandMax(t) == 0) {
217  // We can ignore this task for the rest of the subtree like above.
218  std::swap(tasks[i], tasks[--num_tasks]);
219  }
220 
221  // This task does not have to be considered for propagation in this
222  // particular iteration, but maybe it does later.
223  continue;
224  }
225 
226  // Skip if size is zero.
227  if (helper_->SizeMin(t) == 0) {
228  if (helper_->SizeMax(t) == 0) {
229  std::swap(tasks[i], tasks[--num_tasks]);
230  }
231  continue;
232  }
233 
234  if (!SweepTask(t)) return false;
235  }
236 
237  return true;
238 }
239 
240 bool TimeTablingPerTask::SweepTask(int task_id) {
241  const IntegerValue start_max = helper_->StartMax(task_id);
242  const IntegerValue size_min = helper_->SizeMin(task_id);
243  const IntegerValue initial_start_min = helper_->StartMin(task_id);
244  const IntegerValue initial_end_min = helper_->EndMin(task_id);
245 
246  IntegerValue new_start_min = initial_start_min;
247  IntegerValue new_end_min = initial_end_min;
248 
249  // Find the profile rectangle that overlaps the minimum start time of task_id.
250  // The sentinel prevents out of bound exceptions.
251  DCHECK(std::is_sorted(profile_.begin(), profile_.end()));
252  int rec_id =
253  std::upper_bound(profile_.begin(), profile_.end(), new_start_min,
254  [&](IntegerValue value, const ProfileRectangle& rect) {
255  return value < rect.start;
256  }) -
257  profile_.begin();
258  --rec_id;
259 
260  // A profile rectangle is in conflict with the task if its height exceeds
261  // conflict_height.
262  const IntegerValue conflict_height = CapacityMax() - DemandMin(task_id);
263 
264  // True if the task is in conflict with at least one profile rectangle.
265  bool conflict_found = false;
266 
267  // Last time point during which task_id was in conflict with a profile
268  // rectangle before being pushed.
269  IntegerValue last_initial_conflict = kMinIntegerValue;
270 
271  // Push the task from left to right until it does not overlap any conflicting
272  // rectangle. Pushing the task may push the end of its compulsory part on the
273  // right but will not change its start. The main loop of the propagator will
274  // take care of rebuilding the profile with these possible changes and to
275  // propagate again in order to reach the timetabling consistency or to fail if
276  // the profile exceeds the resource capacity.
277  IntegerValue limit = std::min(start_max, new_end_min);
278  for (; profile_[rec_id].start < limit; ++rec_id) {
279  // If the profile rectangle is not conflicting, go to the next rectangle.
280  if (profile_[rec_id].height <= conflict_height) continue;
281 
282  conflict_found = true;
283 
284  // Compute the next minimum start and end times of task_id. The variables
285  // are not updated yet.
286  new_start_min = profile_[rec_id + 1].start; // i.e. profile_[rec_id].end
287  if (start_max < new_start_min) {
288  if (IsInProfile(task_id)) {
289  // Because the task is part of the profile, we cannot push it further.
290  new_start_min = start_max;
291  } else {
292  // We have a conflict or we can push the task absence. In both cases
293  // we don't need more than start_max + 1 in the explanation below.
294  new_start_min = start_max + 1;
295  }
296  }
297 
298  new_end_min = std::max(new_end_min, new_start_min + size_min);
299  limit = std::min(start_max, new_end_min);
300 
301  if (profile_[rec_id].start < initial_end_min) {
302  last_initial_conflict = std::min(new_start_min, initial_end_min) - 1;
303  }
304  }
305 
306  if (!conflict_found) return true;
307 
308  if (initial_start_min != new_start_min &&
309  !UpdateStartingTime(task_id, last_initial_conflict, new_start_min)) {
310  return false;
311  }
312 
313  return true;
314 }
315 
316 bool TimeTablingPerTask::UpdateStartingTime(int task_id, IntegerValue left,
317  IntegerValue right) {
318  helper_->ClearReason();
319 
320  AddProfileReason(left, right);
321  if (capacity_.var != kNoIntegerVariable) {
322  helper_->MutableIntegerReason()->push_back(
323  integer_trail_->UpperBoundAsLiteral(capacity_.var));
324  }
325 
326  // State of the task to be pushed.
327  helper_->AddEndMinReason(task_id, left + 1);
328  helper_->AddSizeMinReason(task_id, IntegerValue(1));
329  if (demands_[task_id].var != kNoIntegerVariable) {
330  helper_->MutableIntegerReason()->push_back(
331  integer_trail_->LowerBoundAsLiteral(demands_[task_id].var));
332  }
333 
334  // Explain the increase of the minimum start and end times.
335  return helper_->IncreaseStartMin(task_id, right);
336 }
337 
338 void TimeTablingPerTask::AddProfileReason(IntegerValue left,
339  IntegerValue right) {
340  for (int i = 0; i < num_profile_tasks_; ++i) {
341  const int t = profile_tasks_[i];
342 
343  // Do not consider the task if it does not overlap for sure (left, right).
344  const IntegerValue start_max = helper_->StartMax(t);
345  if (right <= start_max) continue;
346  const IntegerValue end_min = helper_->EndMin(t);
347  if (end_min <= left) continue;
348 
349  helper_->AddPresenceReason(t);
350  helper_->AddStartMaxReason(t, std::max(left, start_max));
351  helper_->AddEndMinReason(t, std::min(right, end_min));
352  if (demands_[t].var != kNoIntegerVariable) {
353  helper_->MutableIntegerReason()->push_back(
354  integer_trail_->LowerBoundAsLiteral(demands_[t].var));
355  }
356  }
357 }
358 
359 bool TimeTablingPerTask::IncreaseCapacity(IntegerValue time,
360  IntegerValue new_min) {
361  if (new_min <= CapacityMin()) return true;
362 
363  helper_->ClearReason();
364  AddProfileReason(time, time + 1);
365  if (capacity_.var == kNoIntegerVariable) {
366  return helper_->ReportConflict();
367  }
368 
369  helper_->MutableIntegerReason()->push_back(
370  integer_trail_->UpperBoundAsLiteral(capacity_.var));
371  return helper_->PushIntegerLiteral(capacity_.GreaterOrEqual(new_min));
372 }
373 
374 } // namespace sat
375 } // namespace operations_research
operations_research::sat::TimeTablingPerTask::TimeTablingPerTask
TimeTablingPerTask(const std::vector< AffineExpression > &demands, AffineExpression capacity, IntegerTrail *integer_trail, SchedulingConstraintHelper *helper)
Definition: timetable.cc:27
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::GenericLiteralWatcher::Register
int Register(PropagatorInterface *propagator)
Definition: integer.cc:1910
operations_research::sat::SchedulingConstraintHelper::StartMin
IntegerValue StartMin(int t) const
Definition: intervals.h:228
operations_research::sat::SchedulingConstraintHelper::AddSizeMinReason
void AddSizeMinReason(int t)
Definition: intervals.h:488
min
int64 min
Definition: alldiff_cst.cc:138
operations_research::sat::AffineExpression
Definition: integer.h:205
operations_research::sat::IntegerTrail
Definition: integer.h:533
operations_research::CapSub
int64 CapSub(int64 x, int64 y)
Definition: saturated_arithmetic.h:154
operations_research::sat::kNoIntegerVariable
const IntegerVariable kNoIntegerVariable(-1)
operations_research::sat::SchedulingConstraintHelper::SizeMax
IntegerValue SizeMax(int t) const
Definition: intervals.h:224
max
int64 max
Definition: alldiff_cst.cc:139
operations_research::sat::GenericLiteralWatcher::WatchLowerBound
void WatchLowerBound(IntegerVariable var, int id, int watch_index=-1)
Definition: integer.h:1356
operations_research::sat::SchedulingConstraintHelper::WatchAllTasks
void WatchAllTasks(int id, GenericLiteralWatcher *watcher, bool watch_start_max=true, bool watch_end_max=true) const
Definition: intervals.cc:471
operations_research::sat::SchedulingConstraintHelper::EndMin
IntegerValue EndMin(int t) const
Definition: intervals.h:229
logging.h
operations_research::sat::GenericLiteralWatcher::RegisterReversibleInt
void RegisterReversibleInt(int id, int *rev)
Definition: integer.cc:1954
value
int64 value
Definition: demon_profiler.cc:43
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
operations_research::sat::SchedulingConstraintHelper::TaskByDecreasingStartMax
const std::vector< TaskTime > & TaskByDecreasingStartMax()
Definition: intervals.cc:289
timetable.h
operations_research::sat::GenericLiteralWatcher
Definition: integer.h:1091
operations_research::sat::IntegerTrail::UpperBoundAsLiteral
IntegerLiteral UpperBoundAsLiteral(IntegerVariable i) const
Definition: integer.h:1318
operations_research::sat::SchedulingConstraintHelper::MutableIntegerReason
std::vector< IntegerLiteral > * MutableIntegerReason()
Definition: intervals.h:296
operations_research::sat::SchedulingConstraintHelper::ClearReason
void ClearReason()
Definition: intervals.h:463
operations_research::sat::SchedulingConstraintHelper::ReportConflict
ABSL_MUST_USE_RESULT bool ReportConflict()
Definition: intervals.cc:466
operations_research::sat::SchedulingConstraintHelper
Definition: intervals.h:172
operations_research::sat::SchedulingConstraintHelper::StartMax
IntegerValue StartMax(int t) const
Definition: intervals.h:230
int_type.h
operations_research::sat::GenericLiteralWatcher::NotifyThatPropagatorMayNotReachFixedPointInOnePass
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
Definition: integer.cc:1940
operations_research::sat::kMaxIntegerValue
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
operations_research::sat::SchedulingConstraintHelper::IsAbsent
bool IsAbsent(int t) const
Definition: intervals.h:458
operations_research::sat::IntegerTrail::LowerBoundAsLiteral
IntegerLiteral LowerBoundAsLiteral(IntegerVariable i) const
Definition: integer.h:1313
operations_research::sat::AffineExpression::GreaterOrEqual
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
Definition: integer.h:1268
start_max
Rev< int64 > start_max
Definition: sched_constraints.cc:242
DCHECK
#define DCHECK(condition)
Definition: base/logging.h:884
operations_research::sat::SchedulingConstraintHelper::AddStartMaxReason
void AddStartMaxReason(int t, IntegerValue upper_bound)
Definition: intervals.h:513
operations_research::sat::SchedulingConstraintHelper::SynchronizeAndSetTimeDirection
void SynchronizeAndSetTimeDirection(bool is_forward)
Definition: intervals.cc:234
DCHECK_GE
#define DCHECK_GE(val1, val2)
Definition: base/logging.h:889
operations_research::sat::SchedulingConstraintHelper::IncreaseStartMin
ABSL_MUST_USE_RESULT bool IncreaseStartMin(int t, IntegerValue new_start_min)
Definition: intervals.cc:424
sort.h
operations_research::sat::TimeTablingPerTask::Propagate
bool Propagate() final
Definition: timetable.cc:78
operations_research::sat::SchedulingConstraintHelper::SizeMin
IntegerValue SizeMin(int t) const
Definition: intervals.h:223
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
end_min
Rev< int64 > end_min
Definition: sched_constraints.cc:243
operations_research::sat::SchedulingConstraintHelper::IsPresent
bool IsPresent(int t) const
Definition: intervals.h:453
operations_research::sat::SchedulingConstraintHelper::StartIsFixed
bool StartIsFixed(int t) const
Definition: intervals.h:437
operations_research::sat::SchedulingConstraintHelper::AddEndMinReason
void AddEndMinReason(int t, IntegerValue lower_bound)
Definition: intervals.h:535
operations_research::sat::AffineExpression::var
IntegerVariable var
Definition: integer.h:240
capacity
int64 capacity
Definition: routing_flow.cc:129
operations_research::sat::SchedulingConstraintHelper::TaskByIncreasingEndMin
const std::vector< TaskTime > & TaskByIncreasingEndMin()
Definition: intervals.cc:277
operations_research::sat::GenericLiteralWatcher::WatchUpperBound
void WatchUpperBound(IntegerVariable var, int id, int watch_index=-1)
Definition: integer.h:1374
operations_research::sat::TimeTablingPerTask::RegisterWith
void RegisterWith(GenericLiteralWatcher *watcher)
Definition: timetable.cc:61
time
int64 time
Definition: resource.cc:1683
operations_research::sat::SchedulingConstraintHelper::AddPresenceReason
void AddPresenceReason(int t)
Definition: intervals.h:472
operations_research::sat::SchedulingConstraintHelper::PushIntegerLiteral
ABSL_MUST_USE_RESULT bool PushIntegerLiteral(IntegerLiteral lit)
Definition: intervals.cc:378