Google OR-Tools v9.14
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"
46#include "ortools/sat/model.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 {
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_add_lp_constraints_lazily(false);
482 parameters_.set_use_absl_random(false);
483 }
485 void Clear() override {
486 model_.Clear();
487 response_.Clear();
488 objective_coefficients_.clear();
489 schedule_variables_.clear();
490 }
492 const int index = model_.variables_size();
493 sat::IntegerVariableProto* const variable = model_.add_variables();
494 variable->add_domain(0);
495 variable->add_domain(static_cast<int64_t>(parameters_.mip_max_bound()));
496 return index;
497 }
498 void SetVariableName(int index, absl::string_view name) override {
499 model_.mutable_variables(index)->set_name(name.data());
500 }
501 bool SetVariableBounds(int index, int64_t lower_bound,
502 int64_t upper_bound) override {
503 DCHECK_GE(lower_bound, 0);
504 const int64_t capped_upper_bound =
505 std::min<int64_t>(upper_bound, parameters_.mip_max_bound());
506 if (lower_bound > capped_upper_bound) return false;
507 sat::IntegerVariableProto* const variable = model_.mutable_variables(index);
508 variable->set_domain(0, lower_bound);
509 variable->set_domain(1, capped_upper_bound);
510 return true;
511 }
512 void SetVariableDisjointBounds(int index, const std::vector<int64_t>& starts,
513 const std::vector<int64_t>& ends) override {
514 DCHECK_EQ(starts.size(), ends.size());
515 const int ct = CreateNewConstraint(1, 1);
516 for (int i = 0; i < starts.size(); ++i) {
517 const int variable = CreateNewPositiveVariable();
518#ifndef NDEBUG
519 SetVariableName(variable,
520 absl::StrFormat("disjoint(%ld, %ld)", index, i));
521#endif
522 SetVariableBounds(variable, 0, 1);
523 SetCoefficient(ct, variable, 1);
524 const int window_ct = CreateNewConstraint(starts[i], ends[i]);
525 SetCoefficient(window_ct, index, 1);
526 model_.mutable_constraints(window_ct)->add_enforcement_literal(variable);
527 }
528 }
529 int64_t GetVariableLowerBound(int index) const override {
530 return model_.variables(index).domain(0);
531 }
532 int64_t GetVariableUpperBound(int index) const override {
533 const auto& domain = model_.variables(index).domain();
534 return domain[domain.size() - 1];
535 }
536 void SetObjectiveCoefficient(int index, double coefficient) override {
537 if (index >= objective_coefficients_.size()) {
538 objective_coefficients_.resize(index + 1, 0);
539 }
540 objective_coefficients_[index] = coefficient;
541 sat::FloatObjectiveProto* const objective =
542 model_.mutable_floating_point_objective();
543 objective->add_vars(index);
544 objective->add_coeffs(coefficient);
545 }
546 double GetObjectiveCoefficient(int index) const override {
547 return (index < objective_coefficients_.size())
548 ? objective_coefficients_[index]
549 : 0;
550 }
551 void ClearObjective() override {
552 model_.mutable_floating_point_objective()->Clear();
553 }
554 int NumVariables() const override { return model_.variables_size(); }
555 int CreateNewConstraint(int64_t lower_bound, int64_t upper_bound) override {
557 model_.add_constraints()->mutable_linear();
558 ct->add_domain(lower_bound);
559 ct->add_domain(upper_bound);
560 return model_.constraints_size() - 1;
561 }
562 void SetCoefficient(int ct_index, int index, double coefficient) override {
564 model_.mutable_constraints(ct_index)->mutable_linear();
565 ct->add_vars(index);
566 const int64_t integer_coefficient = coefficient;
567 ct->add_coeffs(integer_coefficient);
568 }
569 bool IsCPSATSolver() override { return true; }
570 void AddObjectiveConstraint() override {
571 const sat::CpObjectiveProto& objective = response_.integer_objective();
572 int64_t activity = 0;
573 for (int i = 0; i < objective.vars_size(); ++i) {
574 activity += response_.solution(objective.vars(i)) * objective.coeffs(i);
575 }
576 const int ct =
577 CreateNewConstraint(std::numeric_limits<int64_t>::min(), activity);
578 for (int i = 0; i < objective.vars_size(); ++i) {
579 SetCoefficient(ct, objective.vars(i), objective.coeffs(i));
580 }
581 model_.clear_objective();
582 }
583 void AddMaximumConstraint(int max_var, std::vector<int> vars) override {
584 sat::LinearArgumentProto* const ct =
585 model_.add_constraints()->mutable_lin_max();
586 ct->mutable_target()->add_vars(max_var);
587 ct->mutable_target()->add_coeffs(1);
588 for (const int var : vars) {
589 sat::LinearExpressionProto* const expr = ct->add_exprs();
590 expr->add_vars(var);
591 expr->add_coeffs(1);
592 }
593 }
594 void AddProductConstraint(int product_var, std::vector<int> vars) override {
595 sat::LinearArgumentProto* const ct =
596 model_.add_constraints()->mutable_int_prod();
597 ct->mutable_target()->add_vars(product_var);
598 ct->mutable_target()->add_coeffs(1);
599 for (const int var : vars) {
601 expr->add_vars(var);
602 expr->add_coeffs(1);
603 }
604 }
605 void SetEnforcementLiteral(int ct, int condition) override {
606 DCHECK_LT(ct, model_.constraints_size());
607 model_.mutable_constraints(ct)->add_enforcement_literal(condition);
608 }
609 void AddRoute(absl::Span<const int64_t> nodes,
610 absl::Span<const int> schedule_variables) override {
611 DCHECK_EQ(nodes.size(), schedule_variables.size());
612 for (const int64_t node : nodes) {
613 if (node >= schedule_hint_.size()) schedule_hint_.resize(node + 1, 0);
614 }
615 for (int n = 0; n < nodes.size(); ++n) {
616 schedule_variables_.push_back(
617 {.node = nodes[n], .cumul = schedule_variables[n]});
618 }
619 }
620 DimensionSchedulingStatus Solve(absl::Duration duration_limit) override {
621 const double max_time = absl::ToDoubleSeconds(duration_limit);
622 if (max_time <= 0.0) return DimensionSchedulingStatus::INFEASIBLE;
623 parameters_.set_max_time_in_seconds(max_time);
624 VLOG(2) << ProtobufDebugString(model_);
625 auto record_hint = [this]() {
626 hint_.Clear();
627 for (int i = 0; i < response_.solution_size(); ++i) {
628 hint_.add_vars(i);
629 hint_.add_values(response_.solution(i));
630 }
631 for (const auto& [node, cumul] : schedule_variables_) {
632 schedule_hint_[node] = response_.solution(cumul);
633 }
634 };
635 model_.clear_solution_hint();
636 auto* hint = model_.mutable_solution_hint();
637 if (hint_.vars_size() == model_.variables_size()) {
638 *hint = hint_;
639 } else {
640 for (const auto& [node, cumul] : schedule_variables_) {
641 if (schedule_hint_[node] == 0) continue;
642 hint->add_vars(cumul);
643 hint->add_values(schedule_hint_[node]);
644 }
645 }
646 sat::Model model;
647 model.Add(sat::NewSatParameters(parameters_));
648 response_ = sat::SolveCpModel(model_, &model);
649 VLOG(2) << response_;
650 DCHECK_NE(response_.status(), sat::CpSolverStatus::MODEL_INVALID);
651 if (response_.status() == sat::CpSolverStatus::OPTIMAL ||
652 (response_.status() == sat::CpSolverStatus::FEASIBLE &&
653 !model_.has_floating_point_objective())) {
654 record_hint();
656 } else if (response_.status() == sat::CpSolverStatus::FEASIBLE) {
657 // TODO(user): Consider storing "feasible" solutions in a separate
658 // cache we use as hint when the "optimal" cache is empty.
660 }
662 }
663 int64_t GetObjectiveValue() const override {
664 return MathUtil::FastInt64Round(response_.objective_value());
665 }
666 double GetValue(int index) const override {
667 return response_.solution(index);
668 }
669 bool SolutionIsInteger() const override { return true; }
670
671 // NOTE: This function is not implemented for the CP-SAT solver.
672 void SetParameters(const std::string& /*parameters*/) override {
673 DCHECK(false);
674 }
675
676 bool ModelIsEmpty() const override { return model_.ByteSizeLong() == 0; }
677
678 // Prints an understandable view of the model
679 std::string PrintModel() const override;
680
681 private:
682 sat::CpModelProto model_;
683 sat::CpSolverResponse response_;
684 sat::SatParameters parameters_;
685 std::vector<double> objective_coefficients_;
687 struct NodeAndCumul {
688 int64_t node;
689 int cumul;
690 };
691 // Stores node/cumul pairs of the routes in the current model.
692 std::vector<NodeAndCumul> schedule_variables_;
693 // Maps node to its last known value in any optimal solution.
694 std::vector<int64_t> schedule_hint_;
695};
696
697// Utility class used in Local/GlobalDimensionCumulOptimizer to set the linear
698// solver constraints and solve the problem.
700 using RouteDimensionTravelInfo = RoutingModel::RouteDimensionTravelInfo;
701 using Resource = RoutingModel::ResourceGroup::Resource;
702
703 public:
704 DimensionCumulOptimizerCore(const RoutingDimension* dimension,
705 bool use_precedence_propagator);
706
707 // Finds an optimal (or just feasible) solution for the route for the given
708 // resource. If the resource is null, it is simply ignored.
710 int vehicle, double solve_duration_ratio,
711 const std::function<int64_t(int64_t)>& next_accessor,
712 const RouteDimensionTravelInfo* dimension_travel_info,
713 const Resource* resource, bool optimize_vehicle_costs,
714 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
715 std::vector<int64_t>* break_values, int64_t* cost_without_transit,
716 int64_t* transit_cost, bool clear_lp = true);
717
718 // Given some cumuls and breaks, computes the solution cost by solving the
719 // same model as in OptimizeSingleRouteWithResource() with the addition of
720 // constraints for cumuls and breaks.
722 int vehicle, double solve_duration_ratio,
723 const std::function<int64_t(int64_t)>& next_accessor,
724 const RouteDimensionTravelInfo* dimension_travel_info,
726 absl::Span<const int64_t> solution_cumul_values,
727 absl::Span<const int64_t> solution_break_values,
728 int64_t* cost_without_transits, int64_t* cost_offset = nullptr,
729 bool reuse_previous_model_if_possible = true, bool clear_lp = false,
730 bool clear_solution_constraints = true,
731 absl::Duration* solve_duration = nullptr);
732
733 // Computes the optimal scheduling solution(s) for the route for each resource
734 // in 'resources' with an index in 'resource_indices'.
735 // If both 'resources' and 'resource_indices' are empty, computes the optimal
736 // solution for the route itself (without added resource constraints).
737 std::vector<DimensionSchedulingStatus> OptimizeSingleRouteWithResources(
738 int vehicle, double solve_duration_ratio,
739 const std::function<int64_t(int64_t)>& next_accessor,
740 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
741 const RouteDimensionTravelInfo* dimension_travel_info,
742 absl::Span<const Resource> resources,
743 absl::Span<const int> resource_indices, bool optimize_vehicle_costs,
745 std::vector<std::vector<int64_t>>* cumul_values,
746 std::vector<std::vector<int64_t>>* break_values,
747 std::vector<int64_t>* costs_without_transits, int64_t* transit_cost,
748 bool clear_lp = true);
749
750 // In the Optimize() method, if both 'cumul_values' and 'cost' parameters are
751 // null, we don't optimize the cost and stop at the first feasible solution in
752 // the linear solver (since in this case only feasibility is of interest).
753 // When 'optimize_resource_assignment' is false, the resource var values are
754 // used to constrain the vehicle routes according to their assigned resource.
756 const std::function<int64_t(int64_t)>& next_accessor,
757 const std::vector<RouteDimensionTravelInfo>&
758 dimension_travel_info_per_route,
759 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
760 std::vector<int64_t>* break_values,
761 std::vector<std::vector<int>>* resource_indices_per_group,
762 int64_t* cost_without_transits, int64_t* transit_cost,
763 bool clear_lp = true, bool optimize_resource_assignment = true);
764
766 const std::function<int64_t(int64_t)>& next_accessor,
767 const std::vector<RouteDimensionTravelInfo>&
768 dimension_travel_info_per_route,
769 RoutingLinearSolverWrapper* solver, std::vector<int64_t>* cumul_values,
770 std::vector<int64_t>* break_values);
771
773 int vehicle, double solve_duration_ratio,
774 const std::function<int64_t(int64_t)>& next_accessor,
775 const RouteDimensionTravelInfo* dimension_travel_info,
776 const Resource* resource, RoutingLinearSolverWrapper* solver,
777 std::vector<int64_t>* cumul_values, std::vector<int64_t>* break_values);
778
779 const RoutingDimension* dimension() const { return dimension_; }
780
781 private:
782 // Initializes the containers and given solver. Must be called prior to
783 // setting any constraints and solving.
784 void InitOptimizer(RoutingLinearSolverWrapper* solver);
785
786 // Computes the minimum/maximum of cumuls for nodes on "route", and sets them
787 // in current_route_[min|max]_cumuls_ respectively.
788 bool ExtractRouteCumulBounds(absl::Span<const int64_t> route,
789 int64_t cumul_offset);
790
791 // Tighten the minimum/maximum of cumuls for nodes on "route"
792 // If the propagator_ is not null, uses the bounds tightened by the
793 // propagator. Otherwise, the minimum transits are used to tighten them.
794 bool TightenRouteCumulBounds(absl::Span<const int64_t> route,
795 absl::Span<const int64_t> min_transits,
796 int64_t cumul_offset);
797
798 // Sets the constraints for all nodes on "vehicle"'s route according to
799 // "next_accessor". If optimize_costs is true, also sets the objective
800 // coefficients for the LP.
801 // Returns false if some infeasibility was detected, true otherwise.
802 bool SetRouteCumulConstraints(
803 int vehicle, const std::function<int64_t(int64_t)>& next_accessor,
804 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
805 const RouteDimensionTravelInfo* dimension_travel_info,
806 int64_t cumul_offset, bool optimize_costs,
807 RoutingLinearSolverWrapper* solver, int64_t* route_transit_cost,
808 int64_t* route_cost_offset);
809
810 // Sets the constraints for all variables related to travel. Handles
811 // static or time-dependent travel values.
812 // Returns false if some infeasibility was detected, true otherwise.
813 bool SetRouteTravelConstraints(
814 const RouteDimensionTravelInfo* dimension_travel_info,
815 absl::Span<const int> lp_slacks, absl::Span<const int64_t> fixed_transit,
817
818 // Sets the global constraints on the dimension, and adds global objective
819 // cost coefficients if optimize_costs is true.
820 // NOTE: When called, the call to this function MUST come after
821 // SetRouteCumulConstraints() has been called on all routes, so that
822 // index_to_cumul_variable_ and min_start/max_end_cumul_ are correctly
823 // initialized.
824 // Returns false if some infeasibility was detected, true otherwise.
825 bool SetGlobalConstraints(
826 const std::function<int64_t(int64_t)>& next_accessor,
827 int64_t cumul_offset, bool optimize_costs,
828 bool optimize_resource_assignment, RoutingLinearSolverWrapper* solver);
829
830 bool SetGlobalConstraintsForResourceAssignment(
831 const std::function<int64_t(int64_t)>& next_accessor,
832 int64_t cumul_offset, RoutingLinearSolverWrapper* solver);
833
834 void SetValuesFromLP(absl::Span<const int> lp_variables, int64_t offset,
836 std::vector<int64_t>* lp_values) const;
837
838 void SetResourceIndices(
840 std::vector<std::vector<int>>* resource_indices_per_group) const;
841
842 // This function packs the routes of the given vehicles while keeping the cost
843 // of the LP lower than its current (supposed optimal) objective value.
844 // It does so by setting the current objective variables' coefficient to 0 and
845 // setting the coefficient of the route ends to 1, to first minimize the route
846 // ends' cumuls, and then maximizes the starts' cumuls without increasing the
847 // ends.
848 DimensionSchedulingStatus PackRoutes(
849 std::vector<int> vehicles, double solve_duration_ratio,
851 const glop::GlopParameters& packing_parameters);
852
853 std::unique_ptr<CumulBoundsPropagator> propagator_;
854 std::vector<int64_t> current_route_min_cumuls_;
855 std::vector<int64_t> current_route_max_cumuls_;
856 const RoutingDimension* const dimension_;
857 // Scheduler variables for current route cumuls and for all nodes cumuls.
858 std::vector<int> current_route_cumul_variables_;
859 std::vector<int> index_to_cumul_variable_;
860 // Scheduler variables for current route breaks and all vehicle breaks.
861 // There are two variables for each break: start and end.
862 // current_route_break_variables_ has variables corresponding to
863 // break[0] start, break[0] end, break[1] start, break[1] end, etc.
864 std::vector<int> current_route_break_variables_;
865 // Vector all_break_variables contains the break variables of all vehicles,
866 // in the same format as current_route_break_variables.
867 // It is the concatenation of break variables of vehicles in [0, #vehicles).
868 std::vector<int> all_break_variables_;
869 // Allows to retrieve break variables of a given vehicle: those go from
870 // all_break_variables_[vehicle_to_all_break_variables_offset_[vehicle]] to
871 // all_break_variables[vehicle_to_all_break_variables_offset_[vehicle+1]-1].
872 std::vector<int> vehicle_to_all_break_variables_offset_;
873 // The following vector contains indices of resource-class-to-vehicle
874 // assignment variables. For every resource group, stores indices of
875 // num_resource_classes*num_vehicles boolean variables indicating whether
876 // resource class #rc is assigned to vehicle #v.
877 std::vector<std::vector<int>>
878 resource_class_to_vehicle_assignment_variables_per_group_;
879 // The following vector keeps track of the resources ignored during resource
880 // assignment because they're pre-assigned to a specific vehicle.
881 std::vector<std::vector<absl::flat_hash_set<int>>>
882 resource_class_ignored_resources_per_group_;
883
884 int max_end_cumul_;
885 int min_start_cumul_;
886 std::vector<std::pair<int64_t, int64_t>>
887 visited_pickup_delivery_indices_for_pair_;
888};
889
890// Class used to compute optimal values for dimension cumuls of routes,
891// minimizing cumul soft lower and upper bound costs, and vehicle span costs of
892// a route.
893// In its methods, next_accessor is a callback returning the next node of a
894// given node on a route.
896 public:
898 const RoutingDimension* dimension,
900
901 // If feasible, computes the optimal cost of the route performed by a vehicle,
902 // minimizing cumul soft lower and upper bound costs and vehicle span costs,
903 // and stores it in "optimal_cost" (if not null).
904 // Returns true iff the route respects all constraints.
906 int vehicle, double solve_duration_ratio,
907 const std::function<int64_t(int64_t)>& next_accessor,
908 int64_t* optimal_cost);
909
910 // Same as ComputeRouteCumulCost, but the cost computed does not contain
911 // the part of the vehicle span cost due to fixed transits.
913 int vehicle, double solve_duration_ratio,
914 const std::function<int64_t(int64_t)>& next_accessor,
915 const RoutingModel::ResourceGroup::Resource* resource,
916 int64_t* optimal_cost_without_transits);
917
918 std::vector<DimensionSchedulingStatus>
920 int vehicle, double solve_duration_ratio,
921 const std::function<int64_t(int64_t)>& next_accessor,
922 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
923 absl::Span<const RoutingModel::ResourceGroup::Resource> resources,
924 absl::Span<const int> resource_indices, bool optimize_vehicle_costs,
925 std::vector<int64_t>* optimal_costs_without_transits,
926 std::vector<std::vector<int64_t>>* optimal_cumuls,
927 std::vector<std::vector<int64_t>>* optimal_breaks);
928
929 // If feasible, computes the optimal values for cumul and break variables
930 // of the route performed by a vehicle, minimizing cumul soft lower, upper
931 // bound costs and vehicle span costs, stores them in "optimal_cumuls"
932 // (if not null), and optimal_breaks, and returns true.
933 // Returns false if the route is not feasible.
935 int vehicle, double solve_duration_ratio,
936 const std::function<int64_t(int64_t)>& next_accessor,
937 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
938 const RoutingModel::ResourceGroup::Resource* resource,
939 std::vector<int64_t>* optimal_cumuls,
940 std::vector<int64_t>* optimal_breaks);
941
942 // Simple combination of ComputeRouteCumulCostWithoutFixedTransits() and
943 // ComputeRouteCumuls().
945 int vehicle, double solve_duration_ratio,
946 const std::function<int64_t(int64_t)>& next_accessor,
947 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
948 std::vector<int64_t>* optimal_cumuls,
949 std::vector<int64_t>* optimal_breaks,
950 int64_t* optimal_cost_without_transits);
951
952 // If feasible, computes the cost of a given route performed by a vehicle
953 // defined by its cumuls and breaks.
955 int vehicle, double solve_duration_ratio,
956 const std::function<int64_t(int64_t)>& next_accessor,
957 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
958 absl::Span<const int64_t> solution_cumul_values,
959 absl::Span<const int64_t> solution_break_values, int64_t* solution_cost,
960 int64_t* cost_offset = nullptr,
961 bool reuse_previous_model_if_possible = false, bool clear_lp = true,
962 absl::Duration* solve_duration = nullptr);
963
964 // Similar to ComputeRouteCumuls, but also tries to pack the cumul values on
965 // the route, such that the cost remains the same, the cumul of route end is
966 // minimized, and then the cumul of the start of the route is maximized.
967 // If 'resource' is non-null, the packed route must also respect its start/end
968 // time window.
970 int vehicle, double solve_duration_ratio,
971 const std::function<int64_t(int64_t)>& next_accessor,
972 const RoutingModel::RouteDimensionTravelInfo* dimension_travel_info,
973 const RoutingModel::ResourceGroup::Resource* resource,
974 std::vector<int64_t>* packed_cumuls, std::vector<int64_t>* packed_breaks);
975
976 const RoutingDimension* dimension() const {
977 return optimizer_core_.dimension();
978 }
979
980 private:
981 std::vector<std::unique_ptr<RoutingLinearSolverWrapper>> solver_;
982 DimensionCumulOptimizerCore optimizer_core_;
983};
984
986 public:
988 const RoutingDimension* dimension,
990 // If feasible, computes the optimal cost of the entire model with regards to
991 // the optimizer_core_'s dimension costs, minimizing cumul soft lower/upper
992 // bound costs and vehicle/global span costs, and stores it in "optimal_cost"
993 // (if not null).
994 // Returns true iff all the constraints can be respected.
996 const std::function<int64_t(int64_t)>& next_accessor,
997 int64_t* optimal_cost_without_transits);
998 // If feasible, computes the optimal values for cumul, break and resource
999 // variables, minimizing cumul soft lower/upper bound costs and vehicle/global
1000 // span costs, stores them in "optimal_cumuls" (if not null), "optimal_breaks"
1001 // and "optimal_resource_indices_per_group", and returns true.
1002 // Returns false if the routes are not feasible.
1004 const std::function<int64_t(int64_t)>& next_accessor,
1005 const std::vector<RoutingModel::RouteDimensionTravelInfo>&
1006 dimension_travel_info_per_route,
1007 std::vector<int64_t>* optimal_cumuls,
1008 std::vector<int64_t>* optimal_breaks,
1009 std::vector<std::vector<int>>* optimal_resource_indices_per_group);
1010
1011 // Similar to ComputeCumuls, but also tries to pack the cumul values on all
1012 // routes, such that the cost remains the same, the cumuls of route ends are
1013 // minimized, and then the cumuls of the starts of the routes are maximized.
1014 // NOTE: It's assumed that all resource variables (if any) are Bound() when
1015 // calling this method, so each vehicle's resource attributes are set as
1016 // constraint on its route and no resource assignment is required.
1018 const std::function<int64_t(int64_t)>& next_accessor,
1019 const std::vector<RoutingModel::RouteDimensionTravelInfo>&
1020 dimension_travel_info_per_route,
1021 std::vector<int64_t>* packed_cumuls, std::vector<int64_t>* packed_breaks);
1022
1023 const RoutingDimension* dimension() const {
1024 return optimizer_core_.dimension();
1025 }
1026
1027 private:
1028 std::unique_ptr<RoutingLinearSolverWrapper> solver_;
1029 DimensionCumulOptimizerCore optimizer_core_;
1030};
1031
1032// Finds the approximate (*) min-cost (i.e. best) assignment of all vehicles
1033// v ∈ 'vehicles' to resources, i.e. indices in [0..num_resources), where the
1034// costs of assigning a vehicle v to a resource r of class r_c is given by
1035// 'vehicle_to_resource_class_assignment_costs(v)[r_c]', unless the latter is
1036// empty in which case vehicle v does not need a resource.
1037//
1038// Returns the cost of that optimal assignment, or -1 if it's infeasible.
1039// Moreover, if 'resource_indices' != nullptr, it assumes that its size is the
1040// global number of vehicles, and assigns its element #v with the resource r
1041// assigned to v, or -1 if none.
1042//
1043// (*) COST SCALING: When the costs are so large that they could possibly yield
1044// int64_t overflow, this method returns a *lower* bound of the actual optimal
1045// cost, and the assignment output in 'resource_indices' may be suboptimal if
1046// that lower bound isn't tight (but it should be very close).
1047//
1048// COMPLEXITY: in practice, should be roughly
1049// O(num_resource_classes * vehicles.size() + resource_indices->size()).
1051 absl::Span<const int> vehicles,
1052 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1053 std::vector<int>>&
1054 resource_indices_per_class,
1055 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1056 absl::flat_hash_set<int>>&
1057 ignored_resources_per_class,
1058 std::function<const std::vector<int64_t>*(int)>
1059 vehicle_to_resource_class_assignment_costs,
1060 std::vector<int>* resource_indices);
1061
1062// Computes the vehicle-to-resource-class assignment costs for the given vehicle
1063// to all resource classes in the group, and sets these costs in
1064// 'assignment_costs' (if non-null). The latter is cleared and kept empty if the
1065// vehicle 'v' should not have a resource assigned to it.
1066// optimize_vehicle_costs indicates if the costs should be optimized or if
1067// we merely care about feasibility (cost of 0) and infeasibility (cost of -1)
1068// of the assignments.
1069// The cumul and break values corresponding to the assignment of each resource
1070// are also set in cumul_values and break_values, if non-null.
1072 int v, double solve_duration_ratio,
1073 const RoutingModel::ResourceGroup& resource_group,
1074 const util_intops::StrongVector<RoutingModel::ResourceClassIndex,
1075 absl::flat_hash_set<int>>&
1076 ignored_resources_per_class,
1077 const std::function<int64_t(int64_t)>& next_accessor,
1078 const std::function<int64_t(int64_t, int64_t)>& transit_accessor,
1079 bool optimize_vehicle_costs, LocalDimensionCumulOptimizer* lp_optimizer,
1080 LocalDimensionCumulOptimizer* mp_optimizer,
1081 std::vector<int64_t>* assignment_costs,
1082 std::vector<std::vector<int64_t>>* cumul_values,
1083 std::vector<std::vector<int64_t>>* break_values);
1084
1085// Structure to store the slope and y_intercept of a segment of a piecewise
1086// linear function.
1088 double slope;
1090
1091 friend ::std::ostream& operator<<(::std::ostream& os,
1092 const SlopeAndYIntercept& it) {
1093 return os << "{" << it.slope << ", " << it.y_intercept << "}";
1094 }
1095};
1096
1097// Given a FloatSlopePiecewiseLinearFunction, returns a vector of slope and
1098// y-intercept corresponding to each segment. Only the segments in
1099// [index_start, index_end[ will be considered.
1100// TODO(user): Consider making the following two functions methods of
1101// FloatSlopePiecewiseLinearFunction. They're only called in lp_scheduling.cc
1102// and ../tour_optimization/model_test.cc, but they might come in handy.
1103std::vector<SlopeAndYIntercept> PiecewiseLinearFunctionToSlopeAndYIntercept(
1104 const FloatSlopePiecewiseLinearFunction& pwl_function, int index_start = 0,
1105 int index_end = -1);
1106
1107// Converts a vector of SlopeAndYIntercept to a vector of convexity regions.
1108// Convexity regions are defined such that, all segment in a convexity region
1109// form a convex function. The boolean in the vector is set to true if the
1110// segment associated to it starts a new convexity region. Therefore, a convex
1111// function would yield {true, false, false, ...} and a concave function would
1112// yield {true, true, true, ...}.
1113std::vector<bool> SlopeAndYInterceptToConvexityRegions(
1114 absl::Span<const SlopeAndYIntercept> slope_and_y_intercept);
1115
1116} // namespace operations_research
1117
1118#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:260
static T Abs(const T x)
Definition mathutil.h:95
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].
RoutingSearchParameters_SchedulingSolver SchedulingSolver
A full-fledged linear programming solver.
Definition lp_solver.h:31
int vars_size() const
repeated int32 vars = 1;
void set_domain(int index, ::int64_t value)
::operations_research::sat::LinearExpressionProto *PROTOBUF_NONNULL mutable_target()
::operations_research::sat::LinearExpressionProto *PROTOBUF_NONNULL add_exprs()
T Add(std::function< T(Model *)> f)
Definition model.h:87
static constexpr SearchBranching PORTFOLIO_SEARCH
constexpr Fractional 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(absl::string_view 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:31
std::vector< SlopeAndYIntercept > PiecewiseLinearFunctionToSlopeAndYIntercept(const FloatSlopePiecewiseLinearFunction &pwl_function, int index_start, int index_end)
friend::std::ostream & operator<<(::std::ostream &os, const SlopeAndYIntercept &it)