Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cumulative.cc
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
15
16#include <algorithm>
17#include <functional>
18#include <vector>
19
20#include "absl/log/check.h"
21#include "absl/strings/str_join.h"
25#include "ortools/sat/integer.h"
29#include "ortools/sat/model.h"
33#include "ortools/sat/sat_parameters.pb.h"
38
39namespace operations_research {
40namespace sat {
41
42std::function<void(Model*)> Cumulative(
43 const std::vector<IntervalVariable>& vars,
44 const std::vector<AffineExpression>& demands, AffineExpression capacity,
46 return [=](Model* model) mutable {
47 if (vars.empty()) return;
48
49 auto* intervals = model->GetOrCreate<IntervalsRepository>();
50 auto* encoder = model->GetOrCreate<IntegerEncoder>();
51 auto* integer_trail = model->GetOrCreate<IntegerTrail>();
52 auto* watcher = model->GetOrCreate<GenericLiteralWatcher>();
53
54 // Redundant constraints to ensure that the resource capacity is high enough
55 // for each task. Also ensure that no task consumes more resource than what
56 // is available. This is useful because the subsequent propagators do not
57 // filter the capacity variable very well.
58 for (int i = 0; i < demands.size(); ++i) {
59 if (intervals->MaxSize(vars[i]) == 0) continue;
60
61 LinearConstraintBuilder builder(model, kMinIntegerValue, IntegerValue(0));
62 builder.AddTerm(demands[i], IntegerValue(1));
63 builder.AddTerm(capacity, IntegerValue(-1));
64 LinearConstraint ct = builder.Build();
65
66 std::vector<Literal> enforcement_literals;
67 if (intervals->IsOptional(vars[i])) {
68 enforcement_literals.push_back(intervals->PresenceLiteral(vars[i]));
69 }
70
71 // If the interval can be of size zero, it currently do not count towards
72 // the capacity. TODO(user): Change that since we have optional interval
73 // for this.
74 if (intervals->MinSize(vars[i]) == 0) {
75 enforcement_literals.push_back(encoder->GetOrCreateAssociatedLiteral(
76 intervals->Size(vars[i]).GreaterOrEqual(IntegerValue(1))));
77 }
78
79 if (enforcement_literals.empty()) {
81 } else {
82 LoadConditionalLinearConstraint(enforcement_literals, ct, model);
83 }
84 }
85
86 if (vars.size() == 1) return;
87
88 const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
89
90 // Detect a subset of intervals that needs to be in disjunction and add a
91 // Disjunctive() constraint over them.
92 if (parameters.use_disjunctive_constraint_in_cumulative()) {
93 // TODO(user): We need to exclude intervals that can be of size zero
94 // because the disjunctive do not "ignore" them like the cumulative
95 // does. That is, the interval [2,2) will be assumed to be in
96 // disjunction with [1, 3) for instance. We need to uniformize the
97 // handling of interval with size zero.
98 std::vector<IntervalVariable> in_disjunction;
99 IntegerValue min_of_demands = kMaxIntegerValue;
100 const IntegerValue capa_max = integer_trail->UpperBound(capacity);
101 for (int i = 0; i < vars.size(); ++i) {
102 const IntegerValue size_min = intervals->MinSize(vars[i]);
103 if (size_min == 0) continue;
104 const IntegerValue demand_min = integer_trail->LowerBound(demands[i]);
105 if (2 * demand_min > capa_max) {
106 in_disjunction.push_back(vars[i]);
107 min_of_demands = std::min(min_of_demands, demand_min);
108 }
109 }
110
111 // Liftable? We might be able to add one more interval!
112 if (!in_disjunction.empty()) {
113 IntervalVariable lift_var;
114 IntegerValue lift_size(0);
115 for (int i = 0; i < vars.size(); ++i) {
116 const IntegerValue size_min = intervals->MinSize(vars[i]);
117 if (size_min == 0) continue;
118 const IntegerValue demand_min = integer_trail->LowerBound(demands[i]);
119 if (2 * demand_min > capa_max) continue;
120 if (min_of_demands + demand_min > capa_max && size_min > lift_size) {
121 lift_var = vars[i];
122 lift_size = size_min;
123 }
124 }
125 if (lift_size > 0) {
126 in_disjunction.push_back(lift_var);
127 }
128 }
129
130 // Add a disjunctive constraint on the intervals in in_disjunction. Do not
131 // create the cumulative at all when all intervals must be in disjunction.
132 //
133 // TODO(user): Do proper experiments to see how beneficial this is, the
134 // disjunctive will propagate more but is also using slower algorithms.
135 // That said, this is more a question of optimizing the disjunctive
136 // propagation code.
137 //
138 // TODO(user): Another "known" idea is to detect pair of tasks that must
139 // be in disjunction and to create a Boolean to indicate which one is
140 // before the other. It shouldn't change the propagation, but may result
141 // in a faster one with smaller explanations, and the solver can also take
142 // decision on such Boolean.
143 //
144 // TODO(user): A better place for stuff like this could be in the
145 // presolver so that it is easier to disable and play with alternatives.
146 if (in_disjunction.size() > 1) AddDisjunctive(in_disjunction, model);
147 if (in_disjunction.size() == vars.size()) return;
148 }
149
150 if (helper == nullptr) {
151 helper = intervals->GetOrCreateHelper(vars);
152 }
153 SchedulingDemandHelper* demands_helper =
154 intervals->GetOrCreateDemandHelper(helper, demands);
155 intervals->RegisterCumulative({capacity, helper, demands_helper});
156
157 // For each variables that is after a subset of task ends (i.e. like a
158 // makespan objective), we detect it and add a special constraint to
159 // propagate it.
160 //
161 // TODO(user): Models that include the makespan as a special interval might
162 // be better, but then not everyone does that. In particular this code
163 // allows to have decent lower bound on the large cumulative minizinc
164 // instances.
165 //
166 // TODO(user): this require the precedence constraints to be already loaded,
167 // and there is no guarantee of that currently. Find a more robust way.
168 //
169 // TODO(user): There is a bit of code duplication with the disjunctive
170 // precedence propagator. Abstract more?
171 if (parameters.use_hard_precedences_in_cumulative()) {
172 // The CumulativeIsAfterSubsetConstraint() always reset the helper to the
173 // forward time direction, so it is important to also precompute the
174 // precedence relation using the same direction! This is needed in case
175 // the helper has already been used and set in the other direction.
176 if (!helper->SynchronizeAndSetTimeDirection(true)) {
177 model->GetOrCreate<SatSolver>()->NotifyThatModelIsUnsat();
178 return;
179 }
180
181 std::vector<IntegerVariable> index_to_end_vars;
182 std::vector<int> index_to_task;
183 index_to_end_vars.clear();
184 for (int t = 0; t < helper->NumTasks(); ++t) {
185 const AffineExpression& end_exp = helper->Ends()[t];
186
187 // TODO(user): Handle generic affine relation?
188 if (end_exp.var == kNoIntegerVariable || end_exp.coeff != 1) continue;
189 index_to_end_vars.push_back(end_exp.var);
190 index_to_task.push_back(t);
191 }
192
193 // TODO(user): This can lead to many constraints. By analyzing a bit more
194 // the precedences, we could restrict that. In particular for cases were
195 // the cumulative is always (bunch of tasks B), T, (bunch of tasks A) and
196 // task T always in the middle, we never need to explicit list the
197 // precedence of a task in B with a task in A.
198 //
199 // TODO(user): If more than one variable are after the same set of
200 // intervals, we should regroup them in a single constraint rather than
201 // having two independent constraint doing the same propagation.
202 std::vector<FullIntegerPrecedence> full_precedences;
203 if (parameters.exploit_all_precedences()) {
204 model->GetOrCreate<PrecedenceRelations>()->ComputeFullPrecedences(
205 index_to_end_vars, &full_precedences);
206 }
207 for (const FullIntegerPrecedence& data : full_precedences) {
208 const int size = data.indices.size();
209 if (size <= 1) continue;
210
211 const IntegerVariable var = data.var;
212 std::vector<int> subtasks;
213 std::vector<IntegerValue> offsets;
214 IntegerValue sum_of_demand_max(0);
215 for (int i = 0; i < size; ++i) {
216 const int t = index_to_task[data.indices[i]];
217 subtasks.push_back(t);
218 sum_of_demand_max += integer_trail->LevelZeroUpperBound(demands[t]);
219
220 // We have var >= end_exp.var + offset, so
221 // var >= (end_exp.var + end_exp.cte) + (offset - end_exp.cte)
222 // var >= task end + new_offset.
223 const AffineExpression& end_exp = helper->Ends()[t];
224 offsets.push_back(data.offsets[i] - end_exp.constant);
225 }
226 if (sum_of_demand_max > integer_trail->LevelZeroLowerBound(capacity)) {
227 VLOG(2) << "Cumulative precedence constraint! var= " << var
228 << " #task: " << absl::StrJoin(subtasks, ",");
230 new CumulativeIsAfterSubsetConstraint(var, capacity, subtasks,
231 offsets, helper,
232 demands_helper, model);
233 constraint->RegisterWith(watcher);
234 model->TakeOwnership(constraint);
235 }
236 }
237 }
238
239 // Propagator responsible for applying Timetabling filtering rule. It
240 // increases the minimum of the start variables, decrease the maximum of the
241 // end variables, and increase the minimum of the capacity variable.
242 TimeTablingPerTask* time_tabling =
243 new TimeTablingPerTask(capacity, helper, demands_helper, model);
244 time_tabling->RegisterWith(watcher);
245 model->TakeOwnership(time_tabling);
246
247 // Propagator responsible for applying the Overload Checking filtering rule.
248 // It increases the minimum of the capacity variable.
249 if (parameters.use_overload_checker_in_cumulative()) {
250 AddCumulativeOverloadChecker(capacity, helper, demands_helper, model);
251 }
252 if (parameters.use_conservative_scale_overload_checker()) {
253 // Since we use the potential DFF conflict on demands to apply the
254 // heuristic, only do so if any demand is greater than 1.
255 bool any_demand_greater_than_one = false;
256 for (int i = 0; i < vars.size(); ++i) {
257 const IntegerValue demand_min = integer_trail->LowerBound(demands[i]);
258 if (demand_min > 1) {
259 any_demand_greater_than_one = true;
260 break;
261 }
262 }
263 if (any_demand_greater_than_one) {
264 AddCumulativeOverloadCheckerDff(capacity, helper, demands_helper,
265 model);
266 }
267 }
268
269 // Propagator responsible for applying the Timetable Edge finding filtering
270 // rule. It increases the minimum of the start variables and decreases the
271 // maximum of the end variables,
272 if (parameters.use_timetable_edge_finding_in_cumulative() &&
273 helper->NumTasks() <=
274 parameters.max_num_intervals_for_timetable_edge_finding()) {
275 TimeTableEdgeFinding* time_table_edge_finding =
276 new TimeTableEdgeFinding(capacity, helper, demands_helper, model);
277 time_table_edge_finding->RegisterWith(watcher);
278 model->TakeOwnership(time_table_edge_finding);
279 }
280 };
281}
282
283std::function<void(Model*)> CumulativeTimeDecomposition(
284 const std::vector<IntervalVariable>& vars,
285 const std::vector<AffineExpression>& demands, AffineExpression capacity,
287 return [=](Model* model) {
288 if (vars.empty()) return;
289
290 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
291 CHECK(integer_trail->IsFixed(capacity));
292 const Coefficient fixed_capacity(
293 integer_trail->UpperBound(capacity).value());
294
295 const int num_tasks = vars.size();
296 SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
297 IntegerEncoder* encoder = model->GetOrCreate<IntegerEncoder>();
298 IntervalsRepository* repository = model->GetOrCreate<IntervalsRepository>();
299
300 std::vector<AffineExpression> start_exprs;
301 std::vector<AffineExpression> end_exprs;
302 std::vector<IntegerValue> fixed_demands;
303
304 for (int t = 0; t < num_tasks; ++t) {
305 start_exprs.push_back(repository->Start(vars[t]));
306 end_exprs.push_back(repository->End(vars[t]));
307 CHECK(integer_trail->IsFixed(demands[t]));
308 fixed_demands.push_back(integer_trail->LowerBound(demands[t]));
309 }
310
311 // Compute time range.
312 IntegerValue min_start = kMaxIntegerValue;
313 IntegerValue max_end = kMinIntegerValue;
314 for (int t = 0; t < num_tasks; ++t) {
315 min_start =
316 std::min(min_start, integer_trail->LowerBound(start_exprs[t]));
317 max_end = std::max(max_end, integer_trail->UpperBound(end_exprs[t]));
318 }
319
320 for (IntegerValue time = min_start; time < max_end; ++time) {
321 std::vector<LiteralWithCoeff> literals_with_coeff;
322 for (int t = 0; t < num_tasks; ++t) {
323 if (!sat_solver->Propagate()) return;
324 const IntegerValue start_min =
325 integer_trail->LowerBound(start_exprs[t]);
326 const IntegerValue end_max = integer_trail->UpperBound(end_exprs[t]);
327 if (end_max <= time || time < start_min || fixed_demands[t] == 0) {
328 continue;
329 }
330
331 // Task t consumes the resource at time if consume_condition is true.
332 std::vector<Literal> consume_condition;
333 const Literal consume = Literal(model->Add(NewBooleanVariable()), true);
334
335 // Task t consumes the resource at time if it is present.
336 if (repository->IsOptional(vars[t])) {
337 consume_condition.push_back(repository->PresenceLiteral(vars[t]));
338 }
339
340 // Task t overlaps time.
341 consume_condition.push_back(encoder->GetOrCreateAssociatedLiteral(
342 start_exprs[t].LowerOrEqual(IntegerValue(time))));
343 consume_condition.push_back(encoder->GetOrCreateAssociatedLiteral(
344 end_exprs[t].GreaterOrEqual(IntegerValue(time + 1))));
345
346 model->Add(ReifiedBoolAnd(consume_condition, consume));
347
348 // this is needed because we currently can't create a boolean variable
349 // if the model is unsat.
350 if (sat_solver->ModelIsUnsat()) return;
351
352 literals_with_coeff.push_back(
353 LiteralWithCoeff(consume, Coefficient(fixed_demands[t].value())));
354 }
355 // The profile cannot exceed the capacity at time.
356 sat_solver->AddLinearConstraint(false, Coefficient(0), true,
357 fixed_capacity, &literals_with_coeff);
358
359 // Abort if UNSAT.
360 if (sat_solver->ModelIsUnsat()) return;
361 }
362 };
363}
364
365std::function<void(Model*)> CumulativeUsingReservoir(
366 const std::vector<IntervalVariable>& vars,
367 const std::vector<AffineExpression>& demands, AffineExpression capacity,
369 return [=](Model* model) {
370 if (vars.empty()) return;
371
372 auto* integer_trail = model->GetOrCreate<IntegerTrail>();
373 auto* encoder = model->GetOrCreate<IntegerEncoder>();
374 auto* repository = model->GetOrCreate<IntervalsRepository>();
375
376 CHECK(integer_trail->IsFixed(capacity));
377 const IntegerValue fixed_capacity(
378 integer_trail->UpperBound(capacity).value());
379
380 std::vector<AffineExpression> times;
381 std::vector<AffineExpression> deltas;
382 std::vector<Literal> presences;
383
384 const int num_tasks = vars.size();
385 for (int t = 0; t < num_tasks; ++t) {
386 CHECK(integer_trail->IsFixed(demands[t]));
387 times.push_back(repository->Start(vars[t]));
388 deltas.push_back(demands[t]);
389 times.push_back(repository->End(vars[t]));
390 deltas.push_back(demands[t].Negated());
391 if (repository->IsOptional(vars[t])) {
392 presences.push_back(repository->PresenceLiteral(vars[t]));
393 presences.push_back(repository->PresenceLiteral(vars[t]));
394 } else {
395 presences.push_back(encoder->GetTrueLiteral());
396 presences.push_back(encoder->GetTrueLiteral());
397 }
398 }
399 AddReservoirConstraint(times, deltas, presences, 0, fixed_capacity.value(),
400 model);
401 };
402}
403
404} // namespace sat
405} // namespace operations_research
IntegerValue size
IntegerValue LowerBound(IntegerVariable i) const
Returns the current lower/upper bound of the given integer variable.
Definition integer.h:1717
IntegerValue UpperBound(IntegerVariable i) const
Definition integer.h:1721
bool IsFixed(IntegerVariable i) const
Checks if the variable is fixed.
Definition integer.h:1725
void AddTerm(IntegerVariable var, IntegerValue coeff)
bool AddLinearConstraint(bool use_lower_bound, Coefficient lower_bound, bool use_upper_bound, Coefficient upper_bound, std::vector< LiteralWithCoeff > *cst)
ABSL_MUST_USE_RESULT bool Propagate()
int NumTasks() const
Returns the number of task.
Definition intervals.h:293
absl::Span< const AffineExpression > Ends() const
Definition intervals.h:480
ABSL_MUST_USE_RESULT bool SynchronizeAndSetTimeDirection(bool is_forward)
Definition intervals.cc:483
void RegisterWith(GenericLiteralWatcher *watcher)
void RegisterWith(GenericLiteralWatcher *watcher)
Definition timetable.cc:343
SatParameters parameters
const Constraint * ct
int64_t value
IntVar * var
GRBmodel * model
std::function< void(Model *)> CumulativeUsingReservoir(const std::vector< IntervalVariable > &vars, const std::vector< AffineExpression > &demands, AffineExpression capacity, SchedulingConstraintHelper *helper)
Another testing code, same assumptions as the CumulativeTimeDecomposition().
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
std::function< void(Model *)> CumulativeTimeDecomposition(const std::vector< IntervalVariable > &vars, const std::vector< AffineExpression > &demands, AffineExpression capacity, SchedulingConstraintHelper *helper)
std::function< BooleanVariable(Model *)> NewBooleanVariable()
Definition integer.h:1893
void LoadConditionalLinearConstraint(const absl::Span< const Literal > enforcement_literals, const LinearConstraint &cst, Model *model)
LinearConstraint version.
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue.value())
const IntegerVariable kNoIntegerVariable(-1)
std::function< void(Model *)> Cumulative(const std::vector< IntervalVariable > &vars, const std::vector< AffineExpression > &demands, AffineExpression capacity, SchedulingConstraintHelper *helper)
Definition cumulative.cc:42
void AddCumulativeOverloadCheckerDff(AffineExpression capacity, SchedulingConstraintHelper *helper, SchedulingDemandHelper *demands, Model *model)
void AddDisjunctive(const std::vector< IntervalVariable > &intervals, Model *model)
std::function< void(Model *)> ReifiedBoolAnd(const std::vector< Literal > &literals, Literal r)
Definition sat_solver.h:991
void AddReservoirConstraint(std::vector< AffineExpression > times, std::vector< AffineExpression > deltas, std::vector< Literal > presences, int64_t min_level, int64_t max_level, Model *model)
Definition timetable.cc:31
void LoadLinearConstraint(const ConstraintProto &ct, Model *m)
void AddCumulativeOverloadChecker(AffineExpression capacity, SchedulingConstraintHelper *helper, SchedulingDemandHelper *demands, Model *model)
In SWIG mode, we don't want anything besides these top-level includes.
int64_t time
Definition resource.cc:1708
Rev< int64_t > end_max
Rev< int64_t > start_min
Represents a term in a pseudo-Boolean formula.