OR-Tools  8.0
disjunctive.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 
15 
16 #include <memory>
17 
19 #include "ortools/base/logging.h"
21 #include "ortools/sat/integer.h"
23 #include "ortools/sat/sat_solver.h"
24 #include "ortools/sat/timetable.h"
25 #include "ortools/util/sort.h"
26 
27 namespace operations_research {
28 namespace sat {
29 
30 std::function<void(Model*)> Disjunctive(
31  const std::vector<IntervalVariable>& vars) {
32  return [=](Model* model) {
33  bool is_all_different = true;
34  IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
35  for (const IntervalVariable var : vars) {
36  if (repository->IsOptional(var) || repository->MinSize(var) != 1 ||
37  repository->MaxSize(var) != 1) {
38  is_all_different = false;
39  break;
40  }
41  }
42  if (is_all_different) {
43  std::vector<IntegerVariable> starts;
44  starts.reserve(vars.size());
45  for (const IntervalVariable var : vars) {
46  starts.push_back(model->Get(StartVar(var)));
47  }
48  model->Add(AllDifferentOnBounds(starts));
49  return;
50  }
51 
52  auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
53  const auto& sat_parameters = *model->GetOrCreate<SatParameters>();
54  if (vars.size() > 2 && sat_parameters.use_combined_no_overlap()) {
55  model->GetOrCreate<CombinedDisjunctive<true>>()->AddNoOverlap(vars);
56  model->GetOrCreate<CombinedDisjunctive<false>>()->AddNoOverlap(vars);
57  return;
58  }
59 
62  model->TakeOwnership(helper);
63 
64  // Experiments to use the timetable only to propagate the disjunctive.
65  if (/*DISABLES_CODE*/ (false)) {
66  const AffineExpression one(IntegerValue(1));
67  std::vector<AffineExpression> demands(vars.size(), one);
68  TimeTablingPerTask* timetable = new TimeTablingPerTask(
69  demands, one, model->GetOrCreate<IntegerTrail>(), helper);
70  timetable->RegisterWith(watcher);
71  model->TakeOwnership(timetable);
72  return;
73  }
74 
75  if (vars.size() == 2) {
76  DisjunctiveWithTwoItems* propagator = new DisjunctiveWithTwoItems(helper);
77  propagator->RegisterWith(watcher);
78  model->TakeOwnership(propagator);
79  } else {
80  // We decided to create the propagators in this particular order, but it
81  // shouldn't matter much because of the different priorities used.
82  {
83  // Only one direction is needed by this one.
84  DisjunctiveOverloadChecker* overload_checker =
85  new DisjunctiveOverloadChecker(helper);
86  const int id = overload_checker->RegisterWith(watcher);
87  watcher->SetPropagatorPriority(id, 1);
88  model->TakeOwnership(overload_checker);
89  }
90  for (const bool time_direction : {true, false}) {
91  DisjunctiveDetectablePrecedences* detectable_precedences =
92  new DisjunctiveDetectablePrecedences(time_direction, helper);
93  const int id = detectable_precedences->RegisterWith(watcher);
94  watcher->SetPropagatorPriority(id, 2);
95  model->TakeOwnership(detectable_precedences);
96  }
97  for (const bool time_direction : {true, false}) {
98  DisjunctiveNotLast* not_last =
99  new DisjunctiveNotLast(time_direction, helper);
100  const int id = not_last->RegisterWith(watcher);
101  watcher->SetPropagatorPriority(id, 3);
102  model->TakeOwnership(not_last);
103  }
104  for (const bool time_direction : {true, false}) {
105  DisjunctiveEdgeFinding* edge_finding =
106  new DisjunctiveEdgeFinding(time_direction, helper);
107  const int id = edge_finding->RegisterWith(watcher);
108  watcher->SetPropagatorPriority(id, 4);
109  model->TakeOwnership(edge_finding);
110  }
111  }
112 
113  // Note that we keep this one even when there is just two intervals. This is
114  // because it might push a variable that is after both of the intervals
115  // using the fact that they are in disjunction.
116  if (sat_parameters.use_precedences_in_disjunctive_constraint() &&
117  !sat_parameters.use_combined_no_overlap()) {
118  for (const bool time_direction : {true, false}) {
120  time_direction, helper, model->GetOrCreate<IntegerTrail>(),
121  model->GetOrCreate<PrecedencesPropagator>());
122  const int id = precedences->RegisterWith(watcher);
123  watcher->SetPropagatorPriority(id, 5);
124  model->TakeOwnership(precedences);
125  }
126  }
127  };
128 }
129 
131  const std::vector<IntervalVariable>& vars) {
132  return [=](Model* model) {
133  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
134  IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
135  PrecedencesPropagator* precedences =
136  model->GetOrCreate<PrecedencesPropagator>();
137  for (int i = 0; i < vars.size(); ++i) {
138  for (int j = 0; j < i; ++j) {
139  const BooleanVariable boolean_var = sat_solver->NewBooleanVariable();
140  const Literal i_before_j = Literal(boolean_var, true);
141  const Literal j_before_i = i_before_j.Negated();
142  precedences->AddConditionalPrecedence(repository->EndVar(vars[i]),
143  repository->StartVar(vars[j]),
144  i_before_j);
145  precedences->AddConditionalPrecedence(repository->EndVar(vars[j]),
146  repository->StartVar(vars[i]),
147  j_before_i);
148  }
149  }
150  };
151 }
152 
154  const std::vector<IntervalVariable>& vars) {
155  return [=](Model* model) {
157  model->Add(Disjunctive(vars));
158  };
159 }
160 
161 void TaskSet::AddEntry(const Entry& e) {
162  int j = sorted_tasks_.size();
163  sorted_tasks_.push_back(e);
164  while (j > 0 && sorted_tasks_[j - 1].start_min > e.start_min) {
165  sorted_tasks_[j] = sorted_tasks_[j - 1];
166  --j;
167  }
168  sorted_tasks_[j] = e;
169  DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
170 
171  // If the task is added after optimized_restart_, we know that we don't need
172  // to scan the task before optimized_restart_ in the next ComputeEndMin().
173  if (j <= optimized_restart_) optimized_restart_ = 0;
174 }
175 
177  int t) {
178  const IntegerValue dmin = helper.DurationMin(t);
179  AddEntry({t, std::max(helper.StartMin(t), helper.EndMin(t) - dmin), dmin});
180 }
181 
183  const int size = sorted_tasks_.size();
184  for (int i = 0;; ++i) {
185  if (i == size) return;
186  if (sorted_tasks_[i].task == e.task) {
187  sorted_tasks_.erase(sorted_tasks_.begin() + i);
188  break;
189  }
190  }
191 
192  optimized_restart_ = sorted_tasks_.size();
193  sorted_tasks_.push_back(e);
194  DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
195 }
196 
198  sorted_tasks_.erase(sorted_tasks_.begin() + index);
199  optimized_restart_ = 0;
200 }
201 
202 IntegerValue TaskSet::ComputeEndMin() const {
203  DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
204  const int size = sorted_tasks_.size();
205  IntegerValue end_min = kMinIntegerValue;
206  for (int i = optimized_restart_; i < size; ++i) {
207  const Entry& e = sorted_tasks_[i];
208  if (e.start_min >= end_min) {
209  optimized_restart_ = i;
211  } else {
212  end_min += e.duration_min;
213  }
214  }
215  return end_min;
216 }
217 
218 IntegerValue TaskSet::ComputeEndMin(int task_to_ignore,
219  int* critical_index) const {
220  // The order in which we process tasks with the same start-min doesn't matter.
221  DCHECK(std::is_sorted(sorted_tasks_.begin(), sorted_tasks_.end()));
222  bool ignored = false;
223  const int size = sorted_tasks_.size();
224  IntegerValue end_min = kMinIntegerValue;
225 
226  // If the ignored task is last and was the start of the critical block, then
227  // we need to reset optimized_restart_.
228  if (optimized_restart_ + 1 == size &&
229  sorted_tasks_[optimized_restart_].task == task_to_ignore) {
230  optimized_restart_ = 0;
231  }
232 
233  for (int i = optimized_restart_; i < size; ++i) {
234  const Entry& e = sorted_tasks_[i];
235  if (e.task == task_to_ignore) {
236  ignored = true;
237  continue;
238  }
239  if (e.start_min >= end_min) {
240  *critical_index = i;
241  if (!ignored) optimized_restart_ = i;
243  } else {
244  end_min += e.duration_min;
245  }
246  }
247  return end_min;
248 }
249 
251  DCHECK_EQ(helper_->NumTasks(), 2);
252 
253  // We can't propagate anything if one of the interval is absent for sure.
254  if (helper_->IsAbsent(0) || helper_->IsAbsent(1)) return true;
255 
256  // Note that this propagation also take care of the "overload checker" part.
257  // It also propagates as much as possible, even in the presence of task with
258  // variable durations.
259  //
260  // TODO(user): For optional interval whose presense in unknown and without
261  // optional variable, the end-min may not be propagated to at least (start_min
262  // + duration_min). Consider that into the computation so we may decide the
263  // interval forced absence? Same for the start-max.
264  int task_before = 0;
265  int task_after = 1;
266  if (helper_->StartMax(0) < helper_->EndMin(1)) {
267  // Task 0 must be before task 1.
268  } else if (helper_->StartMax(1) < helper_->EndMin(0)) {
269  // Task 1 must be before task 0.
270  std::swap(task_before, task_after);
271  } else {
272  return true;
273  }
274 
275  if (helper_->IsPresent(task_before)) {
276  const IntegerValue end_min_before = helper_->EndMin(task_before);
277  if (helper_->StartMin(task_after) < end_min_before) {
278  // Reason for precedences if both present.
279  helper_->ClearReason();
280  helper_->AddReasonForBeingBefore(task_before, task_after);
281 
282  // Reason for the bound push.
283  helper_->AddPresenceReason(task_before);
284  helper_->AddEndMinReason(task_before, end_min_before);
285  if (!helper_->IncreaseStartMin(task_after, end_min_before)) {
286  return false;
287  }
288  }
289  }
290 
291  if (helper_->IsPresent(task_after)) {
292  const IntegerValue start_max_after = helper_->StartMax(task_after);
293  if (helper_->EndMax(task_before) > start_max_after) {
294  // Reason for precedences if both present.
295  helper_->ClearReason();
296  helper_->AddReasonForBeingBefore(task_before, task_after);
297 
298  // Reason for the bound push.
299  helper_->AddPresenceReason(task_after);
300  helper_->AddStartMaxReason(task_after, start_max_after);
301  if (!helper_->DecreaseEndMax(task_before, start_max_after)) {
302  return false;
303  }
304  }
305  }
306 
307  return true;
308 }
309 
311  // This propagator reach the fix point in one pass.
312  const int id = watcher->Register(this);
313  helper_->WatchAllTasks(id, watcher);
314  return id;
315 }
316 
317 template <bool time_direction>
319  : helper_(model->GetOrCreate<AllIntervalsHelper>()) {
320  helper_->SetTimeDirection(time_direction);
321  task_to_disjunctives_.resize(helper_->NumTasks());
322 
323  auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
324  const int id = watcher->Register(this);
325  helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/true,
326  /*watch_end_max=*/false);
327  watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(id);
328 }
329 
330 template <bool time_direction>
332  const std::vector<IntervalVariable>& vars) {
333  const int index = task_sets_.size();
334  task_sets_.emplace_back(vars.size());
335  end_mins_.push_back(kMinIntegerValue);
336  for (const IntervalVariable var : vars) {
337  task_to_disjunctives_[var.value()].push_back(index);
338  }
339 }
340 
341 template <bool time_direction>
343  helper_->SetTimeDirection(time_direction);
344  const auto& task_by_increasing_end_min = helper_->TaskByIncreasingEndMin();
345  const auto& task_by_decreasing_start_max =
346  helper_->TaskByDecreasingStartMax();
347 
348  for (auto& task_set : task_sets_) task_set.Clear();
349  end_mins_.assign(end_mins_.size(), kMinIntegerValue);
350  IntegerValue max_of_end_min = kMinIntegerValue;
351 
352  const int num_tasks = helper_->NumTasks();
353  task_is_added_.assign(num_tasks, false);
354  int queue_index = num_tasks - 1;
355  for (const auto task_time : task_by_increasing_end_min) {
356  const int t = task_time.task_index;
357  const IntegerValue end_min = task_time.time;
358  if (helper_->IsAbsent(t)) continue;
359 
360  // Update all task sets.
361  while (queue_index >= 0) {
362  const auto to_insert = task_by_decreasing_start_max[queue_index];
363  const int task_index = to_insert.task_index;
364  const IntegerValue start_max = to_insert.time;
365  if (end_min <= start_max) break;
366  if (helper_->IsPresent(task_index)) {
367  task_is_added_[task_index] = true;
368  const IntegerValue shifted_smin = helper_->ShiftedStartMin(task_index);
369  const IntegerValue duration_min = helper_->DurationMin(task_index);
370  for (const int d_index : task_to_disjunctives_[task_index]) {
371  // TODO(user): AddEntry() and ComputeEndMin() could be combined.
372  task_sets_[d_index].AddEntry(
373  {task_index, shifted_smin, duration_min});
374  end_mins_[d_index] = task_sets_[d_index].ComputeEndMin();
375  max_of_end_min = std::max(max_of_end_min, end_mins_[d_index]);
376  }
377  }
378  --queue_index;
379  }
380 
381  // Find out amongst the disjunctives in which t appear, the one with the
382  // largest end_min, ignoring t itself. This will be the new start min for t.
383  IntegerValue new_start_min = helper_->StartMin(t);
384  if (new_start_min >= max_of_end_min) continue;
385  int best_critical_index = 0;
386  int best_d_index = -1;
387  if (task_is_added_[t]) {
388  for (const int d_index : task_to_disjunctives_[t]) {
389  if (new_start_min >= end_mins_[d_index]) continue;
390  int critical_index = 0;
391  const IntegerValue end_min_of_critical_tasks =
392  task_sets_[d_index].ComputeEndMin(/*task_to_ignore=*/t,
393  &critical_index);
394  DCHECK_LE(end_min_of_critical_tasks, max_of_end_min);
395  if (end_min_of_critical_tasks > new_start_min) {
396  new_start_min = end_min_of_critical_tasks;
397  best_d_index = d_index;
398  best_critical_index = critical_index;
399  }
400  }
401  } else {
402  // If the task t was not added, then there is no task to ignore and
403  // end_mins_[d_index] is up to date.
404  for (const int d_index : task_to_disjunctives_[t]) {
405  if (end_mins_[d_index] > new_start_min) {
406  new_start_min = end_mins_[d_index];
407  best_d_index = d_index;
408  }
409  }
410  if (best_d_index != -1) {
411  const IntegerValue end_min_of_critical_tasks =
412  task_sets_[best_d_index].ComputeEndMin(/*task_to_ignore=*/t,
413  &best_critical_index);
414  CHECK_EQ(end_min_of_critical_tasks, new_start_min);
415  }
416  }
417 
418  // Do we push something?
419  if (best_d_index == -1) continue;
420 
421  // Same reason as DisjunctiveDetectablePrecedences.
422  // TODO(user): Maybe factor out the code? It does require a function with a
423  // lot of arguments though.
424  helper_->ClearReason();
425  const std::vector<TaskSet::Entry>& sorted_tasks =
426  task_sets_[best_d_index].SortedTasks();
427  const IntegerValue window_start =
428  sorted_tasks[best_critical_index].start_min;
429  for (int i = best_critical_index; i < sorted_tasks.size(); ++i) {
430  const int ct = sorted_tasks[i].task;
431  if (ct == t) continue;
432  helper_->AddPresenceReason(ct);
433  helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
434  window_start);
435  helper_->AddStartMaxReason(ct, end_min - 1);
436  }
437  helper_->AddEndMinReason(t, end_min);
438  if (!helper_->IncreaseStartMin(t, new_start_min)) {
439  return false;
440  }
441 
442  // We need to reorder t inside task_set_. Note that if t is in the set,
443  // it means that the task is present and that IncreaseStartMin() did push
444  // its start (by opposition to an optional interval where the push might
445  // not happen if its start is not optional).
446  if (task_is_added_[t]) {
447  const IntegerValue shifted_smin = helper_->ShiftedStartMin(t);
448  const IntegerValue duration_min = helper_->DurationMin(t);
449  for (const int d_index : task_to_disjunctives_[t]) {
450  task_sets_[d_index].NotifyEntryIsNowLastIfPresent(
451  {t, shifted_smin, duration_min});
452  end_mins_[d_index] = task_sets_[d_index].ComputeEndMin();
453  max_of_end_min = std::max(max_of_end_min, end_mins_[d_index]);
454  }
455  }
456  }
457  return true;
458 }
459 
461  helper_->SetTimeDirection(/*is_forward=*/true);
462 
463  // Split problem into independent part.
464  //
465  // Many propagators in this file use the same approach, we start by processing
466  // the task by increasing start-min, packing everything to the left. We then
467  // process each "independent" set of task separately. A task is independent
468  // from the one before it, if its start-min wasn't pushed.
469  //
470  // This way, we get one or more window [window_start, window_end] so that for
471  // all task in the window, [start_min, end_min] is inside the window, and the
472  // end min of any set of task to the left is <= window_start, and the
473  // start_min of any task to the right is >= end_min.
474  window_.clear();
475  IntegerValue window_end = kMinIntegerValue;
476  IntegerValue relevant_end;
477  int relevant_size = 0;
478  for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
479  const int task = task_time.task_index;
480  if (helper_->IsAbsent(task)) continue;
481 
482  const IntegerValue start_min = task_time.time;
483  if (start_min < window_end) {
484  window_.push_back(task_time);
485  window_end += helper_->DurationMin(task);
486  if (window_end > helper_->EndMax(task)) {
487  relevant_size = window_.size();
488  relevant_end = window_end;
489  }
490  continue;
491  }
492 
493  // Process current window.
494  // We don't need to process the end of the window (after relevant_size)
495  // because these interval can be greedily assembled in a feasible solution.
496  window_.resize(relevant_size);
497  if (relevant_size > 0 && !PropagateSubwindow(relevant_end)) {
498  return false;
499  }
500 
501  // Start of the next window.
502  window_.clear();
503  window_.push_back(task_time);
504  window_end = start_min + helper_->DurationMin(task);
505  relevant_size = 0;
506  }
507 
508  // Process last window.
509  window_.resize(relevant_size);
510  if (relevant_size > 0 && !PropagateSubwindow(relevant_end)) {
511  return false;
512  }
513 
514  return true;
515 }
516 
517 // TODO(user): Improve the Overload Checker using delayed insertion.
518 // We insert events at the cost of O(log n) per insertion, and this is where
519 // the algorithm spends most of its time, thus it is worth improving.
520 // We can insert an arbitrary set of tasks at the cost of O(n) for the whole
521 // set. This is useless for the overload checker as is since we need to check
522 // overload after every insertion, but we could use an upper bound of the
523 // theta envelope to save us from checking the actual value.
524 bool DisjunctiveOverloadChecker::PropagateSubwindow(
525  IntegerValue global_window_end) {
526  // Set up theta tree and task_by_increasing_end_max_.
527  const int window_size = window_.size();
528  theta_tree_.Reset(window_size);
529  task_by_increasing_end_max_.clear();
530  for (int i = 0; i < window_size; ++i) {
531  // No point adding a task if its end_max is too large.
532  const int task = window_[i].task_index;
533  const IntegerValue end_max = helper_->EndMax(task);
534  if (end_max < global_window_end) {
535  task_to_event_[task] = i;
536  task_by_increasing_end_max_.push_back({task, end_max});
537  }
538  }
539 
540  // Introduce events by increasing end_max, check for overloads.
541  std::sort(task_by_increasing_end_max_.begin(),
542  task_by_increasing_end_max_.end());
543  for (const auto task_time : task_by_increasing_end_max_) {
544  const int current_task = task_time.task_index;
545 
546  // We filtered absent task while constructing the subwindow, but it is
547  // possible that as we propagate task absence below, other task also become
548  // absent (if they share the same presence Boolean).
549  if (helper_->IsAbsent(current_task)) continue;
550 
551  DCHECK_NE(task_to_event_[current_task], -1);
552  {
553  const int current_event = task_to_event_[current_task];
554  const IntegerValue energy_min = helper_->DurationMin(current_task);
555  if (helper_->IsPresent(current_task)) {
556  // TODO(user,user): Add max energy deduction for variable
557  // durations by putting the energy_max here and modifying the code
558  // dealing with the optional envelope greater than current_end below.
559  theta_tree_.AddOrUpdateEvent(current_event, window_[current_event].time,
560  energy_min, energy_min);
561  } else {
562  theta_tree_.AddOrUpdateOptionalEvent(
563  current_event, window_[current_event].time, energy_min);
564  }
565  }
566 
567  const IntegerValue current_end = task_time.time;
568  if (theta_tree_.GetEnvelope() > current_end) {
569  // Explain failure with tasks in critical interval.
570  helper_->ClearReason();
571  const int critical_event =
572  theta_tree_.GetMaxEventWithEnvelopeGreaterThan(current_end);
573  const IntegerValue window_start = window_[critical_event].time;
574  const IntegerValue window_end =
575  theta_tree_.GetEnvelopeOf(critical_event) - 1;
576  for (int event = critical_event; event < window_size; event++) {
577  const IntegerValue energy_min = theta_tree_.EnergyMin(event);
578  if (energy_min > 0) {
579  const int task = window_[event].task_index;
580  helper_->AddPresenceReason(task);
581  helper_->AddEnergyAfterReason(task, energy_min, window_start);
582  helper_->AddEndMaxReason(task, window_end);
583  }
584  }
585  return helper_->ReportConflict();
586  }
587 
588  // Exclude all optional tasks that would overload an interval ending here.
589  while (theta_tree_.GetOptionalEnvelope() > current_end) {
590  // Explain exclusion with tasks present in the critical interval.
591  // TODO(user): This could be done lazily, like most of the loop to
592  // compute the reasons in this file.
593  helper_->ClearReason();
594  int critical_event;
595  int optional_event;
596  IntegerValue available_energy;
598  current_end, &critical_event, &optional_event, &available_energy);
599 
600  const int optional_task = window_[optional_event].task_index;
601  const IntegerValue optional_duration_min =
602  helper_->DurationMin(optional_task);
603  const IntegerValue window_start = window_[critical_event].time;
604  const IntegerValue window_end =
605  current_end + optional_duration_min - available_energy - 1;
606  for (int event = critical_event; event < window_size; event++) {
607  const IntegerValue energy_min = theta_tree_.EnergyMin(event);
608  if (energy_min > 0) {
609  const int task = window_[event].task_index;
610  helper_->AddPresenceReason(task);
611  helper_->AddEnergyAfterReason(task, energy_min, window_start);
612  helper_->AddEndMaxReason(task, window_end);
613  }
614  }
615 
616  helper_->AddEnergyAfterReason(optional_task, optional_duration_min,
617  window_start);
618  helper_->AddEndMaxReason(optional_task, window_end);
619 
620  // If tasks shares the same presence literal, it is possible that we
621  // already pushed this task absence.
622  if (!helper_->IsAbsent(optional_task)) {
623  if (!helper_->PushTaskAbsence(optional_task)) return false;
624  }
625  theta_tree_.RemoveEvent(optional_event);
626  }
627  }
628 
629  return true;
630 }
631 
633  // This propagator reach the fix point in one pass.
634  const int id = watcher->Register(this);
635  helper_->SetTimeDirection(/*is_forward=*/true);
636  helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/false,
637  /*watch_end_max=*/true);
638  return id;
639 }
640 
642  helper_->SetTimeDirection(time_direction_);
643 
644  to_propagate_.clear();
645  processed_.assign(helper_->NumTasks(), false);
646 
647  // Split problem into independent part.
648  //
649  // The "independent" window can be processed separately because for each of
650  // them, a task [start-min, end-min] is in the window [window_start,
651  // window_end]. So any task to the left of the window cannot push such
652  // task start_min, and any task to the right of the window will have a
653  // start_max >= end_min, so wouldn't be in detectable precedence.
654  task_by_increasing_end_min_.clear();
655  IntegerValue window_end = kMinIntegerValue;
656  for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
657  const int task = task_time.task_index;
658  if (helper_->IsAbsent(task)) continue;
659 
660  const IntegerValue shifted_smin = task_time.time;
661  const IntegerValue duration_min = helper_->DurationMin(task);
662  const IntegerValue end_min_if_present = shifted_smin + duration_min;
663 
664  // Note that we use the real StartMin() here, as this is the one we will
665  // push.
666  if (helper_->StartMin(task) < window_end) {
667  task_by_increasing_end_min_.push_back({task, end_min_if_present});
668  window_end = std::max(window_end, task_time.time) + duration_min;
669  continue;
670  }
671 
672  // Process current window.
673  if (task_by_increasing_end_min_.size() > 1 && !PropagateSubwindow()) {
674  return false;
675  }
676 
677  // Start of the next window.
678  task_by_increasing_end_min_.clear();
679  task_by_increasing_end_min_.push_back({task, end_min_if_present});
680  window_end = end_min_if_present;
681  }
682 
683  if (task_by_increasing_end_min_.size() > 1 && !PropagateSubwindow()) {
684  return false;
685  }
686 
687  return true;
688 }
689 
690 bool DisjunctiveDetectablePrecedences::PropagateSubwindow() {
691  DCHECK(!task_by_increasing_end_min_.empty());
692 
693  // The vector is already sorted by shifted_start_min, so there is likely a
694  // good correlation, hence the incremental sort.
695  IncrementalSort(task_by_increasing_end_min_.begin(),
696  task_by_increasing_end_min_.end());
697  const IntegerValue max_end_min = task_by_increasing_end_min_.back().time;
698 
699  // Fill and sort task_by_increasing_start_max_.
700  task_by_increasing_start_max_.clear();
701  for (const TaskTime entry : task_by_increasing_end_min_) {
702  const int task = entry.task_index;
703  const IntegerValue start_max = helper_->StartMax(task);
704  if (start_max < max_end_min && helper_->IsPresent(task)) {
705  task_by_increasing_start_max_.push_back({task, start_max});
706  }
707  }
708  if (task_by_increasing_start_max_.empty()) return true;
709  std::sort(task_by_increasing_start_max_.begin(),
710  task_by_increasing_start_max_.end());
711 
712  // Invariant: need_update is false implies that task_set_end_min is equal to
713  // task_set_.ComputeEndMin().
714  //
715  // TODO(user): Maybe it is just faster to merge ComputeEndMin() with
716  // AddEntry().
717  task_set_.Clear();
718  bool need_update = false;
719  IntegerValue task_set_end_min = kMinIntegerValue;
720 
721  int queue_index = 0;
722  int blocking_task = -1;
723  const int queue_size = task_by_increasing_start_max_.size();
724  for (const auto task_time : task_by_increasing_end_min_) {
725  // Note that we didn't put absent task in task_by_increasing_end_min_, but
726  // the absence might have been pushed while looping here. This is fine since
727  // any push we do on this task should handle this case correctly.
728  //
729  // TODO(user): Still test and continue the status even if in most cases the
730  // task will not be absent?
731  const int current_task = task_time.task_index;
732 
733  for (; queue_index < queue_size; ++queue_index) {
734  const auto to_insert = task_by_increasing_start_max_[queue_index];
735  const IntegerValue start_max = to_insert.time;
736  const IntegerValue current_end_min = task_time.time;
737  if (current_end_min <= start_max) break;
738 
739  const int t = to_insert.task_index;
740  DCHECK(helper_->IsPresent(t));
741 
742  // If t has not been processed yet, it has a mandatory part, and rather
743  // than adding it right away to task_set, we will delay all propagation
744  // until current_task is equal to this "blocking task".
745  //
746  // This idea is introduced in "Linear-Time Filtering Algorithms for the
747  // Disjunctive Constraints" Hamed Fahimi, Claude-Guy Quimper.
748  //
749  // Experiments seems to indicate that it is slighlty faster rather than
750  // having to ignore one of the task already inserted into task_set_ when
751  // we have tasks with mandatory parts. It also open-up more option for the
752  // data structure used in task_set_.
753  if (!processed_[t]) {
754  if (blocking_task != -1) {
755  // We have two blocking tasks, which means they are in conflict.
756  helper_->ClearReason();
757  helper_->AddPresenceReason(blocking_task);
758  helper_->AddPresenceReason(t);
759  helper_->AddReasonForBeingBefore(blocking_task, t);
760  helper_->AddReasonForBeingBefore(t, blocking_task);
761  return helper_->ReportConflict();
762  }
763  DCHECK_LT(start_max,
764  helper_->ShiftedStartMin(t) + helper_->DurationMin(t));
765  DCHECK(to_propagate_.empty());
766  blocking_task = t;
767  to_propagate_.push_back(t);
768  } else {
769  need_update = true;
770  task_set_.AddShiftedStartMinEntry(*helper_, t);
771  }
772  }
773 
774  // If we have a blocking task, we delay the propagation until current_task
775  // is the blocking task.
776  if (blocking_task != current_task) {
777  to_propagate_.push_back(current_task);
778  if (blocking_task != -1) continue;
779  }
780  for (const int t : to_propagate_) {
781  DCHECK(!processed_[t]);
782  processed_[t] = true;
783  if (need_update) {
784  need_update = false;
785  task_set_end_min = task_set_.ComputeEndMin();
786  }
787 
788  // task_set_ contains all the tasks that must be executed before t. They
789  // are in "detectable precedence" because their start_max is smaller than
790  // the end-min of t like so:
791  // [(the task t)
792  // (a task in task_set_)]
793  // From there, we deduce that the start-min of t is greater or equal to
794  // the end-min of the critical tasks.
795  //
796  // Note that this works as well when IsPresent(t) is false.
797  if (task_set_end_min > helper_->StartMin(t)) {
798  const int critical_index = task_set_.GetCriticalIndex();
799  const std::vector<TaskSet::Entry>& sorted_tasks =
800  task_set_.SortedTasks();
801  helper_->ClearReason();
802 
803  // We need:
804  // - StartMax(ct) < EndMin(t) for the detectable precedence.
805  // - StartMin(ct) >= window_start for the value of task_set_end_min.
806  const IntegerValue end_min_if_present =
807  helper_->ShiftedStartMin(t) + helper_->DurationMin(t);
808  const IntegerValue window_start =
809  sorted_tasks[critical_index].start_min;
810  for (int i = critical_index; i < sorted_tasks.size(); ++i) {
811  const int ct = sorted_tasks[i].task;
812  DCHECK_NE(ct, t);
813  helper_->AddPresenceReason(ct);
814  helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
815  window_start);
816  helper_->AddStartMaxReason(ct, end_min_if_present - 1);
817  }
818 
819  // Add the reason for t (we only need the end-min).
820  helper_->AddEndMinReason(t, end_min_if_present);
821 
822  // This augment the start-min of t. Note that t is not in task set
823  // yet, so we will use this updated start if we ever add it there.
824  if (!helper_->IncreaseStartMin(t, task_set_end_min)) {
825  return false;
826  }
827  }
828 
829  if (t == blocking_task) {
830  // Insert the blocking_task. Note that because we just pushed it,
831  // it will be last in task_set_ and also the only reason used to push
832  // any of the subsequent tasks. In particular, the reason will be valid
833  // even though task_set might contains tasks with a start_max greater or
834  // equal to the end_min of the task we push.
835  need_update = true;
836  blocking_task = -1;
837  task_set_.AddShiftedStartMinEntry(*helper_, t);
838  }
839  }
840  to_propagate_.clear();
841  }
842  return true;
843 }
844 
846  GenericLiteralWatcher* watcher) {
847  const int id = watcher->Register(this);
848  helper_->SetTimeDirection(time_direction_);
849  helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/true,
850  /*watch_end_max=*/false);
852  return id;
853 }
854 
856  helper_->SetTimeDirection(time_direction_);
857  window_.clear();
858  IntegerValue window_end = kMinIntegerValue;
859  for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
860  const int task = task_time.task_index;
861  if (!helper_->IsPresent(task)) continue;
862 
863  const IntegerValue start_min = task_time.time;
864  if (start_min < window_end) {
865  window_.push_back(task_time);
866  window_end += helper_->DurationMin(task);
867  continue;
868  }
869 
870  if (window_.size() > 1 && !PropagateSubwindow()) {
871  return false;
872  }
873 
874  // Start of the next window.
875  window_.clear();
876  window_.push_back(task_time);
877  window_end = start_min + helper_->DurationMin(task);
878  }
879  if (window_.size() > 1 && !PropagateSubwindow()) {
880  return false;
881  }
882  return true;
883 }
884 
885 bool DisjunctivePrecedences::PropagateSubwindow() {
886  index_to_end_vars_.clear();
887  for (const auto task_time : window_) {
888  const int task = task_time.task_index;
889  index_to_end_vars_.push_back(helper_->EndVars()[task]);
890  }
891  precedences_->ComputePrecedences(index_to_end_vars_, &before_);
892 
893  const int size = before_.size();
894  for (int i = 0; i < size;) {
895  const IntegerVariable var = before_[i].var;
896  DCHECK_NE(var, kNoIntegerVariable);
897  task_set_.Clear();
898 
899  const int initial_i = i;
900  IntegerValue min_offset = before_[i].offset;
901  for (; i < size && before_[i].var == var; ++i) {
902  const TaskTime task_time = window_[before_[i].index];
903  min_offset = std::min(min_offset, before_[i].offset);
904 
905  // The task are actually in sorted order, so we do not need to call
906  // task_set_.Sort(). This property is DCHECKed.
907  task_set_.AddUnsortedEntry({task_time.task_index, task_time.time,
908  helper_->DurationMin(task_time.task_index)});
909  }
910  DCHECK_GE(task_set_.SortedTasks().size(), 2);
911  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
912 
913  // TODO(user): Only use the min_offset of the critical task? Or maybe do a
914  // more general computation to find by how much we can push var?
915  const IntegerValue new_lb = task_set_.ComputeEndMin() + min_offset;
916  if (new_lb > integer_trail_->LowerBound(var)) {
917  const std::vector<TaskSet::Entry>& sorted_tasks = task_set_.SortedTasks();
918  helper_->ClearReason();
919 
920  // Fill task_to_arc_index_ since we need it for the reason.
921  // Note that we do not care about the initial content of this vector.
922  for (int j = initial_i; j < i; ++j) {
923  const int task = window_[before_[j].index].task_index;
924  task_to_arc_index_[task] = before_[j].arc_index;
925  }
926 
927  const int critical_index = task_set_.GetCriticalIndex();
928  const IntegerValue window_start = sorted_tasks[critical_index].start_min;
929  for (int i = critical_index; i < sorted_tasks.size(); ++i) {
930  const int ct = sorted_tasks[i].task;
931  helper_->AddPresenceReason(ct);
932  helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
933  window_start);
934  precedences_->AddPrecedenceReason(task_to_arc_index_[ct], min_offset,
935  helper_->MutableLiteralReason(),
936  helper_->MutableIntegerReason());
937  }
938 
939  // TODO(user): If var is actually a start-min of an interval, we
940  // could push the end-min and check the interval consistency right away.
941  if (!helper_->PushIntegerLiteral(
943  return false;
944  }
945  }
946  }
947  return true;
948 }
949 
951  // This propagator reach the fixed point in one go.
952  const int id = watcher->Register(this);
953  helper_->SetTimeDirection(time_direction_);
954  helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/false,
955  /*watch_end_max=*/false);
956  return id;
957 }
958 
960  helper_->SetTimeDirection(time_direction_);
961 
962  const auto& task_by_decreasing_start_max =
963  helper_->TaskByDecreasingStartMax();
964  const auto& task_by_increasing_shifted_start_min =
966 
967  // Split problem into independent part.
968  //
969  // The situation is trickier here, and we use two windows:
970  // - The classical "start_min_window_" as in the other propagator.
971  // - A second window, that includes all the task with a start_max inside
972  // [window_start, window_end].
973  //
974  // Now, a task from the second window can be detected to be "not last" by only
975  // looking at the task in the first window. Tasks to the left do not cause
976  // issue for the task to be last, and tasks to the right will not lower the
977  // end-min of the task under consideration.
978  int queue_index = task_by_decreasing_start_max.size() - 1;
979  const int num_tasks = task_by_increasing_shifted_start_min.size();
980  for (int i = 0; i < num_tasks;) {
981  start_min_window_.clear();
982  IntegerValue window_end = kMinIntegerValue;
983  for (; i < num_tasks; ++i) {
984  const TaskTime task_time = task_by_increasing_shifted_start_min[i];
985  const int task = task_time.task_index;
986  if (!helper_->IsPresent(task)) continue;
987 
988  const IntegerValue start_min = task_time.time;
989  if (start_min_window_.empty()) {
990  start_min_window_.push_back(task_time);
991  window_end = start_min + helper_->DurationMin(task);
992  } else if (start_min < window_end) {
993  start_min_window_.push_back(task_time);
994  window_end += helper_->DurationMin(task);
995  } else {
996  break;
997  }
998  }
999 
1000  // Add to start_max_window_ all the task whose start_max
1001  // fall into [window_start, window_end).
1002  start_max_window_.clear();
1003  for (; queue_index >= 0; queue_index--) {
1004  const auto task_time = task_by_decreasing_start_max[queue_index];
1005 
1006  // Note that we add task whose presence is still unknown here.
1007  if (task_time.time >= window_end) break;
1008  if (helper_->IsAbsent(task_time.task_index)) continue;
1009  start_max_window_.push_back(task_time);
1010  }
1011 
1012  // If this is the case, we cannot propagate more than the detectable
1013  // precedence propagator. Note that this continue must happen after we
1014  // computed start_max_window_ though.
1015  if (start_min_window_.size() <= 1) continue;
1016 
1017  // Process current window.
1018  if (!start_max_window_.empty() && !PropagateSubwindow()) {
1019  return false;
1020  }
1021  }
1022  return true;
1023 }
1024 
1025 bool DisjunctiveNotLast::PropagateSubwindow() {
1026  auto& task_by_increasing_end_max = start_max_window_;
1027  for (TaskTime& entry : task_by_increasing_end_max) {
1028  entry.time = helper_->EndMax(entry.task_index);
1029  }
1030  IncrementalSort(task_by_increasing_end_max.begin(),
1031  task_by_increasing_end_max.end());
1032 
1033  const IntegerValue threshold = task_by_increasing_end_max.back().time;
1034  auto& task_by_increasing_start_max = start_min_window_;
1035  int queue_size = 0;
1036  for (const TaskTime entry : task_by_increasing_start_max) {
1037  const int task = entry.task_index;
1038  const IntegerValue start_max = helper_->StartMax(task);
1039  DCHECK(helper_->IsPresent(task));
1040  if (start_max < threshold) {
1041  task_by_increasing_start_max[queue_size++] = {task, start_max};
1042  }
1043  }
1044 
1045  // If the size is one, we cannot propagate more than the detectable precedence
1046  // propagator.
1047  if (queue_size <= 1) return true;
1048 
1049  task_by_increasing_start_max.resize(queue_size);
1050  std::sort(task_by_increasing_start_max.begin(),
1051  task_by_increasing_start_max.end());
1052 
1053  task_set_.Clear();
1054  int queue_index = 0;
1055  for (const auto task_time : task_by_increasing_end_max) {
1056  const int t = task_time.task_index;
1057  const IntegerValue end_max = task_time.time;
1058  DCHECK(!helper_->IsAbsent(t));
1059 
1060  // task_set_ contains all the tasks that must start before the end-max of t.
1061  // These are the only candidates that have a chance to decrease the end-max
1062  // of t.
1063  while (queue_index < queue_size) {
1064  const auto to_insert = task_by_increasing_start_max[queue_index];
1065  const IntegerValue start_max = to_insert.time;
1066  if (end_max <= start_max) break;
1067 
1068  const int task_index = to_insert.task_index;
1069  DCHECK(helper_->IsPresent(task_index));
1070  task_set_.AddEntry({task_index, helper_->ShiftedStartMin(task_index),
1071  helper_->DurationMin(task_index)});
1072  ++queue_index;
1073  }
1074 
1075  // In the following case, task t cannot be after all the critical tasks
1076  // (i.e. it cannot be last):
1077  //
1078  // [(critical tasks)
1079  // | <- t start-max
1080  //
1081  // So we can deduce that the end-max of t is smaller than or equal to the
1082  // largest start-max of the critical tasks.
1083  //
1084  // Note that this works as well when the presence of t is still unknown.
1085  int critical_index = 0;
1086  const IntegerValue end_min_of_critical_tasks =
1087  task_set_.ComputeEndMin(/*task_to_ignore=*/t, &critical_index);
1088  if (end_min_of_critical_tasks <= helper_->StartMax(t)) continue;
1089 
1090  // Find the largest start-max of the critical tasks (excluding t). The
1091  // end-max for t need to be smaller than or equal to this.
1092  IntegerValue largest_ct_start_max = kMinIntegerValue;
1093  const std::vector<TaskSet::Entry>& sorted_tasks = task_set_.SortedTasks();
1094  const int sorted_tasks_size = sorted_tasks.size();
1095  for (int i = critical_index; i < sorted_tasks_size; ++i) {
1096  const int ct = sorted_tasks[i].task;
1097  if (t == ct) continue;
1098  const IntegerValue start_max = helper_->StartMax(ct);
1099  if (start_max > largest_ct_start_max) {
1100  largest_ct_start_max = start_max;
1101  }
1102  }
1103 
1104  // If we have any critical task, the test will always be true because
1105  // of the tasks we put in task_set_.
1106  DCHECK(largest_ct_start_max == kMinIntegerValue ||
1107  end_max > largest_ct_start_max);
1108  if (end_max > largest_ct_start_max) {
1109  helper_->ClearReason();
1110 
1111  const IntegerValue window_start = sorted_tasks[critical_index].start_min;
1112  for (int i = critical_index; i < sorted_tasks_size; ++i) {
1113  const int ct = sorted_tasks[i].task;
1114  if (ct == t) continue;
1115  helper_->AddPresenceReason(ct);
1116  helper_->AddEnergyAfterReason(ct, sorted_tasks[i].duration_min,
1117  window_start);
1118  helper_->AddStartMaxReason(ct, largest_ct_start_max);
1119  }
1120 
1121  // Add the reason for t, we only need the start-max.
1122  helper_->AddStartMaxReason(t, end_min_of_critical_tasks - 1);
1123 
1124  // Enqueue the new end-max for t.
1125  // Note that changing it will not influence the rest of the loop.
1126  if (!helper_->DecreaseEndMax(t, largest_ct_start_max)) return false;
1127  }
1128  }
1129  return true;
1130 }
1131 
1133  const int id = watcher->Register(this);
1134  helper_->WatchAllTasks(id, watcher);
1136  return id;
1137 }
1138 
1140  const int num_tasks = helper_->NumTasks();
1141  helper_->SetTimeDirection(time_direction_);
1142  is_gray_.resize(num_tasks, false);
1143  non_gray_task_to_event_.resize(num_tasks);
1144 
1145  window_.clear();
1146  IntegerValue window_end = kMinIntegerValue;
1147  for (const TaskTime task_time : helper_->TaskByIncreasingShiftedStartMin()) {
1148  const int task = task_time.task_index;
1149  if (helper_->IsAbsent(task)) continue;
1150 
1151  // Note that we use the real start min here not the shifted one. This is
1152  // because we might be able to push it if it is smaller than window end.
1153  if (helper_->StartMin(task) < window_end) {
1154  window_.push_back(task_time);
1155  window_end += helper_->DurationMin(task);
1156  continue;
1157  }
1158 
1159  // We need at least 3 tasks for the edge-finding to be different from
1160  // detectable precedences.
1161  if (window_.size() > 2 && !PropagateSubwindow(window_end)) {
1162  return false;
1163  }
1164 
1165  // Start of the next window.
1166  window_.clear();
1167  window_.push_back(task_time);
1168  window_end = task_time.time + helper_->DurationMin(task);
1169  }
1170  if (window_.size() > 2 && !PropagateSubwindow(window_end)) {
1171  return false;
1172  }
1173  return true;
1174 }
1175 
1176 bool DisjunctiveEdgeFinding::PropagateSubwindow(IntegerValue window_end_min) {
1177  // Cache the task end-max and abort early if possible.
1178  task_by_increasing_end_max_.clear();
1179  for (const auto task_time : window_) {
1180  const int task = task_time.task_index;
1181  DCHECK(!helper_->IsAbsent(task));
1182 
1183  // We already mark all the non-present task as gray.
1184  //
1185  // Same for task with an end-max that is too large: Tasks that are not
1186  // present can never trigger propagation or an overload checking failure.
1187  // theta_tree_.GetOptionalEnvelope() is always <= window_end, so tasks whose
1188  // end_max is >= window_end can never trigger propagation or failure either.
1189  // Thus, those tasks can be marked as gray, which removes their contribution
1190  // to theta right away.
1191  const IntegerValue end_max = helper_->EndMax(task);
1192  if (helper_->IsPresent(task) && end_max < window_end_min) {
1193  is_gray_[task] = false;
1194  task_by_increasing_end_max_.push_back({task, end_max});
1195  } else {
1196  is_gray_[task] = true;
1197  }
1198  }
1199 
1200  // If we have just 1 non-gray task, then this propagator does not propagate
1201  // more than the detectable precedences, so we abort early.
1202  if (task_by_increasing_end_max_.size() < 2) return true;
1203  std::sort(task_by_increasing_end_max_.begin(),
1204  task_by_increasing_end_max_.end());
1205 
1206  // Set up theta tree.
1207  //
1208  // Some task in the theta tree will be considered "gray".
1209  // When computing the end-min of the sorted task, we will compute it for:
1210  // - All the non-gray task
1211  // - All the non-gray task + at most one gray task.
1212  //
1213  // TODO(user): it should be faster to initialize it all at once rather
1214  // than calling AddOrUpdate() n times.
1215  const int window_size = window_.size();
1216  event_size_.clear();
1217  theta_tree_.Reset(window_size);
1218  for (int event = 0; event < window_size; ++event) {
1219  const TaskTime task_time = window_[event];
1220  const int task = task_time.task_index;
1221  const IntegerValue energy_min = helper_->DurationMin(task);
1222  event_size_.push_back(energy_min);
1223  if (is_gray_[task]) {
1224  theta_tree_.AddOrUpdateOptionalEvent(event, task_time.time, energy_min);
1225  } else {
1226  non_gray_task_to_event_[task] = event;
1227  theta_tree_.AddOrUpdateEvent(event, task_time.time, energy_min,
1228  energy_min);
1229  }
1230  }
1231 
1232  // At each iteration we either transform a non-gray task into a gray one or
1233  // remove a gray task, so this loop is linear in complexity.
1234  while (true) {
1235  DCHECK(!is_gray_[task_by_increasing_end_max_.back().task_index]);
1236  const IntegerValue non_gray_end_max =
1237  task_by_increasing_end_max_.back().time;
1238 
1239  // Overload checking.
1240  const IntegerValue non_gray_end_min = theta_tree_.GetEnvelope();
1241  if (non_gray_end_min > non_gray_end_max) {
1242  helper_->ClearReason();
1243 
1244  // We need the reasons for the critical tasks to fall in:
1245  const int critical_event =
1246  theta_tree_.GetMaxEventWithEnvelopeGreaterThan(non_gray_end_max);
1247  const IntegerValue window_start = window_[critical_event].time;
1248  const IntegerValue window_end =
1249  theta_tree_.GetEnvelopeOf(critical_event) - 1;
1250  for (int event = critical_event; event < window_size; event++) {
1251  const int task = window_[event].task_index;
1252  if (is_gray_[task]) continue;
1253  helper_->AddPresenceReason(task);
1254  helper_->AddEnergyAfterReason(task, event_size_[event], window_start);
1255  helper_->AddEndMaxReason(task, window_end);
1256  }
1257  return helper_->ReportConflict();
1258  }
1259 
1260  // Edge-finding.
1261  // If we have a situation like:
1262  // [(critical_task_with_gray_task)
1263  // ]
1264  // ^ end-max without the gray task.
1265  //
1266  // Then the gray task must be after all the critical tasks (all the non-gray
1267  // tasks in the tree actually), otherwise there will be no way to schedule
1268  // the critical_tasks inside their time window.
1269  while (theta_tree_.GetOptionalEnvelope() > non_gray_end_max) {
1270  int critical_event_with_gray;
1271  int gray_event;
1272  IntegerValue available_energy;
1274  non_gray_end_max, &critical_event_with_gray, &gray_event,
1275  &available_energy);
1276  const int gray_task = window_[gray_event].task_index;
1277 
1278  // Since the gray task is after all the other, we have a new lower bound.
1279  DCHECK(is_gray_[gray_task]);
1280  if (helper_->StartMin(gray_task) < non_gray_end_min) {
1281  // The API is not ideal here. We just want the start of the critical
1282  // tasks that explain the non_gray_end_min computed above.
1283  const int critical_event =
1284  theta_tree_.GetMaxEventWithEnvelopeGreaterThan(non_gray_end_min -
1285  1);
1286  const int first_event =
1287  std::min(critical_event, critical_event_with_gray);
1288  const int second_event =
1289  std::max(critical_event, critical_event_with_gray);
1290  const IntegerValue first_start = window_[first_event].time;
1291  const IntegerValue second_start = window_[second_event].time;
1292 
1293  // window_end is chosen to be has big as possible and still have an
1294  // overload if the gray task is not last.
1295  const IntegerValue window_end =
1296  non_gray_end_max + event_size_[gray_event] - available_energy - 1;
1297  CHECK_GE(window_end, non_gray_end_max);
1298 
1299  // The non-gray part of the explanation as detailed above.
1300  helper_->ClearReason();
1301  for (int event = first_event; event < window_size; event++) {
1302  const int task = window_[event].task_index;
1303  if (is_gray_[task]) continue;
1304  helper_->AddPresenceReason(task);
1305  helper_->AddEnergyAfterReason(
1306  task, event_size_[event],
1307  event >= second_event ? second_start : first_start);
1308  helper_->AddEndMaxReason(task, window_end);
1309  }
1310 
1311  // Add the reason for the gray_task (we don't need the end-max or
1312  // presence reason).
1313  helper_->AddEnergyAfterReason(gray_task, event_size_[gray_event],
1314  window_[critical_event_with_gray].time);
1315 
1316  // Enqueue the new start-min for gray_task.
1317  //
1318  // TODO(user): propagate the precedence Boolean here too? I think it
1319  // will be more powerful. Even if eventually all these precedence will
1320  // become detectable (see Petr Villim PhD).
1321  if (!helper_->IncreaseStartMin(gray_task, non_gray_end_min)) {
1322  return false;
1323  }
1324  }
1325 
1326  // Remove the gray_task.
1327  theta_tree_.RemoveEvent(gray_event);
1328  }
1329 
1330  // Stop before we get just one non-gray task.
1331  if (task_by_increasing_end_max_.size() <= 2) break;
1332 
1333  // Stop if the min of end_max is too big.
1334  if (task_by_increasing_end_max_[0].time >=
1335  theta_tree_.GetOptionalEnvelope()) {
1336  break;
1337  }
1338 
1339  // Make the non-gray task with larger end-max gray.
1340  const int new_gray_task = task_by_increasing_end_max_.back().task_index;
1341  task_by_increasing_end_max_.pop_back();
1342  const int new_gray_event = non_gray_task_to_event_[new_gray_task];
1343  DCHECK(!is_gray_[new_gray_task]);
1344  is_gray_[new_gray_task] = true;
1345  theta_tree_.AddOrUpdateOptionalEvent(new_gray_event,
1346  window_[new_gray_event].time,
1347  event_size_[new_gray_event]);
1348  }
1349 
1350  return true;
1351 }
1352 
1354  const int id = watcher->Register(this);
1355  helper_->SetTimeDirection(time_direction_);
1356  helper_->WatchAllTasks(id, watcher, /*watch_start_max=*/false,
1357  /*watch_end_max=*/true);
1359  return id;
1360 }
1361 
1362 } // namespace sat
1363 } // namespace operations_research
operations_research::sat::DisjunctiveDetectablePrecedences::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:845
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::DisjunctivePrecedences::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:950
operations_research::sat::TaskSet::Entry::start_min
IntegerValue start_min
Definition: disjunctive.h:62
min
int64 min
Definition: alldiff_cst.cc:138
operations_research::sat::TaskSet::Entry::duration_min
IntegerValue duration_min
Definition: disjunctive.h:63
operations_research::sat::IntegerLiteral::GreaterOrEqual
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1197
operations_research::sat::kNoIntegerVariable
const IntegerVariable kNoIntegerVariable(-1)
max
int64 max
Definition: alldiff_cst.cc:139
operations_research::sat::DisjunctiveNotLast::Propagate
bool Propagate() final
Definition: disjunctive.cc:959
operations_research::sat::SchedulingConstraintHelper::IsAbsent
bool IsAbsent(int t) const
Definition: intervals.h:397
operations_research::sat::SchedulingConstraintHelper::EndMax
IntegerValue EndMax(int t) const
Definition: intervals.h:371
operations_research::sat::DisjunctiveWithTwoItems::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:310
operations_research::sat::DisjunctivePrecedences::Propagate
bool Propagate() final
Definition: disjunctive.cc:855
operations_research::sat::SchedulingConstraintHelper::AddEndMaxReason
void AddEndMaxReason(int t, IntegerValue upper_bound)
Definition: intervals.h:473
operations_research::sat::TaskSet::RemoveEntryWithIndex
void RemoveEntryWithIndex(int index)
Definition: disjunctive.cc:197
operations_research::sat::SchedulingConstraintHelper::EndMin
IntegerValue EndMin(int t) const
Definition: intervals.h:367
all_different.h
operations_research::sat::TaskSet::AddUnsortedEntry
void AddUnsortedEntry(const Entry &e)
Definition: disjunctive.h:89
end_max
Rev< int64 > end_max
Definition: sched_constraints.cc:244
operations_research::sat::DisjunctiveDetectablePrecedences
Definition: disjunctive.h:158
operations_research::sat::TaskSet::SortedTasks
const std::vector< Entry > & SortedTasks() const
Definition: disjunctive.h:119
operations_research::sat::SchedulingConstraintHelper::AddReasonForBeingBefore
void AddReasonForBeingBefore(int before, int after)
Definition: intervals.cc:226
start_min
Rev< int64 > start_min
Definition: sched_constraints.cc:241
operations_research::sat::DisjunctiveNotLast::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:1132
operations_research::sat::TaskSet::Clear
void Clear()
Definition: disjunctive.h:70
logging.h
disjunctive.h
operations_research::sat::SatSolver::NewBooleanVariable
BooleanVariable NewBooleanVariable()
Definition: sat_solver.h:84
operations_research::sat::StartVar
std::function< IntegerVariable(const Model &)> StartVar(IntervalVariable v)
Definition: intervals.h:501
operations_research::sat::SchedulingConstraintHelper::SetTimeDirection
void SetTimeDirection(bool is_forward)
Definition: intervals.cc:142
operations_research::sat::TaskSet::GetCriticalIndex
int GetCriticalIndex() const
Definition: disjunctive.h:117
operations_research::sat::AllIntervalsHelper
Definition: disjunctive.h:184
operations_research::sat::SchedulingConstraintHelper
Definition: intervals.h:137
operations_research::sat::DisjunctiveEdgeFinding
Definition: disjunctive.h:233
operations_research::sat::IntervalsRepository::MaxSize
IntegerValue MaxSize(IntervalVariable i) const
Definition: intervals.h:89
operations_research::sat::IntervalsRepository::IsOptional
bool IsOptional(IntervalVariable i) const
Definition: intervals.h:63
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::TaskTime::time
IntegerValue time
Definition: intervals.h:127
operations_research::sat::SchedulingConstraintHelper::ClearReason
void ClearReason()
Definition: intervals.h:402
operations_research::sat::IntegerTrail::IsCurrentlyIgnored
bool IsCurrentlyIgnored(IntegerVariable i) const
Definition: integer.h:612
operations_research::sat::DisjunctivePrecedences
Definition: disjunctive.h:263
operations_research::sat::GenericLiteralWatcher::Register
int Register(PropagatorInterface *propagator)
Definition: integer.cc:1798
operations_research::sat::IntegerTrail
Definition: integer.h:534
operations_research::sat::GenericLiteralWatcher::NotifyThatPropagatorMayNotReachFixedPointInOnePass
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
Definition: integer.cc:1828
operations_research::sat::ThetaLambdaTree::EnergyMin
IntegerType EnergyMin(int event) const
Definition: theta_tree.h:197
sat_solver.h
operations_research::sat::DisjunctiveWithTwoItems::Propagate
bool Propagate() final
Definition: disjunctive.cc:250
operations_research::sat::Model
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
operations_research::sat::ThetaLambdaTree::AddOrUpdateEvent
void AddOrUpdateEvent(int event, IntegerType initial_envelope, IntegerType energy_min, IntegerType energy_max)
Definition: theta_tree.cc:111
operations_research::sat::ThetaLambdaTree::Reset
void Reset(int num_events)
Definition: theta_tree.cc:40
operations_research::sat::CombinedDisjunctive::AddNoOverlap
void AddNoOverlap(const std::vector< IntervalVariable > &var)
Definition: disjunctive.cc:331
index
int index
Definition: pack.cc:508
operations_research::sat::TimeTablingPerTask::RegisterWith
void RegisterWith(GenericLiteralWatcher *watcher)
Definition: timetable.cc:61
timetable.h
operations_research::sat::SatSolver
Definition: sat_solver.h:58
operations_research::sat::SchedulingConstraintHelper::TaskByDecreasingStartMax
const std::vector< TaskTime > & TaskByDecreasingStartMax()
Definition: intervals.cc:180
operations_research::sat::SchedulingConstraintHelper::NumTasks
int NumTasks() const
Definition: intervals.h:157
operations_research::sat::Literal
Definition: sat_base.h:64
operations_research::sat::DisjunctiveOverloadChecker
Definition: disjunctive.h:136
operations_research::sat::ThetaLambdaTree::GetOptionalEnvelope
IntegerType GetOptionalEnvelope() const
Definition: theta_tree.cc:173
operations_research::sat::DisjunctiveWithBooleanPrecedencesOnly
std::function< void(Model *)> DisjunctiveWithBooleanPrecedencesOnly(const std::vector< IntervalVariable > &vars)
Definition: disjunctive.cc:130
operations_research::sat::DisjunctiveWithTwoItems
Definition: disjunctive.h:298
operations_research::sat::SchedulingConstraintHelper::StartMin
IntegerValue StartMin(int t) const
Definition: intervals.h:359
operations_research::sat::DisjunctiveOverloadChecker::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:632
operations_research::sat::ThetaLambdaTree::GetEnvelopeOf
IntegerType GetEnvelopeOf(int event) const
Definition: theta_tree.cc:202
operations_research::sat::DisjunctiveEdgeFinding::RegisterWith
int RegisterWith(GenericLiteralWatcher *watcher)
Definition: disjunctive.cc:1353
operations_research::sat::GenericLiteralWatcher
Definition: integer.h:1056
operations_research::sat::Literal::Negated
Literal Negated() const
Definition: sat_base.h:91
operations_research::sat::ThetaLambdaTree::GetEventsWithOptionalEnvelopeGreaterThan
void GetEventsWithOptionalEnvelopeGreaterThan(IntegerType target_envelope, int *critical_event, int *optional_event, IntegerType *available_energy) const
Definition: theta_tree.cc:189
operations_research::sat::SchedulingConstraintHelper::AddEndMinReason
void AddEndMinReason(int t, IntegerValue lower_bound)
Definition: intervals.h:453
sat_parameters.pb.h
operations_research::sat::TaskSet::Entry::task
int task
Definition: disjunctive.h:61
operations_research::sat::TaskSet::AddEntry
void AddEntry(const Entry &e)
Definition: disjunctive.cc:161
operations_research::sat::SchedulingConstraintHelper::StartMax
IntegerValue StartMax(int t) const
Definition: intervals.h:363
operations_research::sat::TaskSet::Entry
Definition: disjunctive.h:60
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:343
operations_research::sat::CombinedDisjunctive::Propagate
bool Propagate() final
Definition: disjunctive.cc:342
operations_research::sat::AffineExpression
Definition: integer.h:214
operations_research::sat::SchedulingConstraintHelper::MutableLiteralReason
std::vector< Literal > * MutableLiteralReason()
Definition: intervals.h:232
operations_research::sat::SchedulingConstraintHelper::EndVars
const std::vector< IntegerVariable > & EndVars() const
Definition: intervals.h:256
operations_research::IncrementalSort
void IncrementalSort(int max_comparisons, Iterator begin, Iterator end, Compare comp=Compare{}, bool is_stable=false)
Definition: sort.h:46
operations_research::sat::SchedulingConstraintHelper::TaskByIncreasingShiftedStartMin
const std::vector< TaskTime > & TaskByIncreasingShiftedStartMin()
Definition: intervals.cc:205
operations_research::sat::CombinedDisjunctive::CombinedDisjunctive
CombinedDisjunctive(Model *model)
Definition: disjunctive.cc:318
operations_research::sat::SchedulingConstraintHelper::IncreaseStartMin
ABSL_MUST_USE_RESULT bool IncreaseStartMin(int t, IntegerValue new_min_start)
Definition: intervals.cc:310
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::sat::IntervalsRepository::MinSize
IntegerValue MinSize(IntervalVariable i) const
Definition: intervals.h:82
operations_research::sat::SchedulingConstraintHelper::PushTaskAbsence
ABSL_MUST_USE_RESULT bool PushTaskAbsence(int t)
Definition: intervals.cc:322
start_max
Rev< int64 > start_max
Definition: sched_constraints.cc:242
operations_research::sat::SchedulingConstraintHelper::IsPresent
bool IsPresent(int t) const
Definition: intervals.h:392
operations_research::sat::ThetaLambdaTree::GetEnvelope
IntegerType GetEnvelope() const
Definition: theta_tree.cc:168
operations_research::sat::AllDifferentOnBounds
std::function< void(Model *)> AllDifferentOnBounds(const std::vector< IntegerVariable > &vars)
Definition: all_different.cc:65
operations_research::sat::SchedulingConstraintHelper::AddStartMaxReason
void AddStartMaxReason(int t, IntegerValue upper_bound)
Definition: intervals.h:445
operations_research::sat::DisjunctiveNotLast
Definition: disjunctive.h:213
operations_research::sat::PrecedencesPropagator::AddPrecedenceReason
void AddPrecedenceReason(int arc_index, IntegerValue min_offset, std::vector< Literal > *literal_reason, std::vector< IntegerLiteral > *integer_reason) const
Definition: precedences.cc:204
operations_research::sat::SchedulingConstraintHelper::PushIntegerLiteral
ABSL_MUST_USE_RESULT bool PushIntegerLiteral(IntegerLiteral bound)
Definition: intervals.cc:266
model
GRBmodel * model
Definition: gurobi_interface.cc:195
operations_research::sat::TaskTime::task_index
int task_index
Definition: intervals.h:126
operations_research::sat::SchedulingConstraintHelper::MutableIntegerReason
std::vector< IntegerLiteral > * MutableIntegerReason()
Definition: intervals.h:233
sort.h
operations_research::sat::IntegerTrail::LowerBound
IntegerValue LowerBound(IntegerVariable i) const
Definition: integer.h:1217
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
end_min
Rev< int64 > end_min
Definition: sched_constraints.cc:243
iterator_adaptors.h
operations_research::sat::DisjunctiveOverloadChecker::Propagate
bool Propagate() final
Definition: disjunctive.cc:460
operations_research::sat::DisjunctiveEdgeFinding::Propagate
bool Propagate() final
Definition: disjunctive.cc:1139
operations_research::sat::DisjunctiveDetectablePrecedences::Propagate
bool Propagate() final
Definition: disjunctive.cc:641
operations_research::sat::Disjunctive
std::function< void(Model *)> Disjunctive(const std::vector< IntervalVariable > &vars)
Definition: disjunctive.cc:30
operations_research::sat::SchedulingConstraintHelper::ShiftedStartMin
IntegerValue ShiftedStartMin(int t) const
Definition: intervals.h:376
operations_research::sat::SchedulingConstraintHelper::AddEnergyAfterReason
void AddEnergyAfterReason(int t, IntegerValue energy_min, IntegerValue time)
Definition: intervals.h:481
operations_research::sat::TimeTablingPerTask
Definition: timetable.h:29
operations_research::sat::TaskSet::NotifyEntryIsNowLastIfPresent
void NotifyEntryIsNowLastIfPresent(const Entry &e)
Definition: disjunctive.cc:182
operations_research::sat::PrecedencesPropagator::ComputePrecedences
void ComputePrecedences(const std::vector< IntegerVariable > &vars, std::vector< IntegerPrecedences > *output)
Definition: precedences.cc:127
operations_research::sat::ThetaLambdaTree::GetMaxEventWithEnvelopeGreaterThan
int GetMaxEventWithEnvelopeGreaterThan(IntegerType target_envelope) const
Definition: theta_tree.cc:179
operations_research::sat::SchedulingConstraintHelper::ReportConflict
ABSL_MUST_USE_RESULT bool ReportConflict()
Definition: intervals.cc:338
operations_research::sat::PrecedencesPropagator
Definition: precedences.h:51
operations_research::sat::IntervalsRepository
Definition: intervals.h:45
operations_research::sat::TaskSet::ComputeEndMin
IntegerValue ComputeEndMin() const
Definition: disjunctive.cc:202
operations_research::sat::SchedulingConstraintHelper::DurationMin
IntegerValue DurationMin(int t) const
Definition: intervals.h:347
operations_research::sat::ThetaLambdaTree::AddOrUpdateOptionalEvent
void AddOrUpdateOptionalEvent(int event, IntegerType initial_envelope_opt, IntegerType energy_max)
Definition: theta_tree.cc:124
operations_research::sat::TaskSet::AddShiftedStartMinEntry
void AddShiftedStartMinEntry(const SchedulingConstraintHelper &helper, int t)
Definition: disjunctive.cc:176
operations_research::sat::ThetaLambdaTree::RemoveEvent
void RemoveEvent(int event)
Definition: theta_tree.cc:147
operations_research::sat::SchedulingConstraintHelper::AddPresenceReason
void AddPresenceReason(int t)
Definition: intervals.h:411
operations_research::sat::DisjunctiveWithBooleanPrecedences
std::function< void(Model *)> DisjunctiveWithBooleanPrecedences(const std::vector< IntervalVariable > &vars)
Definition: disjunctive.cc:153
operations_research::sat::TaskSet::ComputeEndMin
IntegerValue ComputeEndMin(int task_to_ignore, int *critical_index) const
Definition: disjunctive.cc:218
integer.h
operations_research::sat::CombinedDisjunctive
Definition: disjunctive.h:195
operations_research::sat::TaskTime
Definition: intervals.h:125
time
int64 time
Definition: resource.cc:1683
operations_research::sat::SchedulingConstraintHelper::DecreaseEndMax
ABSL_MUST_USE_RESULT bool DecreaseEndMax(int t, IntegerValue new_max_end)
Definition: intervals.cc:316