24#include "absl/container/flat_hash_set.h"
25#include "absl/log/check.h"
38class DifferentFromValues :
public Constraint {
40 DifferentFromValues(Solver* solver, IntVar*
var, std::vector<int64_t> values)
41 : Constraint(solver), var_(
var), values_(
std::move(values)) {}
42 void Post()
override {}
43 void InitialPropagate()
override { var_->RemoveValues(values_); }
44 std::string DebugString()
const override {
return "DifferentFromValues"; }
45 void Accept(ModelVisitor*
const visitor)
const override {
46 visitor->BeginVisitConstraint(RoutingModelVisitor::kRemoveValues,
this);
50 visitor->EndVisitConstraint(RoutingModelVisitor::kRemoveValues,
this);
55 const std::vector<int64_t> values_;
60 std::vector<int64_t> values) {
62 new DifferentFromValues(solver,
var, std::move(values)));
73void ComputeVehicleChainStartEndInfo(
74 const RoutingModel&
model, std::vector<int64_t>* end_chain_starts,
75 std::vector<int>* vehicle_index_of_start_chain_end) {
76 vehicle_index_of_start_chain_end->resize(
model.Size() +
model.vehicles(), -1);
78 for (
int vehicle = 0; vehicle <
model.vehicles(); ++vehicle) {
79 int64_t node =
model.Start(vehicle);
80 while (!
model.IsEnd(node) &&
model.NextVar(node)->Bound()) {
81 node =
model.NextVar(node)->Value();
83 vehicle_index_of_start_chain_end->at(node) = vehicle;
89class ResourceAssignmentConstraint :
public Constraint {
91 ResourceAssignmentConstraint(
92 const RoutingModel::ResourceGroup* resource_group,
93 const std::vector<IntVar*>* vehicle_resource_vars, RoutingModel*
model)
94 : Constraint(
model->solver()),
96 resource_group_(*resource_group),
97 vehicle_resource_vars_(*vehicle_resource_vars) {
98 DCHECK_EQ(vehicle_resource_vars_.size(), model_.vehicles());
100 const std::vector<RoutingDimension*>&
dimensions = model_.GetDimensions();
101 for (
int v = 0; v < model_.vehicles(); v++) {
102 IntVar*
const resource_var = vehicle_resource_vars_[v];
103 model->AddToAssignment(resource_var);
105 model->AddVariableTargetToFinalizer(resource_var, -1);
107 if (!resource_group_.VehicleRequiresAResource(v)) {
110 for (
const RoutingModel::DimensionIndex d :
111 resource_group_.GetAffectedDimensionIndices()) {
112 const RoutingDimension*
const dim =
dimensions[d.value()];
114 model->AddVariableMinimizedByFinalizer(dim->CumulVar(model_.End(v)));
115 model->AddVariableMaximizedByFinalizer(dim->CumulVar(model_.Start(v)));
120 void Post()
override {}
122 void InitialPropagate()
override {
123 if (!AllResourceAssignmentsFeasible()) {
126 SetupResourceConstraints();
130 bool AllResourceAssignmentsFeasible() {
131 DCHECK(!model_.GetResourceGroups().empty());
133 std::vector<int64_t> end_chain_starts;
134 std::vector<int> vehicle_index_of_start_chain_end;
135 ComputeVehicleChainStartEndInfo(model_, &end_chain_starts,
136 &vehicle_index_of_start_chain_end);
137 const auto next = [&
model = model_, &end_chain_starts,
138 &vehicle_index_of_start_chain_end](int64_t node) {
139 if (
model.NextVar(node)->Bound())
return model.NextVar(node)->Value();
140 const int vehicle = vehicle_index_of_start_chain_end[node];
147 return end_chain_starts[vehicle];
150 const std::vector<RoutingDimension*>&
dimensions = model_.GetDimensions();
151 for (RoutingModel::DimensionIndex d :
152 resource_group_.GetAffectedDimensionIndices()) {
153 if (!ResourceAssignmentFeasibleForDimension(*
dimensions[d.value()],
161 bool ResourceAssignmentFeasibleForDimension(
162 const RoutingDimension& dimension,
163 const std::function<int64_t(int64_t)>&
next) {
164 LocalDimensionCumulOptimizer*
const optimizer =
165 model_.GetMutableLocalCumulLPOptimizer(dimension);
167 if (optimizer ==
nullptr)
return true;
169 LocalDimensionCumulOptimizer*
const mp_optimizer =
170 model_.GetMutableLocalCumulMPOptimizer(dimension);
171 DCHECK_NE(mp_optimizer,
nullptr);
172 const auto transit = [&dimension](int64_t node, int64_t ) {
178 return std::max<int64_t>(dimension.FixedTransitVar(node)->Min(), 0);
181 using RCIndex = RoutingModel::ResourceClassIndex;
183 ignored_resources_per_class(resource_group_.GetResourceClassesCount());
185 for (
int v : resource_group_.GetVehiclesRequiringAResource()) {
187 v, resource_group_, ignored_resources_per_class,
next, transit,
189 model_.GetMutableLocalCumulLPOptimizer(dimension),
190 model_.GetMutableLocalCumulMPOptimizer(dimension),
198 resource_group_.GetVehiclesRequiringAResource(),
199 resource_group_.GetResourceIndicesPerClass(),
200 ignored_resources_per_class,
205 void SetupResourceConstraints() {
206 Solver*
const s = solver();
209 s->AddConstraint(s->MakeAllDifferentExcept(vehicle_resource_vars_, -1));
210 for (
int v = 0; v < model_.vehicles(); v++) {
211 IntVar*
const resource_var = vehicle_resource_vars_[v];
212 if (!resource_group_.VehicleRequiresAResource(v)) {
213 resource_var->SetValue(-1);
218 s->MakeEquality(model_.VehicleRouteConsideredVar(v),
219 s->MakeIsDifferentCstVar(resource_var, -1)));
222 const absl::flat_hash_set<int>& resources_marked_allowed =
223 resource_group_.GetResourcesMarkedAllowedForVehicle(v);
224 if (!resources_marked_allowed.empty()) {
225 std::vector<int> allowed_resources(resources_marked_allowed.begin(),
226 resources_marked_allowed.end());
227 allowed_resources.push_back(-1);
228 s->AddConstraint(s->MakeMemberCt(resource_var, allowed_resources));
231 if (resource_var->Bound()) {
235 s,
this, &ResourceAssignmentConstraint::ResourceBound,
237 resource_var->WhenBound(demon);
241 void ResourceBound(
int vehicle) {
242 const int64_t resource = vehicle_resource_vars_[vehicle]->Value();
243 if (resource < 0)
return;
244 for (
const RoutingModel::DimensionIndex d :
245 resource_group_.GetAffectedDimensionIndices()) {
246 const RoutingDimension*
const dim = model_.GetDimensions()[d.value()];
247 const RoutingModel::ResourceGroup::Attributes& attributes =
248 resource_group_.GetResources()[resource].GetDimensionAttributes(dim);
251 dim->CumulVar(model_.Start(vehicle))
252 ->SetRange(attributes.start_domain().Min(),
253 attributes.start_domain().Max());
254 dim->CumulVar(model_.End(vehicle))
255 ->SetRange(attributes.end_domain().Min(),
256 attributes.end_domain().Max());
260 const RoutingModel& model_;
261 const RoutingModel::ResourceGroup& resource_group_;
262 const std::vector<IntVar*>& vehicle_resource_vars_;
267 const RoutingModel::ResourceGroup* resource_group,
268 const std::vector<IntVar*>* vehicle_resource_vars, RoutingModel*
model) {
270 resource_group, vehicle_resource_vars,
model));
274class PathSpansAndTotalSlacks :
public Constraint {
276 PathSpansAndTotalSlacks(
const RoutingModel*
model,
277 const RoutingDimension* dimension,
278 std::vector<IntVar*> spans,
279 std::vector<IntVar*> total_slacks)
280 : Constraint(
model->solver()),
282 dimension_(dimension),
283 spans_(
std::move(spans)),
284 total_slacks_(
std::move(total_slacks)) {
285 CHECK_EQ(spans_.size(), model_->vehicles());
286 CHECK_EQ(total_slacks_.size(), model_->vehicles());
287 vehicle_demons_.resize(model_->vehicles());
290 std::string DebugString()
const override {
return "PathSpansAndTotalSlacks"; }
292 void Post()
override {
293 const int num_nodes = model_->VehicleVars().size();
294 const int num_transits = model_->Nexts().size();
295 for (
int node = 0; node < num_nodes; ++node) {
297 model_->solver(),
this, &PathSpansAndTotalSlacks::PropagateNode,
298 "PathSpansAndTotalSlacks::PropagateNode", node);
299 dimension_->CumulVar(node)->WhenRange(demon);
300 model_->VehicleVar(node)->WhenBound(demon);
301 if (node < num_transits) {
302 dimension_->TransitVar(node)->WhenRange(demon);
303 dimension_->FixedTransitVar(node)->WhenBound(demon);
304 model_->NextVar(node)->WhenBound(demon);
307 for (
int vehicle = 0; vehicle < spans_.size(); ++vehicle) {
308 if (!spans_[vehicle] && !total_slacks_[vehicle])
continue;
310 solver(),
this, &PathSpansAndTotalSlacks::PropagateVehicle,
311 "PathSpansAndTotalSlacks::PropagateVehicle", vehicle);
312 vehicle_demons_[vehicle] = demon;
313 if (spans_[vehicle]) spans_[vehicle]->WhenRange(demon);
314 if (total_slacks_[vehicle]) total_slacks_[vehicle]->WhenRange(demon);
315 if (dimension_->HasBreakConstraints()) {
316 for (IntervalVar*
b : dimension_->GetBreakIntervalsOfVehicle(vehicle)) {
317 b->WhenAnything(demon);
324 void InitialPropagate()
override {
325 for (
int vehicle = 0; vehicle < spans_.size(); ++vehicle) {
326 if (!spans_[vehicle] && !total_slacks_[vehicle])
continue;
327 PropagateVehicle(vehicle);
335 void PropagateNode(
int node) {
336 if (!model_->VehicleVar(node)->Bound())
return;
337 const int vehicle = model_->VehicleVar(node)->Min();
338 if (vehicle < 0 || vehicle_demons_[vehicle] ==
nullptr)
return;
339 EnqueueDelayedDemon(vehicle_demons_[vehicle]);
347 int64_t SpanMin(
int vehicle, int64_t sum_fixed_transits) {
348 DCHECK_GE(sum_fixed_transits, 0);
349 const int64_t span_min = spans_[vehicle]
350 ? spans_[vehicle]->Min()
351 : std::numeric_limits<int64_t>::max();
352 const int64_t total_slack_min = total_slacks_[vehicle]
353 ? total_slacks_[vehicle]->Min()
354 : std::numeric_limits<int64_t>::max();
355 return std::min(span_min,
CapAdd(total_slack_min, sum_fixed_transits));
357 int64_t SpanMax(
int vehicle, int64_t sum_fixed_transits) {
358 DCHECK_GE(sum_fixed_transits, 0);
359 const int64_t span_max = spans_[vehicle]
360 ? spans_[vehicle]->Max()
361 : std::numeric_limits<int64_t>::min();
362 const int64_t total_slack_max = total_slacks_[vehicle]
363 ? total_slacks_[vehicle]->Max()
364 : std::numeric_limits<int64_t>::min();
365 return std::max(span_max,
CapAdd(total_slack_max, sum_fixed_transits));
367 void SetSpanMin(
int vehicle, int64_t
min, int64_t sum_fixed_transits) {
368 DCHECK_GE(sum_fixed_transits, 0);
369 if (spans_[vehicle]) {
370 spans_[vehicle]->SetMin(
min);
372 if (total_slacks_[vehicle]) {
373 total_slacks_[vehicle]->SetMin(
CapSub(
min, sum_fixed_transits));
376 void SetSpanMax(
int vehicle, int64_t
max, int64_t sum_fixed_transits) {
377 DCHECK_GE(sum_fixed_transits, 0);
378 if (spans_[vehicle]) {
379 spans_[vehicle]->SetMax(
max);
381 if (total_slacks_[vehicle]) {
382 total_slacks_[vehicle]->SetMax(
CapSub(
max, sum_fixed_transits));
387 void SynchronizeSpanAndTotalSlack(
int vehicle, int64_t sum_fixed_transits) {
388 DCHECK_GE(sum_fixed_transits, 0);
389 IntVar* span = spans_[vehicle];
390 IntVar* total_slack = total_slacks_[vehicle];
391 if (!span || !total_slack)
return;
392 span->SetMin(
CapAdd(total_slack->Min(), sum_fixed_transits));
393 span->SetMax(
CapAdd(total_slack->Max(), sum_fixed_transits));
394 total_slack->SetMin(
CapSub(span->Min(), sum_fixed_transits));
395 total_slack->SetMax(
CapSub(span->Max(), sum_fixed_transits));
398 void PropagateVehicle(
int vehicle) {
399 DCHECK(spans_[vehicle] || total_slacks_[vehicle]);
400 const int start = model_->Start(vehicle);
401 const int end = model_->End(vehicle);
404 if (spans_[vehicle] !=
nullptr &&
405 dimension_->AreVehicleTransitsPositive(vehicle)) {
406 spans_[vehicle]->SetRange(
CapSub(dimension_->CumulVar(
end)->Min(),
407 dimension_->CumulVar(
start)->Max()),
409 dimension_->CumulVar(
start)->Min()));
416 int curr_node =
start;
417 while (!model_->IsEnd(curr_node)) {
418 const IntVar* next_var = model_->NextVar(curr_node);
419 if (!next_var->Bound())
return;
420 path_.push_back(curr_node);
421 curr_node = next_var->Value();
426 int64_t sum_fixed_transits = 0;
427 for (
const int node : path_) {
428 const IntVar* fixed_transit_var = dimension_->FixedTransitVar(node);
429 if (!fixed_transit_var->Bound())
return;
431 CapAdd(sum_fixed_transits, fixed_transit_var->Value());
434 SynchronizeSpanAndTotalSlack(vehicle, sum_fixed_transits);
441 if (dimension_->HasBreakConstraints() &&
442 !dimension_->GetBreakIntervalsOfVehicle(vehicle).empty()) {
443 const int64_t vehicle_start_max = dimension_->CumulVar(
start)->Max();
444 const int64_t vehicle_end_min = dimension_->CumulVar(
end)->Min();
446 int64_t min_break_duration = 0;
447 for (IntervalVar* br : dimension_->GetBreakIntervalsOfVehicle(vehicle)) {
448 if (!br->MustBePerformed())
continue;
449 if (vehicle_start_max < br->EndMin() &&
450 br->StartMax() < vehicle_end_min) {
451 min_break_duration =
CapAdd(min_break_duration, br->DurationMin());
454 SetSpanMin(vehicle,
CapAdd(min_break_duration, sum_fixed_transits),
461 const int64_t slack_max =
462 CapSub(SpanMax(vehicle, sum_fixed_transits), sum_fixed_transits);
463 const int64_t max_additional_slack =
464 CapSub(slack_max, min_break_duration);
465 for (IntervalVar* br : dimension_->GetBreakIntervalsOfVehicle(vehicle)) {
466 if (!br->MustBePerformed())
continue;
468 if (vehicle_start_max >= br->EndMin() &&
469 br->StartMax() < vehicle_end_min) {
470 if (br->DurationMin() > max_additional_slack) {
473 br->SetEndMax(vehicle_start_max);
474 dimension_->CumulVar(
start)->SetMin(br->EndMin());
479 if (vehicle_start_max < br->EndMin() &&
480 br->StartMax() >= vehicle_end_min) {
481 if (br->DurationMin() > max_additional_slack) {
482 br->SetStartMin(vehicle_end_min);
483 dimension_->CumulVar(
end)->SetMax(br->StartMax());
491 IntVar* start_cumul = dimension_->CumulVar(
start);
492 IntVar* end_cumul = dimension_->CumulVar(
end);
493 const int64_t
start_min = start_cumul->Min();
494 const int64_t
start_max = start_cumul->Max();
495 const int64_t
end_min = end_cumul->Min();
496 const int64_t
end_max = end_cumul->Max();
499 SetSpanMin(vehicle, span_lb, sum_fixed_transits);
501 SetSpanMax(vehicle, span_ub, sum_fixed_transits);
503 const int64_t span_min = SpanMin(vehicle, sum_fixed_transits);
504 const int64_t span_max = SpanMax(vehicle, sum_fixed_transits);
505 const int64_t slack_from_lb =
CapSub(span_max, span_lb);
506 const int64_t slack_from_ub =
CapSub(span_ub, span_min);
522 for (
const int node : path_) {
523 span_lb =
CapAdd(span_lb, dimension_->TransitVar(node)->Min());
524 span_ub =
CapAdd(span_ub, dimension_->TransitVar(node)->Max());
526 SetSpanMin(vehicle, span_lb, sum_fixed_transits);
527 SetSpanMax(vehicle, span_ub, sum_fixed_transits);
531 const int64_t span_min = SpanMin(vehicle, sum_fixed_transits);
532 const int64_t span_max = SpanMax(vehicle, sum_fixed_transits);
533 const int64_t slack_from_lb =
CapSub(span_max, span_lb);
534 const int64_t slack_from_ub =
535 span_ub < std::numeric_limits<int64_t>::max()
536 ?
CapSub(span_ub, span_min)
537 :
std::numeric_limits<int64_t>::
max();
538 for (
const int node : path_) {
539 IntVar* transit_var = dimension_->TransitVar(node);
540 const int64_t transit_i_min = transit_var->Min();
541 const int64_t transit_i_max = transit_var->Max();
545 transit_var->SetMax(
CapAdd(transit_i_min, slack_from_lb));
546 transit_var->SetMin(
CapSub(transit_i_max, slack_from_ub));
551 path_.push_back(
end);
565 int64_t arrival_time = dimension_->CumulVar(
start)->Min();
566 for (
int i = 1;
i < path_.size(); ++
i) {
568 std::max(
CapAdd(arrival_time,
569 dimension_->FixedTransitVar(path_[i - 1])->Min()),
570 dimension_->CumulVar(path_[i])->Min());
571 dimension_->CumulVar(path_[i])->SetMin(arrival_time);
576 int64_t departure_time = arrival_time;
577 for (
int i = path_.size() - 2; i >= 0; --i) {
579 std::min(
CapSub(departure_time,
580 dimension_->FixedTransitVar(path_[i])->Min()),
581 dimension_->CumulVar(path_[i])->Max());
583 const int64_t span_lb =
CapSub(arrival_time, departure_time);
584 SetSpanMin(vehicle, span_lb, sum_fixed_transits);
585 const int64_t maximum_deviation =
586 CapSub(SpanMax(vehicle, sum_fixed_transits), span_lb);
587 const int64_t start_lb =
CapSub(departure_time, maximum_deviation);
588 dimension_->CumulVar(
start)->SetMin(start_lb);
593 int64_t departure_time = dimension_->CumulVar(
end)->Max();
594 for (
int i = path_.size() - 2; i >= 0; --i) {
596 std::min(
CapSub(departure_time,
597 dimension_->FixedTransitVar(path_[i])->Min()),
598 dimension_->CumulVar(path_[i])->Max());
599 dimension_->CumulVar(path_[i])->SetMax(departure_time);
604 int arrival_time = departure_time;
605 for (
int i = 1;
i < path_.size(); ++
i) {
607 std::max(
CapAdd(arrival_time,
608 dimension_->FixedTransitVar(path_[i - 1])->Min()),
609 dimension_->CumulVar(path_[i])->Min());
611 const int64_t span_lb =
CapSub(arrival_time, departure_time);
612 SetSpanMin(vehicle, span_lb, sum_fixed_transits);
613 const int64_t maximum_deviation =
614 CapSub(SpanMax(vehicle, sum_fixed_transits), span_lb);
615 dimension_->CumulVar(
end)->SetMax(
616 CapAdd(arrival_time, maximum_deviation));
620 const RoutingModel*
const model_;
621 const RoutingDimension*
const dimension_;
622 std::vector<IntVar*> spans_;
623 std::vector<IntVar*> total_slacks_;
624 std::vector<int> path_;
625 std::vector<Demon*> vehicle_demons_;
630 std::vector<IntVar*> spans,
631 std::vector<IntVar*> total_slacks) {
632 RoutingModel*
const model = dimension->model();
633 CHECK_EQ(
model->vehicles(), spans.size());
634 CHECK_EQ(
model->vehicles(), total_slacks.size());
635 return model->solver()->RevAlloc(
636 new PathSpansAndTotalSlacks(
model, dimension, spans, total_slacks));
649class LightRangeLessOrEqual :
public Constraint {
651 LightRangeLessOrEqual(Solver* s, IntExpr* l, IntExpr* r);
652 ~LightRangeLessOrEqual()
override {}
653 void Post()
override;
654 void InitialPropagate()
override;
655 std::string DebugString()
const override;
656 IntVar* Var()
override {
657 return solver()->MakeIsLessOrEqualVar(left_, right_);
660 void Accept(ModelVisitor*
const visitor)
const override {
671 IntExpr*
const left_;
672 IntExpr*
const right_;
676LightRangeLessOrEqual::LightRangeLessOrEqual(Solver*
const s, IntExpr*
const l,
678 : Constraint(s), left_(l), right_(r), demon_(nullptr) {}
680void LightRangeLessOrEqual::Post() {
682 solver(),
this, &LightRangeLessOrEqual::CheckRange,
"CheckRange");
683 left_->WhenRange(demon_);
684 right_->WhenRange(demon_);
687void LightRangeLessOrEqual::InitialPropagate() {
688 left_->SetMax(right_->Max());
689 right_->SetMin(left_->Min());
690 if (left_->Max() <= right_->Min()) {
691 demon_->inhibit(solver());
695void LightRangeLessOrEqual::CheckRange() {
696 if (left_->Min() > right_->Max()) {
699 if (left_->Max() <= right_->Min()) {
700 demon_->inhibit(solver());
704std::string LightRangeLessOrEqual::DebugString()
const {
705 return left_->DebugString() +
" < " + right_->DebugString();
std::vector< int > dimensions
static const char kLessOrEqual[]
static const char kRightArgument[]
static const char kValuesArgument[]
static const char kVarsArgument[]
static const char kLeftArgument[]
For the time being, Solver is neither MT_SAFE nor MT_HOT.
In SWIG mode, we don't want anything besides these top-level includes.
int64_t CapAdd(int64_t x, int64_t y)
std::vector< int64_t > ComputeVehicleEndChainStarts(const RoutingModel &model)
int64_t CapSub(int64_t x, int64_t y)
bool ComputeVehicleToResourceClassAssignmentCosts(int v, const RoutingModel::ResourceGroup &resource_group, const util_intops::StrongVector< RoutingModel::ResourceClassIndex, absl::flat_hash_set< int > > &ignored_resources_per_class, const std::function< int64_t(int64_t)> &next_accessor, const std::function< int64_t(int64_t, int64_t)> &transit_accessor, bool optimize_vehicle_costs, LocalDimensionCumulOptimizer *lp_optimizer, LocalDimensionCumulOptimizer *mp_optimizer, std::vector< int64_t > *assignment_costs, std::vector< std::vector< int64_t > > *cumul_values, std::vector< std::vector< int64_t > > *break_values)
Constraint * MakePathSpansAndTotalSlacks(const RoutingDimension *dimension, std::vector< IntVar * > spans, std::vector< IntVar * > total_slacks)
Demon * MakeConstraintDemon0(Solver *const s, T *const ct, void(T::*method)(), const std::string &name)
Constraint * MakeResourceConstraint(const RoutingModel::ResourceGroup *resource_group, const std::vector< IntVar * > *vehicle_resource_vars, RoutingModel *model)
Demon * MakeDelayedConstraintDemon1(Solver *const s, T *const ct, void(T::*method)(P), const std::string &name, P param1)
Demon * MakeConstraintDemon1(Solver *const s, T *const ct, void(T::*method)(P), const std::string &name, P param1)
Constraint * MakeDifferentFromValues(Solver *solver, IntVar *var, std::vector< int64_t > values)
int64_t ComputeBestVehicleToResourceAssignment(const std::vector< int > &vehicles, const util_intops::StrongVector< RoutingModel::ResourceClassIndex, std::vector< int > > &resource_indices_per_class, const util_intops::StrongVector< RoutingModel::ResourceClassIndex, absl::flat_hash_set< int > > &ignored_resources_per_class, std::function< const std::vector< int64_t > *(int)> vehicle_to_resource_class_assignment_costs, std::vector< int > *resource_indices)
std::vector< int64_t > assignment_costs
std::optional< int64_t > end