Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
routing_lp_scheduling.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_CONSTRAINT_SOLVER_ROUTING_LP_SCHEDULING_H_
15#define OR_TOOLS_CONSTRAINT_SOLVER_ROUTING_LP_SCHEDULING_H_
16
17#include <algorithm>
18#include <cstdint>
19#include <deque>
20#include <functional>
21#include <limits>
22#include <memory>
23#include <ostream>
24#include <string>
25#include <utility>
26#include <vector>
27
28#include "absl/container/flat_hash_map.h"
29#include "absl/container/flat_hash_set.h"
30#include "absl/log/check.h"
31#include "absl/strings/str_format.h"
32#include "absl/strings/string_view.h"
33#include "absl/time/time.h"
34#include "absl/types/span.h"
38#include "ortools/constraint_solver/routing_parameters.pb.h"
40#include "ortools/glop/parameters.pb.h"
44#include "ortools/sat/cp_model.pb.h"
46#include "ortools/sat/model.h"
47#include "ortools/sat/sat_parameters.pb.h"
50
51namespace operations_research {
52
53// Classes to solve dimension cumul placement (aka scheduling) problems using
54// linear programming.
55
56// Utility class used in the core optimizer to tighten the cumul bounds as much
57// as possible based on the model precedences.
59 public:
60 explicit CumulBoundsPropagator(const RoutingDimension* dimension);
61
62 // Tightens the cumul bounds starting from the current cumul var min/max,
63 // and propagating the precedences resulting from the next_accessor, and the
64 // dimension's precedence rules.
65 // Returns false iff the precedences are infeasible with the given routes.
66 // Otherwise, the user can call CumulMin() and CumulMax() to retrieve the new
67 // bounds of an index.
69 const std::function<int64_t(int64_t)>& next_accessor,
70 int64_t cumul_offset,
71 const std::vector<RoutingModel::RouteDimensionTravelInfo>*
72 dimension_travel_info_per_route = nullptr);
73
74 int64_t CumulMin(int index) const {
75 return propagated_bounds_[PositiveNode(index)];
76 }
77
78 int64_t CumulMax(int index) const {
79 const int64_t negated_upper_bound = propagated_bounds_[NegativeNode(index)];
80 return negated_upper_bound == std::numeric_limits<int64_t>::min()
81 ? std::numeric_limits<int64_t>::max()
82 : -negated_upper_bound;
83 }
84
85 const RoutingDimension& dimension() const { return dimension_; }
86
87 private:
88 // An arc "tail --offset--> head" represents the relation
89 // tail + offset <= head.
90 // As arcs are stored by tail, we don't store it in the struct.
91 struct ArcInfo {
92 int head;
93 int64_t offset;
94 };
95 static const int kNoParent;
96 static const int kParentToBePropagated;
97
98 // Return the node corresponding to the lower bound of the cumul of index and
99 // -index respectively.
100 int PositiveNode(int index) const { return 2 * index; }
101 int NegativeNode(int index) const { return 2 * index + 1; }
102
103 void AddNodeToQueue(int node) {
104 if (!node_in_queue_[node]) {
105 bf_queue_.push_back(node);
106 node_in_queue_[node] = true;
107 }
108 }
109
110 // Adds the relation first_index + offset <= second_index, by adding arcs
111 // first_index --offset--> second_index and
112 // -second_index --offset--> -first_index.
113 void AddArcs(int first_index, int second_index, int64_t offset);
114
115 bool InitializeArcsAndBounds(
116 const std::function<int64_t(int64_t)>& next_accessor,
117 int64_t cumul_offset,
118 const std::vector<RoutingModel::RouteDimensionTravelInfo>*
119 dimension_travel_info_per_route = nullptr);
120
121 bool UpdateCurrentLowerBoundOfNode(int node, int64_t new_lb, int64_t offset);
122
123 bool DisassembleSubtree(int source, int target);
124
125 bool CleanupAndReturnFalse() {
126 // We clean-up node_in_queue_ for future calls, and return false.
127 for (int node_to_cleanup : bf_queue_) {
128 node_in_queue_[node_to_cleanup] = false;
129 }
130 bf_queue_.clear();
131 return false;
132 }
133
134 const RoutingDimension& dimension_;
135 const int64_t num_nodes_;
136
137 // TODO(user): Investigate if all arcs for a given tail can be created
138 // at the same time, in which case outgoing_arcs_ could point to an absl::Span
139 // for each tail index.
140 std::vector<std::vector<ArcInfo>> outgoing_arcs_;
141
142 std::deque<int> bf_queue_;
143 std::vector<bool> node_in_queue_;
144 std::vector<int> tree_parent_node_of_;
145 // After calling PropagateCumulBounds(), for each node index n,
146 // propagated_bounds_[2*n] and -propagated_bounds_[2*n+1] respectively contain
147 // the propagated lower and upper bounds of n's cumul variable.
148 std::vector<int64_t> propagated_bounds_;
149
150 // Vector used in DisassembleSubtree() to avoid memory reallocation.
151 std::vector<int> tmp_dfs_stack_;
152
153 // Used to store the pickup/delivery pairs encountered on the routes.
154 std::vector<std::pair<int64_t, int64_t>>
155 visited_pickup_delivery_indices_for_pair_;
156};
157
159 // An optimal solution was found respecting all constraints.
161 // An optimal solution was found, however constraints which were relaxed were
162 // violated.
164 // Only a feasible solution was found, optimality was not proven.
166 // A solution could not be found.
168};
169
171 public:
172 static const int kNoConstraint = -1;
173
174 virtual ~RoutingLinearSolverWrapper() = default;
175 virtual void Clear() = 0;
176 virtual int CreateNewPositiveVariable() = 0;
177 virtual void SetVariableName(int index, absl::string_view name) = 0;
178 virtual bool SetVariableBounds(int index, int64_t lower_bound,
179 int64_t upper_bound) = 0;
180 virtual void SetVariableDisjointBounds(int index,
181 const std::vector<int64_t>& starts,
182 const std::vector<int64_t>& ends) = 0;
183 virtual int64_t GetVariableLowerBound(int index) const = 0;
184 virtual int64_t GetVariableUpperBound(int index) const = 0;
185 virtual void SetObjectiveCoefficient(int index, double coefficient) = 0;
186 virtual double GetObjectiveCoefficient(int index) const = 0;
187 virtual void ClearObjective() = 0;
188 virtual int NumVariables() const = 0;
189 virtual int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) = 0;
190 virtual void SetCoefficient(int ct, int index, double coefficient) = 0;
191 virtual bool IsCPSATSolver() = 0;
192 virtual void AddObjectiveConstraint() = 0;
193 virtual void AddMaximumConstraint(int max_var, std::vector<int> vars) = 0;
194 virtual void AddProductConstraint(int product_var, std::vector<int> vars) = 0;
195 virtual void SetEnforcementLiteral(int ct, int condition) = 0;
196 virtual DimensionSchedulingStatus Solve(absl::Duration duration_limit) = 0;
197 virtual int64_t GetObjectiveValue() const = 0;
198 virtual double GetValue(int index) const = 0;
199 virtual bool SolutionIsInteger() const = 0;
200
201 // This function is meant to override the parameters of the solver.
202 virtual void SetParameters(const std::string& parameters) = 0;
203 // When solving a scheduling problem, this can be called to add hints that
204 // help the underlying solver:
205 // - nodes is the sequence of nodes in a route represented in the model.
206 // - schedule_variables is the sequence of variables used to represent the
207 // time at which each node is scheduled.
208 virtual void AddRoute(absl::Span<const int64_t> nodes,
209 absl::Span<const int> schedule_variables) = 0;
210
211 // Returns if the model is empty or not.
212 virtual bool ModelIsEmpty() const { return true; }
213
214 // Prints an understandable view of the model.
215 virtual std::string PrintModel() const = 0;
216
217 // Adds a variable with bounds [lower_bound, upper_bound].
218 int AddVariable(int64_t lower_bound, int64_t upper_bound) {
219 CHECK_LE(lower_bound, upper_bound);
220 const int variable = CreateNewPositiveVariable();
221 SetVariableBounds(variable, lower_bound, upper_bound);
222 return variable;
223 }
224 // Adds a linear constraint, enforcing
225 // lower_bound <= sum variable * coeff <= upper_bound,
226 // and returns the identifier of that constraint.
228 int64_t lower_bound, int64_t upper_bound,
229 absl::Span<const std::pair<int, double>> variable_coeffs) {
230 CHECK_LE(lower_bound, upper_bound);
231 const int ct = CreateNewConstraint(lower_bound, upper_bound);
232 for (const auto& variable_coeff : variable_coeffs) {
233 SetCoefficient(ct, variable_coeff.first, variable_coeff.second);
234 }
235 return ct;
236 }
237 // Adds a linear constraint and a 0/1 variable that is true iff
238 // lower_bound <= sum variable * coeff <= upper_bound,
239 // and returns the identifier of that variable.
241 int64_t lower_bound, int64_t upper_bound,
242 absl::Span<const std::pair<int, double>> weighted_variables) {
243 const int reification_ct = AddLinearConstraint(1, 1, {});
244 if (std::numeric_limits<int64_t>::min() < lower_bound) {
245 const int under_lower_bound = AddVariable(0, 1);
246#ifndef NDEBUG
247 SetVariableName(under_lower_bound, "under_lower_bound");
248#endif
249 SetCoefficient(reification_ct, under_lower_bound, 1);
250 const int under_lower_bound_ct =
251 AddLinearConstraint(std::numeric_limits<int64_t>::min(),
252 lower_bound - 1, weighted_variables);
253 SetEnforcementLiteral(under_lower_bound_ct, under_lower_bound);
254 }
255 if (upper_bound < std::numeric_limits<int64_t>::max()) {
256 const int above_upper_bound = AddVariable(0, 1);
257#ifndef NDEBUG
258 SetVariableName(above_upper_bound, "above_upper_bound");
259#endif
260 SetCoefficient(reification_ct, above_upper_bound, 1);
261 const int above_upper_bound_ct = AddLinearConstraint(
262 upper_bound + 1, std::numeric_limits<int64_t>::max(),
263 weighted_variables);
264 SetEnforcementLiteral(above_upper_bound_ct, above_upper_bound);
265 }
266 const int within_bounds = AddVariable(0, 1);
267#ifndef NDEBUG
268 SetVariableName(within_bounds, "within_bounds");
269#endif
270 SetCoefficient(reification_ct, within_bounds, 1);
271 const int within_bounds_ct =
272 AddLinearConstraint(lower_bound, upper_bound, weighted_variables);
273 SetEnforcementLiteral(within_bounds_ct, within_bounds);
274 return within_bounds;
275 }
276};
277
279 public:
280 RoutingGlopWrapper(bool is_relaxation, const glop::GlopParameters& parameters)
281 : is_relaxation_(is_relaxation) {
282 lp_solver_.SetParameters(parameters);
283 linear_program_.SetMaximizationProblem(false);
284 }
285 void Clear() override {
286 linear_program_.Clear();
287 linear_program_.SetMaximizationProblem(false);
288 allowed_intervals_.clear();
289 }
291 return linear_program_.CreateNewVariable().value();
292 }
293 void SetVariableName(int index, absl::string_view name) override {
294 linear_program_.SetVariableName(glop::ColIndex(index), name);
295 }
296 bool SetVariableBounds(int index, int64_t lower_bound,
297 int64_t upper_bound) override {
298 DCHECK_GE(lower_bound, 0);
299 // When variable upper bounds are greater than this threshold, precision
300 // issues arise in GLOP. In this case we are just going to suppose that
301 // these high bound values are infinite and not set the upper bound.
302 const int64_t kMaxValue = 1e10;
303 const double lp_min = lower_bound;
304 const double lp_max =
305 (upper_bound > kMaxValue) ? glop::kInfinity : upper_bound;
306 if (lp_min <= lp_max) {
307 linear_program_.SetVariableBounds(glop::ColIndex(index), lp_min, lp_max);
308 return true;
309 }
310 // The linear_program would not be feasible, and it cannot handle the
311 // lp_min > lp_max case, so we must detect infeasibility here.
312 return false;
313 }
314 void SetVariableDisjointBounds(int index, const std::vector<int64_t>& starts,
315 const std::vector<int64_t>& ends) override {
316 // TODO(user): Investigate if we can avoid rebuilding the interval list
317 // each time (we could keep a reference to the forbidden interval list in
318 // RoutingDimension but we would need to store cumul offsets and use them
319 // when checking intervals).
320 allowed_intervals_[index] =
321 std::make_unique<SortedDisjointIntervalList>(starts, ends);
322 }
323 int64_t GetVariableLowerBound(int index) const override {
324 return linear_program_.variable_lower_bounds()[glop::ColIndex(index)];
325 }
326 int64_t GetVariableUpperBound(int index) const override {
327 const double upper_bound =
328 linear_program_.variable_upper_bounds()[glop::ColIndex(index)];
329 DCHECK_GE(upper_bound, 0);
330 return upper_bound == glop::kInfinity ? std::numeric_limits<int64_t>::max()
331 : static_cast<int64_t>(upper_bound);
332 }
333 void SetObjectiveCoefficient(int index, double coefficient) override {
334 linear_program_.SetObjectiveCoefficient(glop::ColIndex(index), coefficient);
335 }
336 double GetObjectiveCoefficient(int index) const override {
337 return linear_program_.objective_coefficients()[glop::ColIndex(index)];
338 }
339 void ClearObjective() override {
340 for (glop::ColIndex i(0); i < linear_program_.num_variables(); ++i) {
341 linear_program_.SetObjectiveCoefficient(i, 0);
342 }
343 }
344 int NumVariables() const override {
345 return linear_program_.num_variables().value();
346 }
347 int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) override {
348 const glop::RowIndex ct = linear_program_.CreateNewConstraint();
349 linear_program_.SetConstraintBounds(
350 ct,
351 (lower_bound == std::numeric_limits<int64_t>::min()) ? -glop::kInfinity
352 : lower_bound,
353 (upper_bound == std::numeric_limits<int64_t>::max()) ? glop::kInfinity
354 : upper_bound);
355 return ct.value();
356 }
357 void SetCoefficient(int ct, int index, double coefficient) override {
358 // Necessary to keep the model clean
359 // (cf. glop::LinearProgram::NotifyThatColumnsAreClean).
360 if (coefficient == 0.0) return;
361 linear_program_.SetCoefficient(glop::RowIndex(ct), glop::ColIndex(index),
362 coefficient);
363 }
364 bool IsCPSATSolver() override { return false; }
365 void AddObjectiveConstraint() override {
366 double max_coefficient = 0;
367 for (int variable = 0; variable < NumVariables(); variable++) {
368 const double coefficient = GetObjectiveCoefficient(variable);
369 max_coefficient = std::max(MathUtil::Abs(coefficient), max_coefficient);
370 }
371 DCHECK_GE(max_coefficient, 0);
372 if (max_coefficient == 0) {
373 // There are no terms in the objective.
374 return;
375 }
376 const glop::RowIndex ct = linear_program_.CreateNewConstraint();
377 double normalized_objective_value = 0;
378 for (int variable = 0; variable < NumVariables(); variable++) {
379 const double coefficient = GetObjectiveCoefficient(variable);
380 if (coefficient != 0) {
381 const double normalized_coeff = coefficient / max_coefficient;
382 SetCoefficient(ct.value(), variable, normalized_coeff);
383 normalized_objective_value += normalized_coeff * GetValue(variable);
384 }
385 }
386 normalized_objective_value = std::max(
387 normalized_objective_value, GetObjectiveValue() / max_coefficient);
388 linear_program_.SetConstraintBounds(ct, -glop::kInfinity,
389 normalized_objective_value);
390 }
391 void AddMaximumConstraint(int /*max_var*/,
392 std::vector<int> /*vars*/) override {}
393 void AddProductConstraint(int /*product_var*/,
394 std::vector<int> /*vars*/) override {}
395 void SetEnforcementLiteral(int /*ct*/, int /*condition*/) override {};
396 void AddRoute(absl::Span<const int64_t>, absl::Span<const int>) override{};
397 DimensionSchedulingStatus Solve(absl::Duration duration_limit) override {
398 lp_solver_.GetMutableParameters()->set_max_time_in_seconds(
399 absl::ToDoubleSeconds(duration_limit));
400
401 // Because we construct the lp one constraint at a time and we never call
402 // SetCoefficient() on the same variable twice for a constraint, we know
403 // that the columns do not contain duplicates and are already ordered by
404 // constraint so we do not need to call linear_program->CleanUp() which can
405 // be costly. Note that the assumptions are DCHECKed() in the call below.
406 linear_program_.NotifyThatColumnsAreClean();
407 VLOG(2) << linear_program_.Dump();
408 const glop::ProblemStatus status = lp_solver_.Solve(linear_program_);
409 const bool feasible_only = status == glop::ProblemStatus::PRIMAL_FEASIBLE;
410 if (status != glop::ProblemStatus::OPTIMAL &&
411 status != glop::ProblemStatus::IMPRECISE && !feasible_only) {
413 }
414 if (is_relaxation_) {
416 }
417 for (const auto& allowed_interval : allowed_intervals_) {
418 const double value_double = GetValue(allowed_interval.first);
419 const int64_t value =
420 (value_double >= std::numeric_limits<int64_t>::max())
421 ? std::numeric_limits<int64_t>::max()
422 : MathUtil::FastInt64Round(value_double);
423 const SortedDisjointIntervalList* const interval_list =
424 allowed_interval.second.get();
425 const auto it = interval_list->FirstIntervalGreaterOrEqual(value);
426 if (it == interval_list->end() || value < it->start) {
428 }
429 }
430 if (feasible_only && !linear_program_.objective_coefficients().empty()) {
432 }
434 }
435 int64_t GetObjectiveValue() const override {
436 return MathUtil::FastInt64Round(lp_solver_.GetObjectiveValue());
437 }
438 double GetValue(int index) const override {
439 return lp_solver_.variable_values()[glop::ColIndex(index)];
440 }
441 bool SolutionIsInteger() const override {
442 return linear_program_.SolutionIsInteger(lp_solver_.variable_values(),
443 /*absolute_tolerance*/ 1e-3);
444 }
445
446 void SetParameters(const std::string& parameters) override {
447 glop::GlopParameters params;
448 const bool status = params.ParseFromString(parameters);
449 DCHECK(status);
450 lp_solver_.SetParameters(params);
451 }
452
453 // Prints an understandable view of the model
454 // TODO(user): Improve output readability.
455 std::string PrintModel() const override { return linear_program_.Dump(); }
456
457 private:
458 const bool is_relaxation_;
459 glop::LinearProgram linear_program_;
460 glop::LPSolver lp_solver_;
461 absl::flat_hash_map<int, std::unique_ptr<SortedDisjointIntervalList>>
462 allowed_intervals_;
463};
464
466 public:
468 parameters_.set_num_search_workers(1);
469 // Keeping presolve but with 1 iteration; as of 10/2023 it is
470 // significantly faster than both full presolve and no presolve.
471 parameters_.set_cp_model_presolve(true);
472 parameters_.set_max_presolve_iterations(1);
473 parameters_.set_cp_model_probing_level(0);
474 parameters_.set_use_sat_inprocessing(false);
475 parameters_.set_symmetry_level(0);
476 parameters_.set_catch_sigint_signal(false);
477 parameters_.set_mip_max_bound(1e8);
478 parameters_.set_search_branching(sat::SatParameters::PORTFOLIO_SEARCH);
479 parameters_.set_linearization_level(2);
480 parameters_.set_cut_level(0);
481 parameters_.set_use_absl_random(false);
482 }
484 void Clear() override {
485 model_.Clear();
486 response_.Clear();
487 objective_coefficients_.clear();
488 schedule_variables_.clear();
489 }
491 const int index = model_.variables_size();
492 sat::IntegerVariableProto* const variable = model_.add_variables();
493 variable->add_domain(0);
494 variable->add_domain(static_cast<int64_t>(parameters_.mip_max_bound()));
495 return index;
496 }
497 void SetVariableName(int index, absl::string_view name) override {
498 model_.mutable_variables(index)->set_name(name.data());
499 }
500 bool SetVariableBounds(int index, int64_t lower_bound,
501 int64_t upper_bound) override {
502 DCHECK_GE(lower_bound, 0);
503 const int64_t capped_upper_bound =
504 std::min<int64_t>(upper_bound, parameters_.mip_max_bound());
505 if (lower_bound > capped_upper_bound) return false;
506 sat::IntegerVariableProto* const variable = model_.mutable_variables(index);
507 variable->set_domain(0, lower_bound);
508 variable->set_domain(1, capped_upper_bound);
509 return true;
510 }
511 void SetVariableDisjointBounds(int index, const std::vector<int64_t>& starts,
512 const std::vector<int64_t>& ends) override {
513 DCHECK_EQ(starts.size(), ends.size());
514 const int ct = CreateNewConstraint(1, 1);
515 for (int i = 0; i < starts.size(); ++i) {
516 const int variable = CreateNewPositiveVariable();
517#ifndef NDEBUG
518 SetVariableName(variable,
519 absl::StrFormat("disjoint(%ld, %ld)", index, i));
520#endif
521 SetVariableBounds(variable, 0, 1);
522 SetCoefficient(ct, variable, 1);
523 const int window_ct = CreateNewConstraint(starts[i], ends[i]);
524 SetCoefficient(window_ct, index, 1);
525 model_.mutable_constraints(window_ct)->add_enforcement_literal(variable);
526 }
527 }
528 int64_t GetVariableLowerBound(int index) const override {
529 return model_.variables(index).domain(0);
530 }
531 int64_t GetVariableUpperBound(int index) const override {
532 const auto& domain = model_.variables(index).domain();
533 return domain[domain.size() - 1];
534 }
535 void SetObjectiveCoefficient(int index, double coefficient) override {
536 if (index >= objective_coefficients_.size()) {
537 objective_coefficients_.resize(index + 1, 0);
538 }
539 objective_coefficients_[index] = coefficient;
540 sat::FloatObjectiveProto* const objective =
541 model_.mutable_floating_point_objective();
542 objective->add_vars(index);
543 objective->add_coeffs(coefficient);
544 }
545 double GetObjectiveCoefficient(int index) const override {
546 return (index < objective_coefficients_.size())
547 ? objective_coefficients_[index]
548 : 0;
549 }
550 void ClearObjective() override {
551 model_.mutable_floating_point_objective()->Clear();
552 }
553 int NumVariables() const override { return model_.variables_size(); }
554 int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) override {
555 sat::LinearConstraintProto* const ct =
556 model_.add_constraints()->mutable_linear();
557 ct->add_domain(lower_bound);
558 ct->add_domain(upper_bound);
559 return model_.constraints_size() - 1;
560 }
561 void SetCoefficient(int ct_index, int index, double coefficient) override {
562 sat::LinearConstraintProto* const ct =
563 model_.mutable_constraints(ct_index)->mutable_linear();
564 ct->add_vars(index);
565 const int64_t integer_coefficient = coefficient;
566 ct->add_coeffs(integer_coefficient);
567 }
568 bool IsCPSATSolver() override { return true; }
569 void AddObjectiveConstraint() override {
570 const sat::CpObjectiveProto& objective = response_.integer_objective();
571 int64_t activity = 0;
572 for (int i = 0; i < objective.vars_size(); ++i) {
573 activity += response_.solution(objective.vars(i)) * objective.coeffs(i);
574 }
575 const int ct =
576 CreateNewConstraint(std::numeric_limits<int64_t>::min(), activity);
577 for (int i = 0; i < objective.vars_size(); ++i) {
578 SetCoefficient(ct, objective.vars(i), objective.coeffs(i));
579 }
580 model_.clear_objective();
581 }
582 void AddMaximumConstraint(int max_var, std::vector<int> vars) override {
583 sat::LinearArgumentProto* const ct =
584 model_.add_constraints()->mutable_lin_max();
585 ct->mutable_target()->add_vars(max_var);
586 ct->mutable_target()->add_coeffs(1);
587 for (const int var : vars) {
588 sat::LinearExpressionProto* const expr = ct->add_exprs();
589 expr->add_vars(var);
590 expr->add_coeffs(1);
591 }
592 }
593 void AddProductConstraint(int product_var, std::vector<int> vars) override {
594 sat::LinearArgumentProto* const ct =
595 model_.add_constraints()->mutable_int_prod();
596 ct->mutable_target()->add_vars(product_var);
597 ct->mutable_target()->add_coeffs(1);
598 for (const int var : vars) {
599 sat::LinearExpressionProto* expr = ct->add_exprs();
600 expr->add_vars(var);
601 expr->add_coeffs(1);
602 }
603 }
604 void SetEnforcementLiteral(int ct, int condition) override {
605 DCHECK_LT(ct, model_.constraints_size());
606 model_.mutable_constraints(ct)->add_enforcement_literal(condition);
607 }
608 void AddRoute(absl::Span<const int64_t> nodes,
609 absl::Span<const int> schedule_variables) override {
610 DCHECK_EQ(nodes.size(), schedule_variables.size());
611 for (const int64_t node : nodes) {
612 if (node >= schedule_hint_.size()) schedule_hint_.resize(node + 1, 0);
613 }
614 for (int n = 0; n < nodes.size(); ++n) {
615 schedule_variables_.push_back(
616 {.node = nodes[n], .cumul = schedule_variables[n]});
617 }
618 }
619 DimensionSchedulingStatus Solve(absl::Duration duration_limit) override {
620 const double max_time = absl::ToDoubleSeconds(duration_limit);
621 if (max_time <= 0.0) return DimensionSchedulingStatus::INFEASIBLE;
622 parameters_.set_max_time_in_seconds(max_time);
623 VLOG(2) << ProtobufDebugString(model_);
624 auto record_hint = [this]() {
625 hint_.Clear();
626 for (int i = 0; i < response_.solution_size(); ++i) {
627 hint_.add_vars(i);
628 hint_.add_values(response_.solution(i));
629 }
630 for (const auto& [node, cumul] : schedule_variables_) {
631 schedule_hint_[node] = response_.solution(cumul);
632 }
633 };
634 model_.clear_solution_hint();
635 auto* hint = model_.mutable_solution_hint();
636 if (hint_.vars_size() == model_.variables_size()) {
637 *hint = hint_;
638 } else {
639 for (const auto& [node, cumul] : schedule_variables_) {
640 if (schedule_hint_[node] == 0) continue;
641 hint->add_vars(cumul);
642 hint->add_values(schedule_hint_[node]);
643 }
644 }
645 sat::Model model;
646 model.Add(sat::NewSatParameters(parameters_));
647 response_ = sat::SolveCpModel(model_, &model);
648 VLOG(2) << response_;
649 DCHECK_NE(response_.status(), sat::CpSolverStatus::MODEL_INVALID);
650 if (response_.status() == sat::CpSolverStatus::OPTIMAL ||
651 (response_.status() == sat::CpSolverStatus::FEASIBLE &&
652 !model_.has_floating_point_objective())) {
653 record_hint();
655 } else if (response_.status() == sat::CpSolverStatus::FEASIBLE) {
656 // TODO(user): Consider storing "feasible" solutions in a separate
657 // cache we use as hint when the "optimal" cache is empty.
659 }
661 }
662 int64_t GetObjectiveValue() const override {
663 return MathUtil::FastInt64Round(response_.objective_value());
664 }
665 double GetValue(int index) const override {
666 return response_.solution(index);
667 }
668 bool SolutionIsInteger() const override { return true; }
669
670 // NOTE: This function is not implemented for the CP-SAT solver.
671 void SetParameters(const std::string& /*parameters*/) override {
672 DCHECK(false);
673 }
674
675 bool ModelIsEmpty() const override { return model_.ByteSizeLong() == 0; }
676
677 // Prints an understandable view of the model
678 std::string PrintModel() const override;
679
680 private:
681 sat::CpModelProto model_;
682 sat::CpSolverResponse response_;
683 sat::SatParameters parameters_;
684 std::vector<double> objective_coefficients_;
685 sat::PartialVariableAssignment hint_;
686 struct NodeAndCumul {
687 int64_t node;
688 int cumul;
689 };
690 // Stores node/cumul pairs of the routes in the current model.
691 std::vector<NodeAndCumul> schedule_variables_;
692 // Maps node to its last known value in any optimal solution.
693 std::vector<int64_t> schedule_hint_;
694};
695
696// Utility class used in Local/GlobalDimensionCumulOptimizer to set the linear
697// solver constraints and solve the problem.
699 using RouteDimensionTravelInfo = RoutingModel::RouteDimensionTravelInfo;
700 using Resource = RoutingModel::ResourceGroup::Resource;
701
702 public:
703 DimensionCumulOptimizerCore(const RoutingDimension* dimension,
704 bool use_precedence_propagator);
705
706 // Finds an optimal (or just feasible) solution for the route for the given
707 // resource. If the resource is null, it is simply ignored.
709 int vehicle, double solve_duration_ratio,
710 const std::function<int64_t(int64_t)>& next_accessor,
711 const RouteDimensionTravelInfo* dimension_travel_info,
712 const Resource* resource, bool optimize_vehicle_costs,
713 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
714 std::vector<int64_t>* break_values, int64_t* cost_without_transit,
715 int64_t* transit_cost, bool clear_lp = true);
716
717 // Given some cumuls and breaks, computes the solution cost by solving the
718 // same model as in OptimizeSingleRouteWithResource() with the addition of
719 // constraints for cumuls and breaks.
721 int vehicle, double solve_duration_ratio,
722 const std::function<int64_t(int64_t)>& next_accessor,
723 const RouteDimensionTravelInfo* dimension_travel_info,
725 absl::Span<const int64_t> solution_cumul_values,
726 absl::Span<const int64_t> solution_break_values,
727 int64_t* cost_without_transits, int64_t* cost_offset = nullptr,
728 bool reuse_previous_model_if_possible = true, bool clear_lp = false,
729 bool clear_solution_constraints = true,
730 absl::Duration* solve_duration = nullptr);
731
732 // Computes the optimal scheduling solution(s) for the route for each resource
733 // in 'resources' with an index in 'resource_indices'.
734 // If both 'resources' and 'resource_indices' are empty, computes the optimal
735 // solution for the route itself (without added resource constraints).
736 std::vector<DimensionSchedulingStatus> OptimizeSingleRouteWithResources(
737 int vehicle, double solve_duration_ratio,
738 const std::function<int64_t(int64_t)>& next_accessor,
739 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
740 const RouteDimensionTravelInfo* dimension_travel_info,
741 absl::Span<const Resource> resources,
742 absl::Span<const int> resource_indices, bool optimize_vehicle_costs,
744 std::vector<std::vector<int64_t>>* cumul_values,
745 std::vector<std::vector<int64_t>>* break_values,
746 std::vector<int64_t>* costs_without_transits, int64_t* transit_cost,
747 bool clear_lp = true);
748
749 // In the Optimize() method, if both 'cumul_values' and 'cost' parameters are
750 // null, we don't optimize the cost and stop at the first feasible solution in
751 // the linear solver (since in this case only feasibility is of interest).
752 // When 'optimize_resource_assignment' is false, the resource var values are
753 // used to constrain the vehicle routes according to their assigned resource.
755 const std::function<int64_t(int64_t)>& next_accessor,
756 const std::vector<RouteDimensionTravelInfo>&
757 dimension_travel_info_per_route,
758 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
759 std::vector<int64_t>* break_values,
760 std::vector<std::vector<int>>* resource_indices_per_group,
761 int64_t* cost_without_transits, int64_t* transit_cost,
762 bool clear_lp = true, bool optimize_resource_assignment = true);
763
765 const std::function<int64_t(int64_t)>& next_accessor,
766 const std::vector<RouteDimensionTravelInfo>&
767 dimension_travel_info_per_route,
768 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
769 std::vector<int64_t>* break_values);
770
772 int vehicle, double solve_duration_ratio,
773 const std::function<int64_t(int64_t)>& next_accessor,
774 const RouteDimensionTravelInfo* dimension_travel_info,
775 const Resource* resource, RoutingLinearSolverWrapper* solver,
776 std::vector<int64_t>* cumul_values, std::vector<int64_t>* break_values);
777
778 const RoutingDimension* dimension() const { return dimension_; }
779
780 private:
781 // Initializes the containers and given solver. Must be called prior to
782 // setting any constraints and solving.
783 void InitOptimizer(RoutingLinearSolverWrapper* solver);
784
785 // Computes the minimum/maximum of cumuls for nodes on "route", and sets them
786 // in current_route_[min|max]_cumuls_ respectively.
787 bool ExtractRouteCumulBounds(absl::Span<const int64_t> route,
788 int64_t cumul_offset);
789
790 // Tighten the minimum/maximum of cumuls for nodes on "route"
791 // If the propagator_ is not null, uses the bounds tightened by the
792 // propagator. Otherwise, the minimum transits are used to tighten them.
793 bool TightenRouteCumulBounds(absl::Span<const int64_t> route,
794 absl::Span<const int64_t> min_transits,
795 int64_t cumul_offset);
796
797 // Sets the constraints for all nodes on "vehicle"'s route according to
798 // "next_accessor". If optimize_costs is true, also sets the objective
799 // coefficients for the LP.
800 // Returns false if some infeasibility was detected, true otherwise.
801 bool SetRouteCumulConstraints(
802 int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
803 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
804 const RouteDimensionTravelInfo* dimension_travel_info,
805 int64_t cumul_offset, bool optimize_costs,
806 RoutingLinearSolverWrapper* solver, int64_t* route_transit_cost,
807 int64_t* route_cost_offset);
808
809 // Sets the constraints for all variables related to travel. Handles
810 // static or time-dependent travel values.
811 // Returns false if some infeasibility was detected, true otherwise.
812 bool SetRouteTravelConstraints(
813 const RouteDimensionTravelInfo* dimension_travel_info,
814 absl::Span<const int> lp_slacks, absl::Span<const int64_t> fixed_transit,
816
817 // Sets the global constraints on the dimension, and adds global objective
818 // cost coefficients if optimize_costs is true.
819 // NOTE: When called, the call to this function MUST come after
820 // SetRouteCumulConstraints() has been called on all routes, so that
821 // index_to_cumul_variable_ and min_start/max_end_cumul_ are correctly
822 // initialized.
823 // Returns false if some infeasibility was detected, true otherwise.
824 bool SetGlobalConstraints(
825 const std::function<int64_t(int64_t)>& next_accessor,
826 int64_t cumul_offset, bool optimize_costs,
827 bool optimize_resource_assignment, RoutingLinearSolverWrapper* solver);
828
829 bool SetGlobalConstraintsForResourceAssignment(
830 const std::function<int64_t(int64_t)>& next_accessor,
831 int64_t cumul_offset, RoutingLinearSolverWrapper* solver);
832
833 void SetValuesFromLP(absl::Span<const int> lp_variables, int64_t offset,
835 std::vector<int64_t>* lp_values) const;
836
837 void SetResourceIndices(
839 std::vector<std::vector<int>>* resource_indices_per_group) const;
840
841 // This function packs the routes of the given vehicles while keeping the cost
842 // of the LP lower than its current (supposed optimal) objective value.
843 // It does so by setting the current objective variables' coefficient to 0 and
844 // setting the coefficient of the route ends to 1, to first minimize the route
845 // ends' cumuls, and then maximizes the starts' cumuls without increasing the
846 // ends.
847 DimensionSchedulingStatus PackRoutes(
848 std::vector<int> vehicles, double solve_duration_ratio,
850 const glop::GlopParameters& packing_parameters);
851
852 std::unique_ptr<CumulBoundsPropagator> propagator_;
853 std::vector<int64_t> current_route_min_cumuls_;
854 std::vector<int64_t> current_route_max_cumuls_;
855 const RoutingDimension* const dimension_;
856 // Scheduler variables for current route cumuls and for all nodes cumuls.
857 std::vector<int> current_route_cumul_variables_;
858 std::vector<int> index_to_cumul_variable_;
859 // Scheduler variables for current route breaks and all vehicle breaks.
860 // There are two variables for each break: start and end.
861 // current_route_break_variables_ has variables corresponding to
862 // break[0] start, break[0] end, break[1] start, break[1] end, etc.
863 std::vector<int> current_route_break_variables_;
864 // Vector all_break_variables contains the break variables of all vehicles,
865 // in the same format as current_route_break_variables.
866 // It is the concatenation of break variables of vehicles in [0, #vehicles).
867 std::vector<int> all_break_variables_;
868 // Allows to retrieve break variables of a given vehicle: those go from
869 // all_break_variables_[vehicle_to_all_break_variables_offset_[vehicle]] to
870 // all_break_variables[vehicle_to_all_break_variables_offset_[vehicle+1]-1].
871 std::vector<int> vehicle_to_all_break_variables_offset_;
872 // The following vector contains indices of resource-class-to-vehicle
873 // assignment variables. For every resource group, stores indices of
874 // num_resource_classes*num_vehicles boolean variables indicating whether
875 // resource class #rc is assigned to vehicle #v.
876 std::vector<std::vector<int>>
877 resource_class_to_vehicle_assignment_variables_per_group_;
878 // The following vector keeps track of the resources ignored during resource
879 // assignment because they're pre-assigned to a specific vehicle.
880 std::vector<std::vector<absl::flat_hash_set<int>>>
881 resource_class_ignored_resources_per_group_;
882
883 int max_end_cumul_;
884 int min_start_cumul_;
885 std::vector<std::pair<int64_t, int64_t>>
886 visited_pickup_delivery_indices_for_pair_;
887};
888
889// Class used to compute optimal values for dimension cumuls of routes,
890// minimizing cumul soft lower and upper bound costs, and vehicle span costs of
891// a route.
892// In its methods, next_accessor is a callback returning the next node of a
893// given node on a route.
895 public:
897 const RoutingDimension* dimension,
898 RoutingSearchParameters::SchedulingSolver solver_type);
899
900 // If feasible, computes the optimal cost of the route performed by a vehicle,
901 // minimizing cumul soft lower and upper bound costs and vehicle span costs,
902 // and stores it in "optimal_cost" (if not null).
903 // Returns true iff the route respects all constraints.
905 int vehicle, double solve_duration_ratio,
906 const std::function<int64_t(int64_t)>& next_accessor,
907 int64_t* optimal_cost);
908
909 // Same as ComputeRouteCumulCost, but the cost computed does not contain
910 // the part of the vehicle span cost due to fixed transits.
912 int vehicle, double solve_duration_ratio,
913 const std::function<int64_t(int64_t)>& next_accessor,
914 const RoutingModel::ResourceGroup::Resource* resource,
915 int64_t* optimal_cost_without_transits);
916
917 std::vector<DimensionSchedulingStatus>
919 int vehicle, double solve_duration_ratio,
920 const std::function<int64_t(int64_t)>& next_accessor,
921 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
922 absl::Span<const RoutingModel::ResourceGroup::Resource> resources,
923 absl::Span<const int> resource_indices, bool optimize_vehicle_costs,
924 std::vector<int64_t>* optimal_costs_without_transits,
925 std::vector<std::vector<int64_t>>* optimal_cumuls,
926 std::vector<std::vector<int64_t>>* optimal_breaks);
927
928 // If feasible, computes the optimal values for cumul and break variables
929 // of the route performed by a vehicle, minimizing cumul soft lower, upper
930 // bound costs and vehicle span costs, stores them in "optimal_cumuls"
931 // (if not null), and optimal_breaks, and returns true.
932 // Returns false if the route is not feasible.
934 int vehicle, double solve_duration_ratio,
935 const std::function<int64_t(int64_t)>& next_accessor,
936 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
937 const RoutingModel::ResourceGroup::Resource* resource,
938 std::vector<int64_t>* optimal_cumuls,
939 std::vector<int64_t>* optimal_breaks);
940
941 // Simple combination of ComputeRouteCumulCostWithoutFixedTransits() and
942 // ComputeRouteCumuls().
944 int vehicle, double solve_duration_ratio,
945 const std::function<int64_t(int64_t)>& next_accessor,
946 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
947 std::vector<int64_t>* optimal_cumuls,
948 std::vector<int64_t>* optimal_breaks,
949 int64_t* optimal_cost_without_transits);
950
951 // If feasible, computes the cost of a given route performed by a vehicle
952 // defined by its cumuls and breaks.
954 int vehicle, double solve_duration_ratio,
955 const std::function<int64_t(int64_t)>& next_accessor,
956 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
957 absl::Span<const int64_t> solution_cumul_values,
958 absl::Span<const int64_t> solution_break_values, int64_t* solution_cost,
959 int64_t* cost_offset = nullptr,
960 bool reuse_previous_model_if_possible = false, bool clear_lp = true,
961 absl::Duration* solve_duration = nullptr);
962
963 // Similar to ComputeRouteCumuls, but also tries to pack the cumul values on
964 // the route, such that the cost remains the same, the cumul of route end is
965 // minimized, and then the cumul of the start of the route is maximized.
966 // If 'resource' is non-null, the packed route must also respect its start/end
967 // time window.
969 int vehicle, double solve_duration_ratio,
970 const std::function<int64_t(int64_t)>& next_accessor,
971 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
972 const RoutingModel::ResourceGroup::Resource* resource,
973 std::vector<int64_t>* packed_cumuls, std::vector<int64_t>* packed_breaks);
974
975 const RoutingDimension* dimension() const {
976 return optimizer_core_.dimension();
977 }
978
979 private:
980 std::vector<std::unique_ptr<RoutingLinearSolverWrapper>> solver_;
981 DimensionCumulOptimizerCore optimizer_core_;
982};
983
985 public:
987 const RoutingDimension* dimension,
988 RoutingSearchParameters::SchedulingSolver solver_type);
989 // If feasible, computes the optimal cost of the entire model with regards to
990 // the optimizer_core_'s dimension costs, minimizing cumul soft lower/upper
991 // bound costs and vehicle/global span costs, and stores it in "optimal_cost"
992 // (if not null).
993 // Returns true iff all the constraints can be respected.
995 const std::function<int64_t(int64_t)>& next_accessor,
996 int64_t* optimal_cost_without_transits);
997 // If feasible, computes the optimal values for cumul, break and resource
998 // variables, minimizing cumul soft lower/upper bound costs and vehicle/global
999 // span costs, stores them in "optimal_cumuls" (if not null), "optimal_breaks"
1000 // and "optimal_resource_indices_per_group", and returns true.
1001 // Returns false if the routes are not feasible.
1003 const std::function<int64_t(int64_t)>& next_accessor,
1004 const std::vector<RoutingModel::RouteDimensionTravelInfo>&
1005 dimension_travel_info_per_route,
1006 std::vector<int64_t>* optimal_cumuls,
1007 std::vector<int64_t>* optimal_breaks,
1008 std::vector<std::vector<int>>* optimal_resource_indices_per_group);
1009
1010 // Similar to ComputeCumuls, but also tries to pack the cumul values on all
1011 // routes, such that the cost remains the same, the cumuls of route ends are
1012 // minimized, and then the cumuls of the starts of the routes are maximized.
1013 // NOTE: It's assumed that all resource variables (if any) are Bound() when
1014 // calling this method, so each vehicle's resource attributes are set as
1015 // constraint on its route and no resource assignment is required.
1017 const std::function<int64_t(int64_t)>& next_accessor,
1018 const std::vector<RoutingModel::RouteDimensionTravelInfo>&
1019 dimension_travel_info_per_route,
1020 std::vector<int64_t>* packed_cumuls, std::vector<int64_t>* packed_breaks);
1021
1022 const RoutingDimension* dimension() const {
1023 return optimizer_core_.dimension();
1024 }
1025
1026 private:
1027 std::unique_ptr<RoutingLinearSolverWrapper> solver_;
1028 DimensionCumulOptimizerCore optimizer_core_;
1029};
1030
1031// Finds the approximate (*) min-cost (i.e. best) assignment of all vehicles
1032// v ∈ 'vehicles' to resources, i.e. indices in [0..num_resources), where the
1033// costs of assigning a vehicle v to a resource r of class r_c is given by
1034// 'vehicle_to_resource_class_assignment_costs(v)[r_c]', unless the latter is
1035// empty in which case vehicle v does not need a resource.
1036//
1037// Returns the cost of that optimal assignment, or -1 if it's infeasible.
1038// Moreover, if 'resource_indices' != nullptr, it assumes that its size is the
1039// global number of vehicles, and assigns its element #v with the resource r
1040// assigned to v, or -1 if none.
1041//
1042// (*) COST SCALING: When the costs are so large that they could possibly yield
1043// int64_t overflow, this method returns a *lower* bound of the actual optimal
1044// cost, and the assignment output in 'resource_indices' may be suboptimal if
1045// that lower bound isn't tight (but it should be very close).
1046//
1047// COMPLEXITY: in practice, should be roughly
1048// O(num_resource_classes * vehicles.size() + resource_indices->size()).
1050 absl::Span<const int> vehicles,
1051 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1052 std::vector<int>>&
1053 resource_indices_per_class,
1054 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1055 absl::flat_hash_set<int>>&
1056 ignored_resources_per_class,
1057 std::function<const std::vector<int64_t>*(int)>
1058 vehicle_to_resource_class_assignment_costs,
1059 std::vector<int>* resource_indices);
1060
1061// Computes the vehicle-to-resource-class assignment costs for the given vehicle
1062// to all resource classes in the group, and sets these costs in
1063// 'assignment_costs' (if non-null). The latter is cleared and kept empty if the
1064// vehicle 'v' should not have a resource assigned to it.
1065// optimize_vehicle_costs indicates if the costs should be optimized or if
1066// we merely care about feasibility (cost of 0) and infeasibility (cost of -1)
1067// of the assignments.
1068// The cumul and break values corresponding to the assignment of each resource
1069// are also set in cumul_values and break_values, if non-null.
1071 int v, double solve_duration_ratio,
1072 const RoutingModel::ResourceGroup& resource_group,
1073 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1074 absl::flat_hash_set<int>>&
1075 ignored_resources_per_class,
1076 const std::function<int64_t(int64_t)>& next_accessor,
1077 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
1078 bool optimize_vehicle_costs, LocalDimensionCumulOptimizer* lp_optimizer,
1079 LocalDimensionCumulOptimizer* mp_optimizer,
1080 std::vector<int64_t>* assignment_costs,
1081 std::vector<std::vector<int64_t>>* cumul_values,
1082 std::vector<std::vector<int64_t>>* break_values);
1083
1084// Structure to store the slope and y_intercept of a segment of a piecewise
1085// linear function.
1087 double slope;
1089
1090 friend ::std::ostream& operator<<(::std::ostream& os,
1091 const SlopeAndYIntercept& it) {
1092 return os << "{" << it.slope << ", " << it.y_intercept << "}";
1093 }
1094};
1095
1096// Given a FloatSlopePiecewiseLinearFunction, returns a vector of slope and
1097// y-intercept corresponding to each segment. Only the segments in
1098// [index_start, index_end[ will be considered.
1099// TODO(user): Consider making the following two functions methods of
1100// FloatSlopePiecewiseLinearFunction. They're only called in lp_scheduling.cc
1101// and ../tour_optimization/model_test.cc, but they might come in handy.
1102std::vector<SlopeAndYIntercept> PiecewiseLinearFunctionToSlopeAndYIntercept(
1103 const FloatSlopePiecewiseLinearFunction& pwl_function, int index_start = 0,
1104 int index_end = -1);
1105
1106// Converts a vector of SlopeAndYIntercept to a vector of convexity regions.
1107// Convexity regions are defined such that, all segment in a convexity region
1108// form a convex function. The boolean in the vector is set to true if the
1109// segment associated to it starts a new convexity region. Therefore, a convex
1110// function would yield {true, false, false, ...} and a concave function would
1111// yield {true, true, true, ...}.
1112std::vector<bool> SlopeAndYInterceptToConvexityRegions(
1113 absl::Span<const SlopeAndYIntercept> slope_and_y_intercept);
1114
1115} // namespace operations_research
1116
1117#endif // OR_TOOLS_CONSTRAINT_SOLVER_ROUTING_LP_SCHEDULING_H_
CumulBoundsPropagator(const RoutingDimension *dimension)
bool PropagateCumulBounds(const std::function< int64_t(int64_t)> &next_accessor, int64_t cumul_offset, const std::vector< RoutingModel::RouteDimensionTravelInfo > *dimension_travel_info_per_route=nullptr)
const RoutingDimension & dimension() const
DimensionSchedulingStatus Optimize(const std::function< int64_t(int64_t)> &next_accessor, const std::vector< RouteDimensionTravelInfo > &dimension_travel_info_per_route, RoutingLinearSolverWrapper *solver, std::vector< int64_t > *cumul_values, std::vector< int64_t > *break_values, std::vector< std::vector< int > > *resource_indices_per_group, int64_t *cost_without_transits, int64_t *transit_cost, bool clear_lp=true, bool optimize_resource_assignment=true)
DimensionSchedulingStatus ComputeSingleRouteSolutionCostWithoutFixedTransits(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RouteDimensionTravelInfo *dimension_travel_info, RoutingLinearSolverWrapper *solver, absl::Span< const int64_t > solution_cumul_values, absl::Span< const int64_t > solution_break_values, int64_t *cost_without_transits, int64_t *cost_offset=nullptr, bool reuse_previous_model_if_possible=true, bool clear_lp=false, bool clear_solution_constraints=true, absl::Duration *solve_duration=nullptr)
DimensionSchedulingStatus OptimizeAndPack(const std::function< int64_t(int64_t)> &next_accessor, const std::vector< RouteDimensionTravelInfo > &dimension_travel_info_per_route, RoutingLinearSolverWrapper *solver, std::vector< int64_t > *cumul_values, std::vector< int64_t > *break_values)
DimensionCumulOptimizerCore(const RoutingDimension *dimension, bool use_precedence_propagator)
DimensionSchedulingStatus OptimizeSingleRouteWithResource(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RouteDimensionTravelInfo *dimension_travel_info, const Resource *resource, bool optimize_vehicle_costs, RoutingLinearSolverWrapper *solver, std::vector< int64_t > *cumul_values, std::vector< int64_t > *break_values, int64_t *cost_without_transit, int64_t *transit_cost, bool clear_lp=true)
DimensionSchedulingStatus OptimizeAndPackSingleRoute(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RouteDimensionTravelInfo *dimension_travel_info, const Resource *resource, RoutingLinearSolverWrapper *solver, std::vector< int64_t > *cumul_values, std::vector< int64_t > *break_values)
std::vector< DimensionSchedulingStatus > OptimizeSingleRouteWithResources(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const std::function< int64_t(int64_t, int64_t)> &transit_accessor, const RouteDimensionTravelInfo *dimension_travel_info, absl::Span< const Resource > resources, absl::Span< const int > resource_indices, bool optimize_vehicle_costs, RoutingLinearSolverWrapper *solver, std::vector< std::vector< int64_t > > *cumul_values, std::vector< std::vector< int64_t > > *break_values, std::vector< int64_t > *costs_without_transits, int64_t *transit_cost, bool clear_lp=true)
DimensionSchedulingStatus ComputeCumulCostWithoutFixedTransits(const std::function< int64_t(int64_t)> &next_accessor, int64_t *optimal_cost_without_transits)
GlobalDimensionCumulOptimizer(const RoutingDimension *dimension, RoutingSearchParameters::SchedulingSolver solver_type)
GlobalDimensionCumulOptimizer.
DimensionSchedulingStatus ComputeCumuls(const std::function< int64_t(int64_t)> &next_accessor, const std::vector< RoutingModel::RouteDimensionTravelInfo > &dimension_travel_info_per_route, std::vector< int64_t > *optimal_cumuls, std::vector< int64_t > *optimal_breaks, std::vector< std::vector< int > > *optimal_resource_indices_per_group)
DimensionSchedulingStatus ComputePackedCumuls(const std::function< int64_t(int64_t)> &next_accessor, const std::vector< RoutingModel::RouteDimensionTravelInfo > &dimension_travel_info_per_route, std::vector< int64_t > *packed_cumuls, std::vector< int64_t > *packed_breaks)
DimensionSchedulingStatus ComputeRouteSolutionCostWithoutFixedTransits(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RoutingModel::RouteDimensionTravelInfo *dimension_travel_info, absl::Span< const int64_t > solution_cumul_values, absl::Span< const int64_t > solution_break_values, int64_t *solution_cost, int64_t *cost_offset=nullptr, bool reuse_previous_model_if_possible=false, bool clear_lp=true, absl::Duration *solve_duration=nullptr)
DimensionSchedulingStatus ComputePackedRouteCumuls(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RoutingModel::RouteDimensionTravelInfo *dimension_travel_info, const RoutingModel::ResourceGroup::Resource *resource, std::vector< int64_t > *packed_cumuls, std::vector< int64_t > *packed_breaks)
LocalDimensionCumulOptimizer(const RoutingDimension *dimension, RoutingSearchParameters::SchedulingSolver solver_type)
LocalDimensionCumulOptimizer.
DimensionSchedulingStatus ComputeRouteCumuls(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RoutingModel::RouteDimensionTravelInfo *dimension_travel_info, const RoutingModel::ResourceGroup::Resource *resource, std::vector< int64_t > *optimal_cumuls, std::vector< int64_t > *optimal_breaks)
DimensionSchedulingStatus ComputeRouteCumulCostWithoutFixedTransits(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RoutingModel::ResourceGroup::Resource *resource, int64_t *optimal_cost_without_transits)
DimensionSchedulingStatus ComputeRouteCumulsAndCostWithoutFixedTransits(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const RoutingModel::RouteDimensionTravelInfo *dimension_travel_info, std::vector< int64_t > *optimal_cumuls, std::vector< int64_t > *optimal_breaks, int64_t *optimal_cost_without_transits)
std::vector< DimensionSchedulingStatus > ComputeRouteCumulCostsForResourcesWithoutFixedTransits(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, const std::function< int64_t(int64_t, int64_t)> &transit_accessor, absl::Span< const RoutingModel::ResourceGroup::Resource > resources, absl::Span< const int > resource_indices, bool optimize_vehicle_costs, std::vector< int64_t > *optimal_costs_without_transits, std::vector< std::vector< int64_t > > *optimal_cumuls, std::vector< std::vector< int64_t > > *optimal_breaks)
DimensionSchedulingStatus ComputeRouteCumulCost(int vehicle, double solve_duration_ratio, const std::function< int64_t(int64_t)> &next_accessor, int64_t *optimal_cost)
static int64_t FastInt64Round(double x)
Definition mathutil.h:272
static T Abs(const T x)
Definition mathutil.h:96
void AddMaximumConstraint(int max_var, std::vector< int > vars) override
void SetParameters(const std::string &) override
void SetVariableDisjointBounds(int index, const std::vector< int64_t > &starts, const std::vector< int64_t > &ends) override
double GetValue(int index) const override
int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) override
DimensionSchedulingStatus Solve(absl::Duration duration_limit) override
void SetCoefficient(int ct_index, int index, double coefficient) override
void SetVariableName(int index, absl::string_view name) override
bool SetVariableBounds(int index, int64_t lower_bound, int64_t upper_bound) override
void SetObjectiveCoefficient(int index, double coefficient) override
double GetObjectiveCoefficient(int index) const override
std::string PrintModel() const override
Prints an understandable view of the model.
int64_t GetVariableUpperBound(int index) const override
void SetEnforcementLiteral(int ct, int condition) override
void AddRoute(absl::Span< const int64_t > nodes, absl::Span< const int > schedule_variables) override
int64_t GetVariableLowerBound(int index) const override
bool ModelIsEmpty() const override
Returns if the model is empty or not.
void AddProductConstraint(int product_var, std::vector< int > vars) override
int64_t GetVariableLowerBound(int index) const override
bool SetVariableBounds(int index, int64_t lower_bound, int64_t upper_bound) override
double GetValue(int index) const override
double GetObjectiveCoefficient(int index) const override
RoutingGlopWrapper(bool is_relaxation, const glop::GlopParameters &parameters)
void AddRoute(absl::Span< const int64_t >, absl::Span< const int >) override
void SetObjectiveCoefficient(int index, double coefficient) override
void AddMaximumConstraint(int, std::vector< int >) override
DimensionSchedulingStatus Solve(absl::Duration duration_limit) override
int64_t GetVariableUpperBound(int index) const override
void SetVariableDisjointBounds(int index, const std::vector< int64_t > &starts, const std::vector< int64_t > &ends) override
void SetCoefficient(int ct, int index, double coefficient) override
void SetVariableName(int index, absl::string_view name) override
int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) override
void AddProductConstraint(int, std::vector< int >) override
void SetParameters(const std::string &parameters) override
This function is meant to override the parameters of the solver.
virtual int64_t GetObjectiveValue() const =0
virtual DimensionSchedulingStatus Solve(absl::Duration duration_limit)=0
virtual void SetCoefficient(int ct, int index, double coefficient)=0
virtual int64_t GetVariableUpperBound(int index) const =0
int AddLinearConstraint(int64_t lower_bound, int64_t upper_bound, absl::Span< const std::pair< int, double > > variable_coeffs)
virtual int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound)=0
virtual void SetEnforcementLiteral(int ct, int condition)=0
virtual void AddProductConstraint(int product_var, std::vector< int > vars)=0
virtual std::string PrintModel() const =0
Prints an understandable view of the model.
virtual double GetValue(int index) const =0
virtual void SetVariableDisjointBounds(int index, const std::vector< int64_t > &starts, const std::vector< int64_t > &ends)=0
int AddReifiedLinearConstraint(int64_t lower_bound, int64_t upper_bound, absl::Span< const std::pair< int, double > > weighted_variables)
virtual void AddRoute(absl::Span< const int64_t > nodes, absl::Span< const int > schedule_variables)=0
virtual void SetObjectiveCoefficient(int index, double coefficient)=0
virtual bool SetVariableBounds(int index, int64_t lower_bound, int64_t upper_bound)=0
virtual void SetParameters(const std::string &parameters)=0
This function is meant to override the parameters of the solver.
virtual void AddMaximumConstraint(int max_var, std::vector< int > vars)=0
virtual void SetVariableName(int index, absl::string_view name)=0
virtual bool ModelIsEmpty() const
Returns if the model is empty or not.
virtual int64_t GetVariableLowerBound(int index) const =0
virtual double GetObjectiveCoefficient(int index) const =0
int AddVariable(int64_t lower_bound, int64_t upper_bound)
Adds a variable with bounds [lower_bound, upper_bound].
A full-fledged linear programming solver.
Definition lp_solver.h:31
T Add(std::function< T(Model *)> f)
Definition model.h:87
constexpr double kInfinity
Infinity for type Fractional.
Definition lp_types.h:87
ProblemStatus
Different statuses for a given problem.
Definition lp_types.h:105
std::function< SatParameters(Model *)> NewSatParameters(const std::string &params)
CpSolverResponse SolveCpModel(const CpModelProto &model_proto, Model *model)
In SWIG mode, we don't want anything besides these top-level includes.
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)
@ FEASIBLE
Only a feasible solution was found, optimality was not proven.
@ OPTIMAL
An optimal solution was found respecting all constraints.
std::vector< bool > SlopeAndYInterceptToConvexityRegions(absl::Span< const SlopeAndYIntercept > slope_and_y_intercept)
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)
std::string ProtobufDebugString(const P &message)
Definition proto_utils.h:32
std::vector< SlopeAndYIntercept > PiecewiseLinearFunctionToSlopeAndYIntercept(const FloatSlopePiecewiseLinearFunction &pwl_function, int index_start, int index_end)
friend::std::ostream & operator<<(::std::ostream &os, const SlopeAndYIntercept &it)