Google OR-Tools v9.12
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-2025 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 <cstdint>
19#include <memory>
20#include <string>
21#include <utility>
22#include <vector>
23
24#include "absl/strings/str_cat.h"
25#include "absl/types/span.h"
27#include "ortools/sat/integer.h"
30#include "ortools/sat/model.h"
34#include "ortools/sat/util.h"
36
37namespace operations_research {
38namespace sat {
39
40// Enforces a disjunctive (or no overlap) constraint on the given interval
41// variables. The intervals are interpreted as [start, end) and the constraint
42// enforces that no time point belongs to two intervals.
43//
44// TODO(user): This is not completely true for empty intervals (start == end).
45// Make sure such intervals are ignored by the constraint.
46void AddDisjunctive(const std::vector<IntervalVariable>& intervals,
47 Model* model);
48
49// Creates Boolean variables for all the possible precedences of the form (task
50// i is before task j) and forces that, for each couple of task (i,j), either i
51// is before j or j is before i. Do not create any other propagators.
53 absl::Span<const IntervalVariable> intervals, Model* model);
54
55// Helper class to compute the end-min of a set of tasks given their start-min
56// and size-min. In Petr Vilim's PhD "Global Constraints in Scheduling",
57// this corresponds to his Theta-tree except that we use a O(n) implementation
58// for most of the function here, not a O(log(n)) one.
59class TaskSet {
60 public:
61 explicit TaskSet(int num_tasks) { sorted_tasks_.ClearAndReserve(num_tasks); }
62
63 struct Entry {
64 int task;
65 IntegerValue start_min;
66 IntegerValue size_min;
67
68 // Note that the tie-breaking is not important here.
69 bool operator<(Entry other) const { return start_min < other.start_min; }
70 };
71
72 // Insertion and modification. These leave sorted_tasks_ sorted.
73 void Clear() {
74 sorted_tasks_.clear();
75 optimized_restart_ = 0;
76 }
77 void AddEntry(const Entry& e);
78
79 // Same as AddEntry({t, helper->ShiftedStartMin(t), helper->SizeMin(t)}).
80 // This is a minor optimization to not call SizeMin(t) twice.
81 void AddShiftedStartMinEntry(const SchedulingConstraintHelper& helper, int t);
82
83 // Advanced usage, if the entry is present, this assumes that its start_min is
84 // >= the end min without it, and update the datastructure accordingly.
85 void NotifyEntryIsNowLastIfPresent(const Entry& e);
86
87 // Advanced usage. Instead of calling many AddEntry(), it is more efficient to
88 // call AddUnsortedEntry() instead, but then Sort() MUST be called just after
89 // the insertions. Nothing is checked here, so it is up to the client to do
90 // that properly.
91 void AddUnsortedEntry(const Entry& e) { sorted_tasks_.push_back(e); }
92 void Sort() { std::sort(sorted_tasks_.begin(), sorted_tasks_.end()); }
93
94 // Returns the end-min for the task in the set. The time profile of the tasks
95 // packed to the left will always be a set of contiguous tasks separated by
96 // empty space:
97 //
98 // [Bunch of tasks] ... [Bunch of tasks] ... [critical tasks].
99 //
100 // We call "critical tasks" the last group. These tasks will be solely
101 // responsible for the end-min of the whole set. The returned
102 // critical_index will be the index of the first critical task in
103 // SortedTasks().
104 //
105 // A reason for the min end is:
106 // - The size-min of all the critical tasks.
107 // - The fact that all critical tasks have a start-min greater or equal to the
108 // first of them, that is SortedTasks()[critical_index].start_min.
109 //
110 // It is possible to behave like if one task was not in the set by setting
111 // task_to_ignore to the id of this task. This returns 0 if the set is empty
112 // in which case critical_index will be left unchanged.
113 IntegerValue ComputeEndMin(int task_to_ignore, int* critical_index) const;
114 IntegerValue ComputeEndMin() const;
115
116 // Warning, this is only valid if ComputeEndMin() was just called. It is the
117 // same index as if one called ComputeEndMin(-1, &critical_index), but saves
118 // another unneeded loop.
119 int GetCriticalIndex() const { return optimized_restart_; }
120
121 absl::Span<const Entry> SortedTasks() const { return sorted_tasks_; }
122
123 private:
124 FixedCapacityVector<Entry> sorted_tasks_;
125 mutable int optimized_restart_ = 0;
126};
127
128// Simple class to display statistics at the end if --v=1.
130 explicit PropagationStatistics(std::string _name, Model* model = nullptr)
131 : name(_name),
132 shared_stats(model == nullptr
133 ? nullptr
134 : model->GetOrCreate<SharedStatistics>()) {};
135
137 if (shared_stats == nullptr) return;
138 if (!VLOG_IS_ON(1)) return;
139 std::vector<std::pair<std::string, int64_t>> stats;
140 stats.push_back({absl::StrCat(name, "/num_calls"), num_calls});
141 stats.push_back({absl::StrCat(name, "/num_calls_with_propagation"),
143 stats.push_back(
144 {absl::StrCat(name, "/num_calls_with_conflicts"), num_conflicts});
145 stats.push_back(
146 {absl::StrCat(name, "/num_propagations"), num_propagations});
147 shared_stats->AddStats(stats);
148 }
149
154
160
161 const std::string name;
164
165 int64_t num_calls = 0;
166 int64_t num_calls_with_propagation = 0; // Only count if we did something.
167 int64_t num_conflicts = 0;
168 int64_t num_propagations = 0;
169};
170
171// ============================================================================
172// Below are many of the known propagation techniques for the disjunctive, each
173// implemented in only one time direction and in its own propagator class. The
174// Disjunctive() model function above will instantiate the used ones (according
175// to the solver parameters) in both time directions.
176//
177// See Petr Vilim PhD "Global Constraints in Scheduling" for a description of
178// some of the algorithm.
179// ============================================================================
180
182 public:
184 Model* model = nullptr)
185 : helper_(helper),
186 window_(new TaskTime[helper->NumTasks()]),
187 task_to_event_(new int[helper->NumTasks()]),
188 stats_("DisjunctiveOverloadChecker", model) {
189 task_by_increasing_end_max_.ClearAndReserve(helper->NumTasks());
190 }
191
192 bool Propagate() final;
194
195 private:
196 bool PropagateSubwindow(int relevant_size, IntegerValue global_window_end);
197
199
200 // Size assigned at construction, stay fixed afterwards.
201 std::unique_ptr<TaskTime[]> window_;
202 std::unique_ptr<int[]> task_to_event_;
203
204 FixedCapacityVector<TaskTime> task_by_increasing_end_max_;
205
206 ThetaLambdaTree<IntegerValue> theta_tree_;
208};
209
210// This one is a simpler version of DisjunctiveDetectablePrecedences, it
211// detect all implied precedences between TWO tasks and push bounds accordingly.
212// If we created all pairwise precedence Booleans, this would already be
213// propagated and in this case we don't create this propagator.
214//
215// Otherwise, this generate short reason and is good to do early as it
216// propagates a lot.
218 public:
220 Model* model = nullptr)
221 : helper_(helper), stats_("DisjunctiveSimplePrecedences", model) {}
222 bool Propagate() final;
224
225 private:
226 bool PropagateOneDirection();
227 bool Push(TaskTime before, int t);
228
231};
232
234 public:
237 Model* model = nullptr)
238 : time_direction_(time_direction),
239 helper_(helper),
240 task_set_(helper->NumTasks()),
241 stats_("DisjunctiveDetectablePrecedences", model) {
242 ranks_.resize(helper->NumTasks());
243 to_add_.ClearAndReserve(helper->NumTasks());
244 }
245 bool Propagate() final;
247
248 private:
249 bool PropagateWithRanks();
250 bool Push(IntegerValue task_set_end_min, int t);
251
252 FixedCapacityVector<int> to_add_;
253 std::vector<int> ranks_;
254
255 const bool time_direction_;
257 TaskSet task_set_;
259};
260
261// This propagates the same things as DisjunctiveDetectablePrecedences, except
262// that it only sort the full set of intervals once and then work on a combined
263// set of disjunctives.
264template <bool time_direction>
266 public:
267 explicit CombinedDisjunctive(Model* model);
268
269 // After creation, this must be called for all the disjunctive constraints
270 // in the model.
271 void AddNoOverlap(absl::Span<const IntervalVariable> var);
272
273 bool Propagate() final;
274
275 private:
277 std::vector<std::vector<int>> task_to_disjunctives_;
278 std::vector<bool> task_is_added_;
279 std::vector<TaskSet> task_sets_;
280 std::vector<IntegerValue> end_mins_;
281};
282
284 public:
285 DisjunctiveNotLast(bool time_direction, SchedulingConstraintHelper* helper,
286 Model* model = nullptr)
287 : time_direction_(time_direction),
288 helper_(helper),
289 task_set_(helper->NumTasks()),
290 stats_("DisjunctiveNotLast", model) {
291 start_min_window_.ClearAndReserve(helper->NumTasks());
292 start_max_window_.ClearAndReserve(helper->NumTasks());
293 }
294 bool Propagate() final;
296
297 private:
298 bool PropagateSubwindow();
299
300 FixedCapacityVector<TaskTime> start_min_window_;
301 FixedCapacityVector<TaskTime> start_max_window_;
302
303 const bool time_direction_;
305 TaskSet task_set_;
307};
308
310 public:
311 DisjunctiveEdgeFinding(bool time_direction,
313 Model* model = nullptr)
314 : time_direction_(time_direction),
315 helper_(helper),
316 stats_("DisjunctiveEdgeFinding", model) {
317 task_by_increasing_end_max_.ClearAndReserve(helper->NumTasks());
318 window_.ClearAndReserve(helper->NumTasks());
319 event_size_.ClearAndReserve(helper->NumTasks());
320 }
321 bool Propagate() final;
323
324 private:
325 bool PropagateSubwindow(IntegerValue window_end_min);
326
327 const bool time_direction_;
329
330 // This only contains non-gray tasks.
331 FixedCapacityVector<TaskTime> task_by_increasing_end_max_;
332
333 // All these member are indexed in the same way.
335 ThetaLambdaTree<IntegerValue> theta_tree_;
336 FixedCapacityVector<IntegerValue> event_size_;
337
338 // Task indexed.
339 std::vector<int> non_gray_task_to_event_;
340 std::vector<bool> is_gray_;
341
343};
344
345// Exploits the precedences relations of the form "this set of disjoint
346// IntervalVariables must be performed before a given IntegerVariable". The
347// relations are computed with PrecedencesPropagator::ComputePrecedences().
349 public:
350 DisjunctivePrecedences(bool time_direction,
351 SchedulingConstraintHelper* helper, Model* model)
352 : time_direction_(time_direction),
353 helper_(helper),
354 integer_trail_(model->GetOrCreate<IntegerTrail>()),
355 precedence_relations_(model->GetOrCreate<PrecedenceRelations>()),
356 stats_("DisjunctivePrecedences", model) {
357 window_.ClearAndReserve(helper->NumTasks());
358 index_to_end_vars_.ClearAndReserve(helper->NumTasks());
359 indices_before_.ClearAndReserve(helper->NumTasks());
360 }
361
362 bool Propagate() final;
364
365 private:
366 bool PropagateSubwindow();
367
368 const bool time_direction_;
370 IntegerTrail* integer_trail_;
371 PrecedenceRelations* precedence_relations_;
372
374 FixedCapacityVector<IntegerVariable> index_to_end_vars_;
375
376 FixedCapacityVector<int> indices_before_;
377 std::vector<bool> skip_;
378 std::vector<PrecedenceRelations::PrecedenceData> before_;
379
381};
382
383// This is an optimization for the case when we have a big number of such
384// pairwise constraints. This should be roughtly equivalent to what the general
385// disjunctive case is doing, but it dealt with variable size better and has a
386// lot less overhead.
388 public:
390 : helper_(helper) {}
391 bool Propagate() final;
393
394 private:
396};
397
398} // namespace sat
399} // namespace operations_research
400
401#endif // OR_TOOLS_SAT_DISJUNCTIVE_H_
void AddNoOverlap(absl::Span< const IntervalVariable > var)
DisjunctiveDetectablePrecedences(bool time_direction, SchedulingConstraintHelper *helper, Model *model=nullptr)
DisjunctiveEdgeFinding(bool time_direction, SchedulingConstraintHelper *helper, Model *model=nullptr)
DisjunctiveNotLast(bool time_direction, SchedulingConstraintHelper *helper, Model *model=nullptr)
int RegisterWith(GenericLiteralWatcher *watcher)
DisjunctiveOverloadChecker(SchedulingConstraintHelper *helper, Model *model=nullptr)
DisjunctivePrecedences(bool time_direction, SchedulingConstraintHelper *helper, Model *model)
DisjunctiveSimplePrecedences(SchedulingConstraintHelper *helper, Model *model=nullptr)
DisjunctiveWithTwoItems(SchedulingConstraintHelper *helper)
int RegisterWith(GenericLiteralWatcher *watcher)
Base class for CP like propagators.
Definition integer.h:1048
int NumTasks() const
Returns the number of task.
Simple class to add statistics by name and print them at the end.
void NotifyEntryIsNowLastIfPresent(const Entry &e)
void AddUnsortedEntry(const Entry &e)
Definition disjunctive.h:91
IntegerValue ComputeEndMin() const
absl::Span< const Entry > SortedTasks() const
void AddShiftedStartMinEntry(const SchedulingConstraintHelper &helper, int t)
void Clear()
Insertion and modification. These leave sorted_tasks_ sorted.
Definition disjunctive.h:73
void AddDisjunctive(const std::vector< IntervalVariable > &intervals, Model *model)
void AddDisjunctiveWithBooleanPrecedencesOnly(absl::Span< const IntervalVariable > intervals, Model *model)
In SWIG mode, we don't want anything besides these top-level includes.
STL namespace.
Simple class to display statistics at the end if –v=1.
PropagationStatistics(std::string _name, Model *model=nullptr)