Google OR-Tools v9.9
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
disjunctive.h
Go to the documentation of this file.
1// Copyright 2010-2024 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#ifndef OR_TOOLS_SAT_DISJUNCTIVE_H_
15#define OR_TOOLS_SAT_DISJUNCTIVE_H_
16
17#include <algorithm>
18#include <functional>
19#include <memory>
20#include <vector>
21
22#include "absl/types/span.h"
23#include "ortools/base/macros.h"
24#include "ortools/sat/integer.h"
26#include "ortools/sat/model.h"
31
32namespace operations_research {
33namespace sat {
34
35// Enforces a disjunctive (or no overlap) constraint on the given interval
36// variables. The intervals are interpreted as [start, end) and the constraint
37// enforces that no time point belongs to two intervals.
38//
39// TODO(user): This is not completely true for empty intervals (start == end).
40// Make sure such intervals are ignored by the constraint.
41void AddDisjunctive(const std::vector<IntervalVariable>& intervals,
42 Model* model);
43
44// Creates Boolean variables for all the possible precedences of the form (task
45// i is before task j) and forces that, for each couple of task (i,j), either i
46// is before j or j is before i. Do not create any other propagators.
48 const std::vector<IntervalVariable>& intervals, Model* model);
49
50// Helper class to compute the end-min of a set of tasks given their start-min
51// and size-min. In Petr Vilim's PhD "Global Constraints in Scheduling",
52// this corresponds to his Theta-tree except that we use a O(n) implementation
53// for most of the function here, not a O(log(n)) one.
54class TaskSet {
55 public:
56 explicit TaskSet(int num_tasks) { sorted_tasks_.reserve(num_tasks); }
57
58 struct Entry {
59 int task;
60 IntegerValue start_min;
61 IntegerValue size_min;
62
63 // Note that the tie-breaking is not important here.
64 bool operator<(Entry other) const { return start_min < other.start_min; }
65 };
66
67 // Insertion and modification. These leave sorted_tasks_ sorted.
68 void Clear() {
69 sorted_tasks_.clear();
70 optimized_restart_ = 0;
71 }
72 void AddEntry(const Entry& e);
73
74 // Same as AddEntry({t, helper->ShiftedStartMin(t), helper->SizeMin(t)}).
75 // This is a minor optimization to not call SizeMin(t) twice.
76 void AddShiftedStartMinEntry(const SchedulingConstraintHelper& helper, int t);
77
78 // Advanced usage, if the entry is present, this assumes that its start_min is
79 // >= the end min without it, and update the datastructure accordingly.
80 void NotifyEntryIsNowLastIfPresent(const Entry& e);
81
82 // Advanced usage. Instead of calling many AddEntry(), it is more efficient to
83 // call AddUnsortedEntry() instead, but then Sort() MUST be called just after
84 // the insertions. Nothing is checked here, so it is up to the client to do
85 // that properly.
86 void AddUnsortedEntry(const Entry& e) { sorted_tasks_.push_back(e); }
87 void Sort() { std::sort(sorted_tasks_.begin(), sorted_tasks_.end()); }
88
89 // Returns the end-min for the task in the set. The time profile of the tasks
90 // packed to the left will always be a set of contiguous tasks separated by
91 // empty space:
92 //
93 // [Bunch of tasks] ... [Bunch of tasks] ... [critical tasks].
94 //
95 // We call "critical tasks" the last group. These tasks will be solely
96 // responsible for the end-min of the whole set. The returned
97 // critical_index will be the index of the first critical task in
98 // SortedTasks().
99 //
100 // A reason for the min end is:
101 // - The size-min of all the critical tasks.
102 // - The fact that all critical tasks have a start-min greater or equal to the
103 // first of them, that is SortedTasks()[critical_index].start_min.
104 //
105 // It is possible to behave like if one task was not in the set by setting
106 // task_to_ignore to the id of this task. This returns 0 if the set is empty
107 // in which case critical_index will be left unchanged.
108 IntegerValue ComputeEndMin(int task_to_ignore, int* critical_index) const;
109 IntegerValue ComputeEndMin() const;
110
111 // Warning, this is only valid if ComputeEndMin() was just called. It is the
112 // same index as if one called ComputeEndMin(-1, &critical_index), but saves
113 // another unneeded loop.
114 int GetCriticalIndex() const { return optimized_restart_; }
115
116 const std::vector<Entry>& SortedTasks() const { return sorted_tasks_; }
117
118 private:
119 std::vector<Entry> sorted_tasks_;
120 mutable int optimized_restart_ = 0;
121};
122
123// ============================================================================
124// Below are many of the known propagation techniques for the disjunctive, each
125// implemented in only one time direction and in its own propagator class. The
126// Disjunctive() model function above will instantiate the used ones (according
127// to the solver parameters) in both time directions.
128//
129// See Petr Vilim PhD "Global Constraints in Scheduling" for a description of
130// some of the algorithm.
131// ============================================================================
132
133class DisjunctiveOverloadChecker : public PropagatorInterface {
134 public:
136 : helper_(helper),
137 window_(new TaskTime[helper->NumTasks()]),
138 task_to_event_(new int[helper->NumTasks()]) {}
139
140 bool Propagate() final;
142
143 private:
144 bool PropagateSubwindow(int relevat_size, IntegerValue global_window_end);
145
147
148 // Size assigned at construction, stay fixed afterwards.
149 std::unique_ptr<TaskTime[]> window_;
150 std::unique_ptr<int[]> task_to_event_;
151
152 std::vector<TaskTime> task_by_increasing_end_max_;
153
154 ThetaLambdaTree<IntegerValue> theta_tree_;
155};
156
158 public:
161 : time_direction_(time_direction),
162 helper_(helper),
163 task_set_(helper->NumTasks()) {}
164 bool Propagate() final;
166
167 private:
168 bool PropagateSubwindow();
169
170 std::vector<TaskTime> task_by_increasing_end_min_;
171 std::vector<TaskTime> task_by_increasing_start_max_;
172
173 std::vector<bool> processed_;
174 std::vector<int> to_propagate_;
175
176 const bool time_direction_;
178 TaskSet task_set_;
179};
180
181// Singleton model class which is just a SchedulingConstraintHelper will all
182// the intervals.
184 public:
187 model->GetOrCreate<IntervalsRepository>()->AllIntervals(), model) {}
188};
189
190// This propagates the same things as DisjunctiveDetectablePrecedences, except
191// that it only sort the full set of intervals once and then work on a combined
192// set of disjunctives.
193template <bool time_direction>
194class CombinedDisjunctive : public PropagatorInterface {
195 public:
197
198 // After creation, this must be called for all the disjunctive constraints
199 // in the model.
200 void AddNoOverlap(absl::Span<const IntervalVariable> var);
201
202 bool Propagate() final;
203
204 private:
205 AllIntervalsHelper* helper_;
206 std::vector<std::vector<int>> task_to_disjunctives_;
207 std::vector<bool> task_is_added_;
208 std::vector<TaskSet> task_sets_;
209 std::vector<IntegerValue> end_mins_;
210};
211
213 public:
214 DisjunctiveNotLast(bool time_direction, SchedulingConstraintHelper* helper)
215 : time_direction_(time_direction),
216 helper_(helper),
217 task_set_(helper->NumTasks()) {}
218 bool Propagate() final;
219 int RegisterWith(GenericLiteralWatcher* watcher);
220
221 private:
222 bool PropagateSubwindow();
223
224 std::vector<TaskTime> start_min_window_;
225 std::vector<TaskTime> start_max_window_;
226
227 const bool time_direction_;
229 TaskSet task_set_;
230};
231
233 public:
234 DisjunctiveEdgeFinding(bool time_direction,
236 : time_direction_(time_direction), helper_(helper) {}
237 bool Propagate() final;
238 int RegisterWith(GenericLiteralWatcher* watcher);
239
240 private:
241 bool PropagateSubwindow(IntegerValue window_end_min);
242
243 const bool time_direction_;
245
246 // This only contains non-gray tasks.
247 std::vector<TaskTime> task_by_increasing_end_max_;
248
249 // All these member are indexed in the same way.
250 std::vector<TaskTime> window_;
251 ThetaLambdaTree<IntegerValue> theta_tree_;
252 std::vector<IntegerValue> event_size_;
253
254 // Task indexed.
255 std::vector<int> non_gray_task_to_event_;
256 std::vector<bool> is_gray_;
257};
258
259// Exploits the precedences relations of the form "this set of disjoint
260// IntervalVariables must be performed before a given IntegerVariable". The
261// relations are computed with PrecedencesPropagator::ComputePrecedences().
263 public:
264 DisjunctivePrecedences(bool time_direction,
266 IntegerTrail* integer_trail,
267 PrecedencesPropagator* precedences)
268 : time_direction_(time_direction),
269 helper_(helper),
270 integer_trail_(integer_trail),
271 precedences_(precedences),
272 task_set_(helper->NumTasks()),
273 task_to_arc_index_(helper->NumTasks()) {}
274 bool Propagate() final;
275 int RegisterWith(GenericLiteralWatcher* watcher);
276
277 private:
278 bool PropagateSubwindow();
279
280 const bool time_direction_;
282 IntegerTrail* integer_trail_;
283 PrecedencesPropagator* precedences_;
284
285 std::vector<TaskTime> window_;
286 std::vector<IntegerVariable> index_to_end_vars_;
287
288 TaskSet task_set_;
289 std::vector<int> task_to_arc_index_;
290 std::vector<PrecedencesPropagator::IntegerPrecedences> before_;
291};
292
293// This is an optimization for the case when we have a big number of such
294// pairwise constraints. This should be roughtly equivalent to what the general
295// disjunctive case is doing, but it dealt with variable size better and has a
296// lot less overhead.
298 public:
300 : helper_(helper) {}
301 bool Propagate() final;
302 int RegisterWith(GenericLiteralWatcher* watcher);
303
304 private:
306};
307
308} // namespace sat
309} // namespace operations_research
310
311#endif // OR_TOOLS_SAT_DISJUNCTIVE_H_
DisjunctiveOverloadChecker(SchedulingConstraintHelper *helper)
int RegisterWith(GenericLiteralWatcher *watcher)
Base class for CP like propagators.
Definition integer.h:1318
void NotifyEntryIsNowLastIfPresent(const Entry &e)
void AddUnsortedEntry(const Entry &e)
Definition disjunctive.h:86
IntegerValue ComputeEndMin() const
const std::vector< Entry > & SortedTasks() const
void AddShiftedStartMinEntry(const SchedulingConstraintHelper &helper, int t)
void Clear()
Insertion and modification. These leave sorted_tasks_ sorted.
Definition disjunctive.h:68
IntVar * var
GRBmodel * model
void AddDisjunctiveWithBooleanPrecedencesOnly(const std::vector< IntervalVariable > &intervals, Model *model)
void AddDisjunctive(const std::vector< IntervalVariable > &intervals, Model *model)
In SWIG mode, we don't want anything besides these top-level includes.
STL namespace.