Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
routing_decision_builders.cc
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
15
16#include <algorithm>
17#include <cstdint>
18#include <functional>
19#include <limits>
20#include <string>
21#include <tuple>
22#include <utility>
23#include <vector>
24
25#include "absl/algorithm/container.h"
26#include "absl/container/flat_hash_set.h"
27#include "absl/log/check.h"
28#include "absl/types/span.h"
35
36namespace operations_research {
37
38namespace {
39
40// A decision builder which tries to assign values to variables as close as
41// possible to target values first.
42class SetValuesFromTargets : public DecisionBuilder {
43 public:
44 SetValuesFromTargets(std::vector<IntVar*> variables,
45 std::vector<int64_t> targets)
46 : variables_(std::move(variables)),
47 targets_(std::move(targets)),
48 index_(0),
49 steps_(variables_.size(), 0) {
50 DCHECK_EQ(variables_.size(), targets_.size());
51 }
52 Decision* Next(Solver* solver) override {
53 int index = index_.Value();
54 while (index < variables_.size() && variables_[index]->Bound()) {
55 ++index;
56 }
57 index_.SetValue(solver, index);
58 if (index >= variables_.size()) return nullptr;
59 const int64_t variable_min = variables_[index]->Min();
60 const int64_t variable_max = variables_[index]->Max();
61 // Target can be before, inside, or after the variable range.
62 // We do a trichotomy on this for clarity.
63 if (targets_[index] <= variable_min) {
64 return solver->MakeAssignVariableValue(variables_[index], variable_min);
65 } else if (targets_[index] >= variable_max) {
66 return solver->MakeAssignVariableValue(variables_[index], variable_max);
67 } else {
68 int64_t step = steps_[index];
69 int64_t value = CapAdd(targets_[index], step);
70 // If value is out of variable's range, we can remove the interval of
71 // values already explored (which can make the solver fail) and
72 // recall Next() to get back into the trichotomy above.
73 if (value < variable_min || variable_max < value) {
74 step = GetNextStep(step);
75 value = CapAdd(targets_[index], step);
76 if (step > 0) {
77 // Values in [variable_min, value) were already explored.
78 variables_[index]->SetMin(value);
79 } else {
80 // Values in (value, variable_max] were already explored.
81 variables_[index]->SetMax(value);
82 }
83 return Next(solver);
84 }
85 steps_.SetValue(solver, index, GetNextStep(step));
86 return solver->MakeAssignVariableValueOrDoNothing(variables_[index],
87 value);
88 }
89 }
90
91 private:
92 int64_t GetNextStep(int64_t step) const {
93 return (step > 0) ? -step : CapSub(1, step);
94 }
95 const std::vector<IntVar*> variables_;
96 const std::vector<int64_t> targets_;
97 Rev<int> index_;
98 RevArray<int64_t> steps_;
99};
100
101} // namespace
102
104 std::vector<IntVar*> variables,
105 std::vector<int64_t> targets) {
106 return solver->RevAlloc(
107 new SetValuesFromTargets(std::move(variables), std::move(targets)));
108}
109
110namespace {
111
112bool DimensionFixedTransitsEqualTransitEvaluatorForVehicle(
113 const RoutingDimension& dimension, int vehicle) {
114 const RoutingModel* const model = dimension.model();
115 int node = model->Start(vehicle);
116 while (!model->IsEnd(node)) {
117 if (!model->NextVar(node)->Bound()) {
118 return false;
119 }
120 const int next = model->NextVar(node)->Value();
121 if (dimension.transit_evaluator(vehicle)(node, next) !=
122 dimension.FixedTransitVar(node)->Value()) {
123 return false;
124 }
125 node = next;
126 }
127 return true;
128}
129
130bool DimensionFixedTransitsEqualTransitEvaluators(
131 const RoutingDimension& dimension) {
132 for (int vehicle = 0; vehicle < dimension.model()->vehicles(); vehicle++) {
133 if (!DimensionFixedTransitsEqualTransitEvaluatorForVehicle(dimension,
134 vehicle)) {
135 return false;
136 }
137 }
138 return true;
139}
140
141// Concatenates cumul_values and break_values into 'values', and generates the
142// corresponding 'variables' vector.
143void AppendRouteCumulAndBreakVarAndValues(
144 const RoutingDimension& dimension, int vehicle,
145 absl::Span<const int64_t> cumul_values,
146 absl::Span<const int64_t> break_values, std::vector<IntVar*>* variables,
147 std::vector<int64_t>* values) {
148 auto& vars = *variables;
149 auto& vals = *values;
150 DCHECK_EQ(vars.size(), vals.size());
151 const int old_num_values = vals.size();
152 vals.insert(vals.end(), cumul_values.begin(), cumul_values.end());
153 const RoutingModel& model = *dimension.model();
154 {
155 int current = model.Start(vehicle);
156 while (true) {
157 vars.push_back(dimension.CumulVar(current));
158 if (!model.IsEnd(current)) {
159 current = model.NextVar(current)->Value();
160 } else {
161 break;
162 }
163 }
164 }
165 if (dimension.HasBreakConstraints()) {
166 for (IntervalVar* interval :
167 dimension.GetBreakIntervalsOfVehicle(vehicle)) {
168 vars.push_back(interval->SafeStartExpr(0)->Var());
169 vars.push_back(interval->SafeEndExpr(0)->Var());
170 }
171 vals.insert(vals.end(), break_values.begin(), break_values.end());
172 }
173 DCHECK_EQ(vars.size(), vals.size());
174 int new_num_values = old_num_values;
175 for (int j = old_num_values; j < vals.size(); ++j) {
176 // Value kint64min signals an unoptimized variable, skip setting those.
177 if (vals[j] == std::numeric_limits<int64_t>::min()) continue;
178 // Skip variables that are not bound.
179 if (vars[j]->Bound()) continue;
180 vals[new_num_values] = vals[j];
181 vars[new_num_values] = vars[j];
182 ++new_num_values;
183 }
184 vars.resize(new_num_values);
185 vals.resize(new_num_values);
186}
187
188namespace {
189int GetVehicleRouteSize(const RoutingModel& model, int vehicle) {
190 int route_size = -1;
191 int64_t node = model.Start(vehicle);
192 while (node != model.End(vehicle)) {
193 route_size++;
194 DCHECK(model.NextVar(node)->Bound());
195 node = model.NextVar(node)->Value();
196 }
197 DCHECK_GE(route_size, 0);
198 return route_size;
199}
200} // namespace
201
202class SetCumulsFromLocalDimensionCosts : public DecisionBuilder {
203 public:
204 SetCumulsFromLocalDimensionCosts(
205 LocalDimensionCumulOptimizer* lp_optimizer,
206 LocalDimensionCumulOptimizer* mp_optimizer, bool optimize_and_pack,
207 std::vector<RoutingModel::RouteDimensionTravelInfo>
208 dimension_travel_info_per_route)
209 : model_(*lp_optimizer->dimension()->model()),
210 dimension_(*lp_optimizer->dimension()),
211 lp_optimizer_(lp_optimizer),
212 mp_optimizer_(mp_optimizer),
213 rg_index_(model_.GetDimensionResourceGroupIndices(&dimension_).empty()
214 ? -1
215 : model_.GetDimensionResourceGroupIndex(&dimension_)),
216 resource_group_(rg_index_ >= 0 ? model_.GetResourceGroup(rg_index_)
217 : nullptr),
218 vehicle_resource_class_values_(model_.vehicles()),
219 optimize_and_pack_(optimize_and_pack),
220 dimension_travel_info_per_route_(
221 std::move(dimension_travel_info_per_route)),
222 decision_level_(0) {
223 if (!dimension_travel_info_per_route_.empty()) {
224 DCHECK(optimize_and_pack_);
225 DCHECK_EQ(dimension_travel_info_per_route_.size(), model_.vehicles());
226 }
227 }
228
229 Decision* Next(Solver* solver) override {
230 if (decision_level_.Value() == 2) return nullptr;
231 if (decision_level_.Value() == 1) {
232 Decision* d = set_values_from_targets_->Next(solver);
233 if (d == nullptr) decision_level_.SetValue(solver, 2);
234 return d;
235 }
236 decision_level_.SetValue(solver, 1);
237 if (!FillCPVariablesAndValues(solver)) {
238 solver->Fail();
239 }
240 set_values_from_targets_ =
241 MakeSetValuesFromTargets(solver, cp_variables_, cp_values_);
242 return solver->MakeAssignVariablesValuesOrDoNothing(cp_variables_,
243 cp_values_);
244 }
245
246 private:
247 using Resource = RoutingModel::ResourceGroup::Resource;
248 using RCIndex = RoutingModel::ResourceClassIndex;
249 using RouteDimensionTravelInfo = RoutingModel::RouteDimensionTravelInfo;
250
251 bool FillCPVariablesAndValues(Solver* solver) {
252 DCHECK(DimensionFixedTransitsEqualTransitEvaluators(dimension_));
253 cp_variables_.clear();
254 cp_values_.clear();
255 vehicles_without_resource_assignment_.clear();
256 vehicles_with_resource_assignment_.clear();
257
258 used_resources_per_class_.clear();
259 DetermineVehiclesRequiringResourceAssignment(
260 &vehicles_without_resource_assignment_,
261 &vehicles_with_resource_assignment_, &used_resources_per_class_);
262
263 const auto next = [&model = model_](int64_t n) {
264 return model.NextVar(n)->Value();
265 };
266
267 // First look at vehicles that do not need resource assignment (fewer/faster
268 // computations).
269 // NOTE(user): If it ever becomes an issue, we can consider leaving more
270 // 'shares' for the resource assignment calls since they're more expensive.
271 int solve_duration_shares = vehicles_without_resource_assignment_.size() +
272 vehicles_with_resource_assignment_.size();
273 for (int vehicle : vehicles_without_resource_assignment_) {
274 // This can trigger a fail if the time limit is reached.
275 solver->TopPeriodicCheck();
276 cumul_values_.clear();
277 break_start_end_values_.clear();
278 // TODO(user): Distinguish between FEASIBLE and OPTIMAL statuses to
279 // keep track of the FEASIBLE-only cases, and resolve the feasible-only
280 // cases with the remaining time (if any) after all routes have been
281 // scheduled with the initial 'solve_duration_ratio'.
282 if (!ComputeCumulAndBreakValuesForVehicle(
283 vehicle, /*solve_duration_ratio=*/1.0 / solve_duration_shares,
284 next, &cumul_values_, &break_start_end_values_)) {
285 return false;
286 }
287 solve_duration_shares--;
288 AppendRouteCumulAndBreakVarAndValues(dimension_, vehicle, cumul_values_,
289 break_start_end_values_,
290 &cp_variables_, &cp_values_);
291 }
292
293 if (vehicles_with_resource_assignment_.empty()) {
294 return true;
295 }
296
297 // Do resource assignment for the vehicles requiring it and append the
298 // corresponding var and values.
299 resource_indices_.clear();
300 if (!ComputeVehicleResourceClassValuesAndIndices(
301 vehicles_with_resource_assignment_, used_resources_per_class_, next,
302 &resource_indices_)) {
303 return false;
304 }
305 DCHECK_EQ(resource_indices_.size(), model_.vehicles());
306 const int num_resource_classes = resource_group_->GetResourceClassesCount();
307 for (int v : vehicles_with_resource_assignment_) {
308 DCHECK(next(model_.Start(v)) != model_.End(v) ||
309 model_.IsVehicleUsedWhenEmpty(v));
310 const auto& [unused, cumul_values, break_values] =
311 vehicle_resource_class_values_[v];
312 const int resource_index = resource_indices_[v];
313 DCHECK_GE(resource_index, 0);
314 DCHECK_EQ(cumul_values.size(), num_resource_classes);
315 DCHECK_EQ(break_values.size(), num_resource_classes);
316 const int rc_index =
317 resource_group_->GetResourceClassIndex(resource_index).value();
318 const std::vector<int64_t>& optimal_cumul_values = cumul_values[rc_index];
319 const std::vector<int64_t>& optimal_break_values = break_values[rc_index];
320 AppendRouteCumulAndBreakVarAndValues(dimension_, v, optimal_cumul_values,
321 optimal_break_values, &cp_variables_,
322 &cp_values_);
323
324 const std::vector<IntVar*>& resource_vars =
325 model_.ResourceVars(rg_index_);
326 DCHECK_EQ(resource_vars.size(), resource_indices_.size());
327 cp_variables_.insert(cp_variables_.end(), resource_vars.begin(),
328 resource_vars.end());
329 cp_values_.insert(cp_values_.end(), resource_indices_.begin(),
330 resource_indices_.end());
331 }
332 return true;
333 }
334
335 inline void DetermineVehiclesRequiringResourceAssignment(
336 std::vector<int>* vehicles_without_resource_assignment,
337 std::vector<int>* vehicles_with_resource_assignment,
338 util_intops::StrongVector<RCIndex, absl::flat_hash_set<int>>*
339 used_resources_per_class) const {
340 DCHECK(vehicles_without_resource_assignment->empty());
341 DCHECK(vehicles_with_resource_assignment->empty());
342 DCHECK(used_resources_per_class->empty());
343 struct VehicleInfo {
344 int vehicle_index;
345 int route_size;
346 bool requires_resource;
347#if __cplusplus < 202002L
348 VehicleInfo(int vi, int rs, bool rr)
349 : vehicle_index(vi), route_size(rs), requires_resource(rr) {}
350#endif
351 bool operator<(const VehicleInfo& other) const {
352 return std::tie(route_size, vehicle_index) <
353 std::tie(other.route_size, other.vehicle_index);
354 }
355 };
356
357 std::vector<VehicleInfo> vehicle_info;
358 vehicle_info.reserve(model_.vehicles());
359 if (rg_index_ < 0) {
360 for (int v = 0; v < model_.vehicles(); ++v) {
361 const int route_size = GetVehicleRouteSize(model_, v);
362 vehicle_info.emplace_back(v, route_size, false);
363 }
364 absl::c_sort(vehicle_info);
365 vehicles_without_resource_assignment->resize(model_.vehicles());
366 absl::c_transform(vehicle_info,
367 vehicles_without_resource_assignment->begin(),
368 [](const VehicleInfo& v) { return v.vehicle_index; });
369 return;
370 }
371
372 DCHECK_NE(resource_group_, nullptr);
373 used_resources_per_class->resize(
374 resource_group_->GetResourceClassesCount());
375 int num_vehicles_with_resource_assignment = 0;
376 for (int v = 0; v < model_.vehicles(); ++v) {
377 bool needs_resource = resource_group_->VehicleRequiresAResource(v);
378 if (needs_resource) {
379 if (model_.NextVar(model_.Start(v))->Value() == model_.End(v) &&
380 !model_.IsVehicleUsedWhenEmpty(v)) {
381 // No resource assignment required for this unused vehicle.
382 // TODO(user): Investigate if we should skip unused vehicles.
383 needs_resource = false;
384 } else if (model_.ResourceVar(v, rg_index_)->Bound()) {
385 needs_resource = false;
386 const int resource_idx = model_.ResourceVar(v, rg_index_)->Value();
387 DCHECK_GE(resource_idx, 0);
388 used_resources_per_class
389 ->at(resource_group_->GetResourceClassIndex(resource_idx))
390 .insert(resource_idx);
391 } else {
392 num_vehicles_with_resource_assignment++;
393 }
394 }
395 vehicle_info.emplace_back(v, GetVehicleRouteSize(model_, v),
396 needs_resource);
397 }
398 absl::c_sort(vehicle_info);
399 vehicles_with_resource_assignment->reserve(
400 num_vehicles_with_resource_assignment);
401 vehicles_without_resource_assignment->reserve(
402 model_.vehicles() - num_vehicles_with_resource_assignment);
403 for (const VehicleInfo& v_info : vehicle_info) {
404 if (v_info.requires_resource) {
405 vehicles_with_resource_assignment->push_back(v_info.vehicle_index);
406 } else {
407 vehicles_without_resource_assignment->push_back(v_info.vehicle_index);
408 }
409 }
410 DCHECK_EQ(vehicles_without_resource_assignment->size() +
411 vehicles_with_resource_assignment->size(),
412 model_.vehicles());
413 }
414
415 bool ComputeCumulAndBreakValuesForVehicle(
416 int vehicle, double solve_duration_ratio,
417 const std::function<int64_t(int64_t)>& next_accessor,
418 std::vector<int64_t>* cumul_values,
419 std::vector<int64_t>* break_start_end_values) {
420 cumul_values->clear();
421 break_start_end_values->clear();
422 const RouteDimensionTravelInfo* const dimension_travel_info =
423 dimension_travel_info_per_route_.empty()
424 ? nullptr
425 : &dimension_travel_info_per_route_[vehicle];
426 const Resource* resource = nullptr;
427 if (rg_index_ >= 0 && model_.ResourceVar(vehicle, rg_index_)->Bound()) {
428 const int resource_index =
429 model_.ResourceVar(vehicle, rg_index_)->Value();
430 if (resource_index >= 0) {
431 resource =
432 &model_.GetResourceGroup(rg_index_)->GetResource(resource_index);
433 }
434 }
435 const bool use_mp_optimizer =
436 dimension_.HasQuadraticCostSoftSpanUpperBounds() ||
437 (dimension_.HasBreakConstraints() &&
438 !dimension_.GetBreakIntervalsOfVehicle(vehicle).empty());
439 LocalDimensionCumulOptimizer* const optimizer =
440 use_mp_optimizer ? mp_optimizer_ : lp_optimizer_;
441 DCHECK_NE(optimizer, nullptr);
443 optimize_and_pack_ ? optimizer->ComputePackedRouteCumuls(
444 vehicle, solve_duration_ratio, next_accessor,
445 dimension_travel_info, resource, cumul_values,
446 break_start_end_values)
447 : optimizer->ComputeRouteCumuls(
448 vehicle, solve_duration_ratio, next_accessor,
449 dimension_travel_info, resource, cumul_values,
450 break_start_end_values);
451 // If relaxation is not feasible, try the MP optimizer.
453 DCHECK(!use_mp_optimizer);
454 DCHECK_NE(mp_optimizer_, nullptr);
455 status = optimize_and_pack_
456 ? mp_optimizer_->ComputePackedRouteCumuls(
457 vehicle, solve_duration_ratio, next_accessor,
458 dimension_travel_info, resource, cumul_values,
459 break_start_end_values)
460 : mp_optimizer_->ComputeRouteCumuls(
461 vehicle, solve_duration_ratio, next_accessor,
462 dimension_travel_info, resource, cumul_values,
463 break_start_end_values);
464 }
466 }
467
468 bool ComputeVehicleResourceClassValuesAndIndices(
469 absl::Span<const int> vehicles_to_assign,
470 const util_intops::StrongVector<RCIndex, absl::flat_hash_set<int>>&
471 used_resources_per_class,
472 const std::function<int64_t(int64_t)>& next_accessor,
473 std::vector<int>* resource_indices) {
474 resource_indices->assign(model_.vehicles(), -1);
475 if (vehicles_to_assign.empty()) return true;
476 DCHECK_NE(resource_group_, nullptr);
477
478 int solve_duration_shares = vehicles_to_assign.size();
479 for (int v : vehicles_to_assign) {
480 DCHECK(resource_group_->VehicleRequiresAResource(v));
481 auto& [assignment_costs, cumul_values, break_values] =
482 vehicle_resource_class_values_[v];
484 v, /*solve_duration_ratio=*/1.0 / solve_duration_shares,
485 *resource_group_, used_resources_per_class, next_accessor,
486 dimension_.transit_evaluator(v),
487 /*optimize_vehicle_costs*/ true, lp_optimizer_, mp_optimizer_,
488 &assignment_costs, &cumul_values, &break_values)) {
489 return false;
490 }
491 solve_duration_shares--;
492 }
493
495 vehicles_to_assign,
496 resource_group_->GetResourceIndicesPerClass(),
497 used_resources_per_class,
498 [&vehicle_rc_values = vehicle_resource_class_values_](int v) {
499 return &vehicle_rc_values[v].assignment_costs;
500 },
501 resource_indices) >= 0;
502 }
503
504 const RoutingModel& model_;
505 const RoutingDimension& dimension_;
506 LocalDimensionCumulOptimizer* lp_optimizer_;
507 LocalDimensionCumulOptimizer* mp_optimizer_;
508 // Stores the resource group index of the lp_/mp_optimizer_'s dimension, if
509 // there is any.
510 const int rg_index_;
511 const RoutingModel::ResourceGroup* const resource_group_;
512 // Stores the information related to assigning a given vehicle to resource
513 // classes. We keep these as class members to avoid unnecessary memory
514 // reallocations.
515 struct VehicleResourceClassValues {
516 std::vector<int64_t> assignment_costs;
517 std::vector<std::vector<int64_t>> cumul_values;
518 std::vector<std::vector<int64_t>> break_values;
519 };
520 std::vector<VehicleResourceClassValues> vehicle_resource_class_values_;
521 const bool optimize_and_pack_;
522 const std::vector<RouteDimensionTravelInfo> dimension_travel_info_per_route_;
523 std::vector<IntVar*> cp_variables_;
524 std::vector<int64_t> cp_values_;
525 // Decision level of this decision builder:
526 // - level 0: set remaining dimension values at once.
527 // - level 1: set remaining dimension values one by one.
528 Rev<int> decision_level_;
529 DecisionBuilder* set_values_from_targets_ = nullptr;
530 // "Local" variables used by FillCPVariablesAndValues(). They can't be defined
531 // as true local variables, because the function may backtrack when a time
532 // limit is reached.
533 std::vector<int> vehicles_without_resource_assignment_;
534 std::vector<int> vehicles_with_resource_assignment_;
535 util_intops::StrongVector<RCIndex, absl::flat_hash_set<int>>
536 used_resources_per_class_;
537 std::vector<int64_t> cumul_values_;
538 std::vector<int64_t> break_start_end_values_;
539 std::vector<int> resource_indices_;
540};
541
542} // namespace
543
545 Solver* solver, LocalDimensionCumulOptimizer* lp_optimizer,
546 LocalDimensionCumulOptimizer* mp_optimizer, bool optimize_and_pack,
547 std::vector<RoutingModel::RouteDimensionTravelInfo>
548 dimension_travel_info_per_route) {
549 return solver->RevAlloc(new SetCumulsFromLocalDimensionCosts(
550 lp_optimizer, mp_optimizer, optimize_and_pack,
551 std::move(dimension_travel_info_per_route)));
552}
553
554namespace {
555
556class SetCumulsFromGlobalDimensionCosts : public DecisionBuilder {
557 public:
558 SetCumulsFromGlobalDimensionCosts(
559 GlobalDimensionCumulOptimizer* global_optimizer,
560 GlobalDimensionCumulOptimizer* global_mp_optimizer,
561 bool optimize_and_pack,
562 std::vector<RoutingModel::RouteDimensionTravelInfo>
563 dimension_travel_info_per_route)
564 : global_optimizer_(global_optimizer),
565 global_mp_optimizer_(global_mp_optimizer),
566 optimize_and_pack_(optimize_and_pack),
567 dimension_travel_info_per_route_(
568 std::move(dimension_travel_info_per_route)),
569 decision_level_(0) {
570 DCHECK(dimension_travel_info_per_route_.empty() ||
571 dimension_travel_info_per_route_.size() ==
572 global_optimizer_->dimension()->model()->vehicles());
573 // Store the cp variables used to set values on in Next().
574 // NOTE: The order is important as we use the same order to add values
575 // in cp_values_.
576 const RoutingDimension* dimension = global_optimizer_->dimension();
577 const RoutingModel* model = dimension->model();
578 cp_variables_ = dimension->cumuls();
579 if (dimension->HasBreakConstraints()) {
580 for (int vehicle = 0; vehicle < model->vehicles(); ++vehicle) {
581 for (IntervalVar* interval :
582 dimension->GetBreakIntervalsOfVehicle(vehicle)) {
583 cp_variables_.push_back(interval->SafeStartExpr(0)->Var());
584 cp_variables_.push_back(interval->SafeEndExpr(0)->Var());
585 }
586 }
587 }
588 // NOTE: When packing, the resource variables should already have a bound
589 // value which is taken into account by the optimizer, so we don't set them
590 // in MakeSetValuesFromTargets().
591 if (!optimize_and_pack_) {
592 for (int rg_index : model->GetDimensionResourceGroupIndices(dimension)) {
593 const std::vector<IntVar*>& res_vars = model->ResourceVars(rg_index);
594 cp_variables_.insert(cp_variables_.end(), res_vars.begin(),
595 res_vars.end());
596 }
597 }
598 }
599
600 Decision* Next(Solver* solver) override {
601 if (decision_level_.Value() == 2) return nullptr;
602 if (decision_level_.Value() == 1) {
603 Decision* d = set_values_from_targets_->Next(solver);
604 if (d == nullptr) decision_level_.SetValue(solver, 2);
605 return d;
606 }
607 decision_level_.SetValue(solver, 1);
608 if (!FillCPValues()) {
609 solver->Fail();
610 }
611 set_values_from_targets_ =
612 MakeSetValuesFromTargets(solver, cp_variables_, cp_values_);
613 return solver->MakeAssignVariablesValuesOrDoNothing(cp_variables_,
614 cp_values_);
615 }
616
617 private:
618 bool FillCPValues() {
619 const RoutingDimension* dimension = global_optimizer_->dimension();
620 DCHECK(DimensionFixedTransitsEqualTransitEvaluators(*dimension));
621 RoutingModel* const model = dimension->model();
622
623 GlobalDimensionCumulOptimizer* const optimizer =
624 model->GetDimensionResourceGroupIndices(dimension).empty()
625 ? global_optimizer_
626 : global_mp_optimizer_;
627 DimensionSchedulingStatus status = ComputeCumulBreakAndResourceValues(
628 optimizer, &cumul_values_, &break_start_end_values_,
629 &resource_indices_per_group_);
631 // If relaxation is not feasible, try the MILP optimizer.
632 status = ComputeCumulBreakAndResourceValues(
633 global_mp_optimizer_, &cumul_values_, &break_start_end_values_,
634 &resource_indices_per_group_);
635 }
637 return false;
638 }
639 // Concatenate cumul_values_, break_start_end_values_ and all
640 // resource_indices_per_group_ into cp_values_.
641 // NOTE: The order is important as it corresponds to the order of
642 // variables in cp_variables_.
643 cp_values_ = std::move(cumul_values_);
644 if (dimension->HasBreakConstraints()) {
645 cp_values_.insert(cp_values_.end(), break_start_end_values_.begin(),
646 break_start_end_values_.end());
647 }
648 if (optimize_and_pack_) {
649// Resource variables should be bound when packing, so we don't need
650// to restore them again.
651#ifndef NDEBUG
652 for (int rg_index : model->GetDimensionResourceGroupIndices(dimension)) {
653 for (IntVar* res_var : model->ResourceVars(rg_index)) {
654 DCHECK(res_var->Bound());
655 }
656 }
657#endif
658 } else {
659 // Add resource values to cp_values_.
660 for (int rg_index : model->GetDimensionResourceGroupIndices(dimension)) {
661 const std::vector<int>& resource_values =
662 resource_indices_per_group_[rg_index];
663 DCHECK(!resource_values.empty());
664 cp_values_.insert(cp_values_.end(), resource_values.begin(),
665 resource_values.end());
666 }
667 }
668 DCHECK_EQ(cp_variables_.size(), cp_values_.size());
669 // Value kint64min signals an unoptimized variable, set to min instead.
670 for (int j = 0; j < cp_values_.size(); ++j) {
671 if (cp_values_[j] == std::numeric_limits<int64_t>::min()) {
672 cp_values_[j] = cp_variables_[j]->Min();
673 }
674 }
675 return true;
676 }
677
678 DimensionSchedulingStatus ComputeCumulBreakAndResourceValues(
679 GlobalDimensionCumulOptimizer* optimizer,
680 std::vector<int64_t>* cumul_values,
681 std::vector<int64_t>* break_start_end_values,
682 std::vector<std::vector<int>>* resource_indices_per_group) {
683 DCHECK_NE(optimizer, nullptr);
684 cumul_values->clear();
685 break_start_end_values->clear();
686 resource_indices_per_group->clear();
687 RoutingModel* const model = optimizer->dimension()->model();
688 const auto next = [model](int64_t n) { return model->NextVar(n)->Value(); };
689 return optimize_and_pack_
690 ? optimizer->ComputePackedCumuls(
691 next, dimension_travel_info_per_route_, cumul_values,
692 break_start_end_values)
693 : optimizer->ComputeCumuls(
694 next, dimension_travel_info_per_route_, cumul_values,
695 break_start_end_values, resource_indices_per_group);
696 }
697
698 GlobalDimensionCumulOptimizer* const global_optimizer_;
699 GlobalDimensionCumulOptimizer* const global_mp_optimizer_;
700 const bool optimize_and_pack_;
701 std::vector<IntVar*> cp_variables_;
702 std::vector<int64_t> cp_values_;
703 // The following 3 members are stored internally to avoid unnecessary memory
704 // reallocations.
705 std::vector<int64_t> cumul_values_;
706 std::vector<int64_t> break_start_end_values_;
707 std::vector<std::vector<int>> resource_indices_per_group_;
708 const std::vector<RoutingModel::RouteDimensionTravelInfo>
709 dimension_travel_info_per_route_;
710 // Decision level of this decision builder:
711 // - level 0: set remaining dimension values at once.
712 // - level 1: set remaining dimension values one by one.
713 Rev<int> decision_level_;
714 DecisionBuilder* set_values_from_targets_ = nullptr;
715};
716
717} // namespace
718
720 Solver* solver, GlobalDimensionCumulOptimizer* global_optimizer,
721 GlobalDimensionCumulOptimizer* global_mp_optimizer, bool optimize_and_pack,
722 std::vector<RoutingModel::RouteDimensionTravelInfo>
723 dimension_travel_info_per_route) {
724 return solver->RevAlloc(new SetCumulsFromGlobalDimensionCosts(
725 global_optimizer, global_mp_optimizer, optimize_and_pack,
726 std::move(dimension_travel_info_per_route)));
727}
728
729namespace {
730// A decision builder that tries to set variables to their value in the last
731// solution, if their corresponding vehicle path has not changed.
732// This tries to constrain all such variables in one shot in order to speed up
733// instantiation.
734// TODO(user): try to use Assignment instead of MakeAssignment(),
735// try to record and restore the min/max instead of a single value.
736class RestoreDimensionValuesForUnchangedRoutes : public DecisionBuilder {
737 public:
738 explicit RestoreDimensionValuesForUnchangedRoutes(RoutingModel* model)
739 : model_(model) {
740 model_->AddAtSolutionCallback([this]() { AtSolution(); });
741 model_->AddRestoreDimensionValuesResetCallback([this]() { Reset(); });
742 next_last_value_.resize(model_->Nexts().size(), -1);
743 }
744
745 // In a given branch of a search tree, this decision builder only returns
746 // a Decision once, the first time it is called in that branch.
747 Decision* Next(Solver* const s) override {
748 if (!must_return_decision_) return nullptr;
749 s->SaveAndSetValue(&must_return_decision_, false);
750 return MakeDecision(s);
751 }
752
753 void Reset() { next_last_value_.assign(model_->Nexts().size(), -1); }
754
755 private:
756 // Initialize() is lazy to make sure all dimensions have been instantiated
757 // when initialization is done.
758 void Initialize() {
759 is_initialized_ = true;
760 const int num_nodes = model_->VehicleVars().size();
761 node_to_integer_variable_indices_.resize(num_nodes);
762 node_to_interval_variable_indices_.resize(num_nodes);
763 // Search for dimension variables that correspond to input variables.
764 for (const std::string& dimension_name : model_->GetAllDimensionNames()) {
765 const RoutingDimension& dimension =
766 model_->GetDimensionOrDie(dimension_name);
767 // Search among cumuls and slacks, and attach them to corresponding nodes.
768 for (const std::vector<IntVar*>& dimension_variables :
769 {dimension.cumuls(), dimension.slacks()}) {
770 const int num_dimension_variables = dimension_variables.size();
771 DCHECK_LE(num_dimension_variables, num_nodes);
772 for (int node = 0; node < num_dimension_variables; ++node) {
773 node_to_integer_variable_indices_[node].push_back(
774 integer_variables_.size());
775 integer_variables_.push_back(dimension_variables[node]);
776 }
777 }
778 // Search for break start/end variables, attach them to vehicle starts.
779 for (int vehicle = 0; vehicle < model_->vehicles(); ++vehicle) {
780 if (!dimension.HasBreakConstraints()) continue;
781 const int vehicle_start = model_->Start(vehicle);
782 for (IntervalVar* interval :
783 dimension.GetBreakIntervalsOfVehicle(vehicle)) {
784 node_to_interval_variable_indices_[vehicle_start].push_back(
785 interval_variables_.size());
786 interval_variables_.push_back(interval);
787 }
788 }
789 }
790 integer_variables_last_min_.resize(integer_variables_.size());
791 interval_variables_last_start_min_.resize(interval_variables_.size());
792 interval_variables_last_end_max_.resize(interval_variables_.size());
793 }
794
795 Decision* MakeDecision(Solver* const s) {
796 if (!is_initialized_) return nullptr;
797 // Collect vehicles that have not changed.
798 std::vector<int> unchanged_vehicles;
799 const int num_vehicles = model_->vehicles();
800 for (int v = 0; v < num_vehicles; ++v) {
801 bool unchanged = true;
802 for (int current = model_->Start(v); !model_->IsEnd(current);
803 current = next_last_value_[current]) {
804 if (!model_->NextVar(current)->Bound() ||
805 next_last_value_[current] != model_->NextVar(current)->Value()) {
806 unchanged = false;
807 break;
808 }
809 }
810 if (unchanged) unchanged_vehicles.push_back(v);
811 }
812 // If all routes are unchanged, the solver might be trying to do a full
813 // reschedule. Do nothing.
814 if (unchanged_vehicles.size() == num_vehicles) return nullptr;
815
816 // Collect cumuls and slacks of unchanged routes to be assigned a value.
817 std::vector<IntVar*> vars;
818 std::vector<int64_t> values;
819 for (const int vehicle : unchanged_vehicles) {
820 for (int current = model_->Start(vehicle); true;
821 current = next_last_value_[current]) {
822 for (const int index : node_to_integer_variable_indices_[current]) {
823 vars.push_back(integer_variables_[index]);
824 values.push_back(integer_variables_last_min_[index]);
825 }
826 for (const int index : node_to_interval_variable_indices_[current]) {
827 const int64_t start_min = interval_variables_last_start_min_[index];
828 const int64_t end_max = interval_variables_last_end_max_[index];
829 if (start_min < end_max) {
830 vars.push_back(interval_variables_[index]->SafeStartExpr(0)->Var());
831 values.push_back(interval_variables_last_start_min_[index]);
832 vars.push_back(interval_variables_[index]->SafeEndExpr(0)->Var());
833 values.push_back(interval_variables_last_end_max_[index]);
834 } else {
835 vars.push_back(interval_variables_[index]->PerformedExpr()->Var());
836 values.push_back(0);
837 }
838 }
839 if (model_->IsEnd(current)) break;
840 }
841 }
842 return s->MakeAssignVariablesValuesOrDoNothing(vars, values);
843 }
844
845 void AtSolution() {
846 if (!is_initialized_) Initialize();
847 const int num_integers = integer_variables_.size();
848 // Variables may not be fixed at solution time,
849 // the decision builder is fine with the Min() of the unfixed variables.
850 for (int i = 0; i < num_integers; ++i) {
851 integer_variables_last_min_[i] = integer_variables_[i]->Min();
852 }
853 const int num_intervals = interval_variables_.size();
854 for (int i = 0; i < num_intervals; ++i) {
855 const bool is_performed = interval_variables_[i]->MustBePerformed();
856 interval_variables_last_start_min_[i] =
857 is_performed ? interval_variables_[i]->StartMin() : 0;
858 interval_variables_last_end_max_[i] =
859 is_performed ? interval_variables_[i]->EndMax() : -1;
860 }
861 const int num_nodes = next_last_value_.size();
862 for (int node = 0; node < num_nodes; ++node) {
863 if (model_->IsEnd(node)) continue;
864 next_last_value_[node] = model_->NextVar(node)->Value();
865 }
866 }
867
868 // Input data.
869 RoutingModel* const model_;
870
871 // The valuation of the last solution.
872 std::vector<int> next_last_value_;
873 // For every node, the indices of integer_variables_ and interval_variables_
874 // that correspond to that node.
875 std::vector<std::vector<int>> node_to_integer_variable_indices_;
876 std::vector<std::vector<int>> node_to_interval_variable_indices_;
877 // Variables and the value they had in the previous solution.
878 std::vector<IntVar*> integer_variables_;
879 std::vector<int64_t> integer_variables_last_min_;
880 std::vector<IntervalVar*> interval_variables_;
881 std::vector<int64_t> interval_variables_last_start_min_;
882 std::vector<int64_t> interval_variables_last_end_max_;
883
884 bool is_initialized_ = false;
885 bool must_return_decision_ = true;
886};
887} // namespace
888
890 RoutingModel* model) {
891 return model->solver()->RevAlloc(
892 new RestoreDimensionValuesForUnchangedRoutes(model));
893}
894
895// FinalizerVariables
896
898 int64_t cost) {
899 CHECK(var != nullptr);
900 const int index =
901 gtl::LookupOrInsert(&weighted_finalizer_variable_index_, var,
902 weighted_finalizer_variable_targets_.size());
903 if (index < weighted_finalizer_variable_targets_.size()) {
904 auto& [var_target, total_cost] =
905 weighted_finalizer_variable_targets_[index];
906 DCHECK_EQ(var_target.var, var);
907 DCHECK_EQ(var_target.target, target);
908 total_cost = CapAdd(total_cost, cost);
909 } else {
910 DCHECK_EQ(index, weighted_finalizer_variable_targets_.size());
911 weighted_finalizer_variable_targets_.push_back({{var, target}, cost});
912 }
913}
914
916 CHECK(var != nullptr);
917 if (finalizer_variable_target_set_.contains(var)) return;
918 finalizer_variable_target_set_.insert(var);
919 finalizer_variable_targets_.push_back({var, target});
920}
921
923 std::stable_sort(weighted_finalizer_variable_targets_.begin(),
924 weighted_finalizer_variable_targets_.end(),
925 [](const std::pair<VarTarget, int64_t>& var_cost1,
926 const std::pair<VarTarget, int64_t>& var_cost2) {
927 return var_cost1.second > var_cost2.second;
928 });
929 const int num_variables = weighted_finalizer_variable_targets_.size() +
930 finalizer_variable_targets_.size();
931 std::vector<IntVar*> variables;
932 std::vector<int64_t> targets;
933 variables.reserve(num_variables);
934 targets.reserve(num_variables);
935 for (const auto& [var_target, cost] : weighted_finalizer_variable_targets_) {
936 variables.push_back(var_target.var);
937 targets.push_back(var_target.target);
938 }
939 for (const auto& [var, target] : finalizer_variable_targets_) {
940 variables.push_back(var);
941 targets.push_back(target);
942 }
943 return MakeSetValuesFromTargets(solver_, std::move(variables),
944 std::move(targets));
945}
946
947} // namespace operations_research
void AddVariableTarget(IntVar *var, int64_t target)
void AddWeightedVariableTarget(IntVar *var, int64_t target, int64_t cost)
RoutingResourceClassIndex ResourceClassIndex
Definition routing.h:273
Collection::value_type::second_type & LookupOrInsert(Collection *const collection, const typename Collection::value_type::first_type &key, const typename Collection::value_type::second_type &value)
Definition map_util.h:242
OR-Tools root namespace.
int64_t CapAdd(int64_t x, int64_t y)
int64_t ComputeBestVehicleToResourceAssignment(absl::Span< const 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)
int64_t CapSub(int64_t x, int64_t y)
DecisionBuilder * MakeRestoreDimensionValuesForUnchangedRoutes(RoutingModel *model)
bool ComputeVehicleToResourceClassAssignmentCosts(int v, double solve_duration_ratio, 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)
DecisionBuilder * MakeSetCumulsFromGlobalDimensionCosts(Solver *solver, GlobalDimensionCumulOptimizer *global_optimizer, GlobalDimensionCumulOptimizer *global_mp_optimizer, bool optimize_and_pack, std::vector< RoutingModel::RouteDimensionTravelInfo > dimension_travel_info_per_route)
Variant based on global optimizers, handling all routes together.
DecisionBuilder * MakeSetCumulsFromLocalDimensionCosts(Solver *solver, LocalDimensionCumulOptimizer *lp_optimizer, LocalDimensionCumulOptimizer *mp_optimizer, bool optimize_and_pack, std::vector< RoutingModel::RouteDimensionTravelInfo > dimension_travel_info_per_route)
DecisionBuilder * MakeSetValuesFromTargets(Solver *solver, std::vector< IntVar * > variables, std::vector< int64_t > targets)
STL namespace.
bool Next()
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...