Classes | Macros | Typedefs | Functions
routing.h File Reference
#include <cstddef>
#include <functional>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash.h"
#include "absl/time/time.h"
#include "ortools/base/adjustable_priority_queue-inl.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/int_type_indexed_vector.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_parameters.pb.h"
#include "ortools/constraint_solver/routing_types.h"
#include "ortools/glop/lp_solver.h"
#include "ortools/graph/graph.h"
#include "ortools/sat/theta_tree.h"
#include "ortools/util/range_query_function.h"
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  DisjunctivePropagator::Tasks
 A structure to hold tasks described by their features. More...
 
struct  TypeRegulationsChecker::NodeCount
 
struct  SimpleBoundCosts::BoundCost
 
struct  RoutingDimension::NodePrecedence
 
struct  CheapestInsertionFilteredDecisionBuilder::StartEndValue
 
struct  SavingsFilteredDecisionBuilder::SavingsParameters
 
class  SavingsFilteredDecisionBuilder::SavingsContainer< S >
 
struct  SavingsFilteredDecisionBuilder::VehicleClassEntry
 

Macros

#define OR_TOOLS_CONSTRAINT_SOLVER_ROUTING_H_
 

Typedefs

using GetTabuVarsCallback = std::function< std::vector< operations_research::IntVar * >(RoutingModel *)>
 Sets the callback returning the variable to use for the Tabu Search metaheuristic. More...
 

Functions

routing_no_lns(default:false) int GetVisitType (int64 index) const
 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. More...
 
void CloseVisitTypes ()
 This function should be called once all node visit types have been set and prior to adding any incompatibilities/requirements. More...
 
int GetNumberOfVisitTypes () const
 
void AddHardTypeIncompatibility (int type1, int type2)
 Incompatibilities: Two nodes with "hard" incompatible types cannot share the same route at all, while with a "temporal" incompatibility they can't be on the same route at the same time. More...
 
void AddTemporalTypeIncompatibility (int type1, int type2)
 
const absl::flat_hash_set< int > & GetHardTypeIncompatibilitiesOfType (int type) const
 Returns visit types incompatible with a given type. More...
 
const absl::flat_hash_set< int > & GetTemporalTypeIncompatibilitiesOfType (int type) const
 
bool HasHardTypeIncompatibilities () const
 Returns true iff any hard (resp. More...
 
bool HasTemporalTypeIncompatibilities () const
 
void AddSameVehicleRequiredTypeAlternatives (int dependent_type, absl::flat_hash_set< int > required_type_alternatives)
 Requirements: More...
 
void AddTemporalRequiredTypeAlternatives (int dependent_type, absl::flat_hash_set< int > required_type_alternatives)
 If type_D temporally depends on type_R, any non-delivery node_D of type_D requires at least one non-delivered node of type_R on its vehicle at the time node_D is visited. More...
 
const std::vector< absl::flat_hash_set< int > > & GetSameVehicleRequiredTypeAlternativesOfType (int type) const
 clang-format off Returns the sets of same-vehicle/temporal requirement alternatives for the given type. More...
 
const std::vector< absl::flat_hash_set< int > > & GetTemporalRequiredTypeAlternativesOfType (int type) const
 
bool HasSameVehicleTypeRequirements () const
 clang-format on Returns true iff any same-route (resp. More...
 
bool HasTemporalTypeRequirements () const
 
bool HasTypeRegulations () const
 Returns true iff the model has any incompatibilities or requirements set on node types. More...
 
int64 UnperformedPenalty (int64 var_index) const
 Get the "unperformed" penalty of a node. More...
 
int64 UnperformedPenaltyOrValue (int64 default_value, int64 var_index) const
 Same as above except that it returns default_value instead of 0 when penalty is not well defined (default value is passed as first argument to simplify the usage of the method in a callback). More...
 
int64 GetDepot () const
 Returns the variable index of the first starting or ending node of all routes. More...
 
void SetArcCostEvaluatorOfAllVehicles (int evaluator_index)
 Sets the cost function of the model such that the cost of a segment of a route between node 'from' and 'to' is evaluator(from, to), whatever the route or vehicle performing the route. More...
 
void SetArcCostEvaluatorOfVehicle (int evaluator_index, int vehicle)
 Sets the cost function for a given vehicle route. More...
 
void SetFixedCostOfAllVehicles (int64 cost)
 Sets the fixed cost of all vehicle routes. More...
 
void SetFixedCostOfVehicle (int64 cost, int vehicle)
 Sets the fixed cost of one vehicle route. More...
 
int64 GetFixedCostOfVehicle (int vehicle) const
 Returns the route fixed cost taken into account if the route of the vehicle is not empty, aka there's at least one node on the route other than the first and last nodes. More...
 
quadratic_cost_factor_of_vehicle_ *[v] square of length of route v void SetAmortizedCostFactorsOfAllVehicles (int64 linear_cost_factor, int64 quadratic_cost_factor)
 The following methods set the linear and quadratic cost factors of vehicles (must be positive values). More...
 
void SetAmortizedCostFactorsOfVehicle (int64 linear_cost_factor, int64 quadratic_cost_factor, int vehicle)
 Sets the linear and quadratic cost factor of the given vehicle. More...
 
const std::vector< int64 > & GetAmortizedLinearCostFactorOfVehicles () const
 
const std::vector< int64 > & GetAmortizedQuadraticCostFactorOfVehicles () const
 
void ConsiderEmptyRouteCostsForVehicle (bool consider_costs, int vehicle)
 
bool AreEmptyRouteCostsConsideredForVehicle (int vehicle) const
 
const Solver::IndexEvaluator2 & first_solution_evaluator () const
 Search Gets/sets the evaluator used during the search. More...
 
void SetFirstSolutionEvaluator (Solver::IndexEvaluator2 evaluator)
 Takes ownership of evaluator. More...
 
void AddLocalSearchOperator (LocalSearchOperator *ls_operator)
 Adds a local search operator to the set of operators used to solve the vehicle routing problem. More...
 
void AddSearchMonitor (SearchMonitor *const monitor)
 Adds a search monitor to the search used to solve the routing model. More...
 
void AddAtSolutionCallback (std::function< void()> callback)
 Adds a callback called each time a solution is found during the search. More...
 
void AddVariableMinimizedByFinalizer (IntVar *var)
 Adds a variable to minimize in the solution finalizer. More...
 
void AddVariableMaximizedByFinalizer (IntVar *var)
 Adds a variable to maximize in the solution finalizer (see above for information on the solution finalizer). More...
 
void CloseModel ()
 Closes the current routing model; after this method is called, no modification to the model can be done, but RoutesToAssignment becomes available. More...
 
void CloseModelWithParameters (const RoutingSearchParameters &search_parameters)
 Same as above taking search parameters (as of 10/2015 some the parameters have to be set when closing the model). More...
 
const Assignment * Solve (const Assignment *assignment=nullptr)
 Solves the current routing model; closes the current model. More...
 
const Assignment * SolveWithParameters (const RoutingSearchParameters &search_parameters, std::vector< const Assignment * > *solutions=nullptr)
 Solves the current routing model with the given parameters. More...
 
const Assignment * SolveFromAssignmentWithParameters (const Assignment *assignment, const RoutingSearchParameters &search_parameters, std::vector< const Assignment * > *solutions=nullptr)
 
void SetAssignmentFromOtherModelAssignment (Assignment *target_assignment, const RoutingModel *source_model, const Assignment *source_assignment)
 Given a "source_model" and its "source_assignment", resets "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ if costs aren't homogeneous across vehicles) of "this" model, with the values set according to those in "other_assignment". More...
 
int64 ComputeLowerBound ()
 Computes a lower bound to the routing problem solving a linear assignment problem. More...
 
Status status () const
 Returns the current status of the routing model. More...
 
IntVar * ApplyLocks (const std::vector< int64 > &locks)
 Applies a lock chain to the next search. More...
 
bool ApplyLocksToAllVehicles (const std::vector< std::vector< int64 >> &locks, bool close_routes)
 Applies lock chains to all vehicles to the next search, such that locks[p] is the lock chain for route p. More...
 
const Assignment *const PreAssignment () const
 Returns an assignment used to fix some of the variables of the problem. More...
 
Assignment * MutablePreAssignment ()
 
bool WriteAssignment (const std::string &file_name) const
 Writes the current solution to a file containing an AssignmentProto. More...
 
Assignment * ReadAssignment (const std::string &file_name)
 Reads an assignment from a file and returns the current solution. More...
 
Assignment * RestoreAssignment (const Assignment &solution)
 Restores an assignment as a solution in the routing model and returns the new solution. More...
 
Assignment * ReadAssignmentFromRoutes (const std::vector< std::vector< int64 >> &routes, bool ignore_inactive_indices)
 Restores the routes as the current solution. More...
 
bool RoutesToAssignment (const std::vector< std::vector< int64 >> &routes, bool ignore_inactive_indices, bool close_routes, Assignment *const assignment) const
 Fills an assignment from a specification of the routes of the vehicles. More...
 
void AssignmentToRoutes (const Assignment &assignment, std::vector< std::vector< int64 >> *const routes) const
 Converts the solution in the given assignment to routes for all vehicles. More...
 
Assignment * CompactAssignment (const Assignment &assignment) const
 Returns a compacted version of the given assignment, in which all vehicles with id lower or equal to some N have non-empty routes, and all vehicles with id greater than N have empty routes. More...
 
Assignment * CompactAndCheckAssignment (const Assignment &assignment) const
 Same as CompactAssignment() but also checks the validity of the final compact solution; if it is not valid, no attempts to repair it are made (instead, the method returns nullptr). More...
 
void AddToAssignment (IntVar *const var)
 Adds an extra variable to the vehicle routing assignment. More...
 
void AddIntervalToAssignment (IntervalVar *const interval)
 
const Assignment * PackCumulsOfOptimizerDimensionsFromAssignment (const Assignment *original_assignment, absl::Duration duration_limit)
 For every dimension in the model's dimensions_for_local/global_optimizer_, this method tries to pack the cumul values of the dimension, such that: More...
 
void SetSweepArranger (SweepArranger *sweep_arranger)
 
SweepArranger * sweep_arranger () const
 Returns the sweep arranger to be used by routing heuristics. More...
 
void AddLocalSearchFilter (LocalSearchFilter *filter)
 Adds a custom local search filter to the list of filters used to speed up local search by pruning unfeasible variable assignments. More...
 
int64 Start (int vehicle) const
 Model inspection. More...
 
int64 End (int vehicle) const
 Returns the variable index of the ending node of a vehicle route. More...
 
bool IsStart (int64 index) const
 Returns true if 'index' represents the first node of a route. More...
 
bool IsEnd (int64 index) const
 Returns true if 'index' represents the last node of a route. More...
 
int VehicleIndex (int index) const
 Returns the vehicle of the given start/end index, and -1 if the given index is not a vehicle start/end. More...
 
int64 Next (const Assignment &assignment, int64 index) const
 Assignment inspection Returns the variable index of the node directly after the node corresponding to 'index' in 'assignment'. More...
 
bool IsVehicleUsed (const Assignment &assignment, int vehicle) const
 Returns true if the route of 'vehicle' is non empty in 'assignment'. More...
 
const std::vector< IntVar * > & Nexts () const
 Variables. More...
 
const std::vector< IntVar * > & VehicleVars () const
 Returns all vehicle variables of the model, such that VehicleVars(i) is the vehicle variable of the node corresponding to i. More...
 
IntVar * NextVar (int64 index) const
 Returns the next variable of the node corresponding to index. More...
 
IntVar * ActiveVar (int64 index) const
 Returns the active variable of the node corresponding to index. More...
 
IntVar * VehicleCostsConsideredVar (int vehicle) const
 Returns the variable specifying whether or not costs are considered for vehicle. More...
 
IntVar * VehicleVar (int64 index) const
 Returns the vehicle variable of the node corresponding to index. More...
 
IntVar * CostVar () const
 Returns the global cost variable which is being minimized. More...
 
int64 GetArcCostForVehicle (int64 from_index, int64 to_index, int64 vehicle) const
 Returns the cost of the transit arc between two nodes for a given vehicle. More...
 
bool CostsAreHomogeneousAcrossVehicles () const
 Whether costs are homogeneous across all vehicles. More...
 
int64 GetHomogeneousCost (int64 from_index, int64 to_index) const
 Returns the cost of the segment between two nodes supposing all vehicle costs are the same (returns the cost for the first vehicle otherwise). More...
 
int64 GetArcCostForFirstSolution (int64 from_index, int64 to_index) const
 Returns the cost of the arc in the context of the first solution strategy. More...
 
int64 GetArcCostForClass (int64 from_index, int64 to_index, int64 cost_class_index) const
 Returns the cost of the segment between two nodes for a given cost class. More...
 
CostClassIndex GetCostClassIndexOfVehicle (int64 vehicle) const
 Get the cost class index of the given vehicle. More...
 
bool HasVehicleWithCostClassIndex (CostClassIndex cost_class_index) const
 Returns true iff the model contains a vehicle with the given cost_class_index. More...
 
int GetCostClassesCount () const
 Returns the number of different cost classes in the model. More...
 
int GetNonZeroCostClassesCount () const
 Ditto, minus the 'always zero', built-in cost class. More...
 
VehicleClassIndex GetVehicleClassIndexOfVehicle (int64 vehicle) const
 
int GetVehicleClassesCount () const
 Returns the number of different vehicle classes in the model. More...
 
const std::vector< int > & GetSameVehicleIndicesOfIndex (int node) const
 Returns variable indices of nodes constrained to be on the same route. More...
 
bool ArcIsMoreConstrainedThanArc (int64 from, int64 to1, int64 to2)
 Returns whether the arc from->to1 is more constrained than from->to2, taking into account, in order: More...
 
std::string DebugOutputAssignment (const Assignment &solution_assignment, const std::string &dimension_to_print) const
 Print some debugging information about an assignment, including the feasible intervals of the CumulVar for dimension "dimension_to_print" at each step of the routes. More...
 
Solver * solver () const
 Returns the underlying constraint solver. More...
 
bool CheckLimit ()
 Returns true if the search limit has been crossed. More...
 
absl::Duration RemainingTime () const
 Returns the time left in the search limit. More...
 
int nodes () const
 Sizes and indices Returns the number of nodes in the model. More...
 
int vehicles () const
 Returns the number of vehicle routes in the model. More...
 
int64 Size () const
 Returns the number of next variables in the model. More...
 
int64 GetNumberOfDecisionsInFirstSolution (const RoutingSearchParameters &search_parameters) const
 Returns statistics on first solution search, number of decisions sent to filters, number of decisions rejected by filters. More...
 
int64 GetNumberOfRejectsInFirstSolution (const RoutingSearchParameters &search_parameters) const
 
bool IsMatchingModel () const
 Returns true if a vehicle/node matching problem is detected. More...
 
void SetTabuVarsCallback (GetTabuVarsCallback tabu_var_callback)
 
DecisionBuilder * MakeGuidedSlackFinalizer (const RoutingDimension *dimension, std::function< int64(int64)> initializer)
 The next few members are in the public section only for testing purposes. More...
 
static std::unique_ptr< LocalSearchOperator > MakeGreedyDescentLSOperator (std::vector< IntVar * > variables)
 
DecisionBuilder * MakeSelfDependentDimensionFinalizer (const RoutingDimension *dimension)
 MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a self-dependent dimension. More...
 

Macro Definition Documentation

◆ OR_TOOLS_CONSTRAINT_SOLVER_ROUTING_H_

#define OR_TOOLS_CONSTRAINT_SOLVER_ROUTING_H_

Typedef Documentation

◆ GetTabuVarsCallback

using GetTabuVarsCallback = std::function<std::vector<operations_research::IntVar*>(RoutingModel*)>

Sets the callback returning the variable to use for the Tabu Search metaheuristic.

Definition at line 1200 of file routing.h.

Function Documentation

◆ ActiveVar()

IntVar* ActiveVar ( int64  index) const

Returns the active variable of the node corresponding to index.

Definition at line 1068 of file routing.h.

◆ AddAtSolutionCallback()

void AddAtSolutionCallback ( std::function< void()>  callback)

Adds a callback called each time a solution is found during the search.

This is a shortcut to creating a monitor to call the callback on AtSolution() and adding it with AddSearchMonitor.

◆ AddHardTypeIncompatibility()

void AddHardTypeIncompatibility ( int  type1,
int  type2 
)

Incompatibilities: Two nodes with "hard" incompatible types cannot share the same route at all, while with a "temporal" incompatibility they can't be on the same route at the same time.

◆ AddIntervalToAssignment()

void AddIntervalToAssignment ( IntervalVar *const  interval)

◆ AddLocalSearchFilter()

void AddLocalSearchFilter ( LocalSearchFilter *  filter)

Adds a custom local search filter to the list of filters used to speed up local search by pruning unfeasible variable assignments.

Calling this method after the routing model has been closed (CloseModel() or Solve() has been called) has no effect. The routing model does not take ownership of the filter.

Definition at line 1029 of file routing.h.

◆ AddLocalSearchOperator()

void AddLocalSearchOperator ( LocalSearchOperator *  ls_operator)

Adds a local search operator to the set of operators used to solve the vehicle routing problem.

◆ AddSameVehicleRequiredTypeAlternatives()

void AddSameVehicleRequiredTypeAlternatives ( int  dependent_type,
absl::flat_hash_set< int >  required_type_alternatives 
)

Requirements:

Note
As of 2019-04, cycles in the requirement graph are not supported, and lead to the dependent nodes being skipped if possible (otherwise the model is considered infeasible). The following functions specify that "dependent_type" requires at least one of the types in "required_type_alternatives".

For same-vehicle requirements, a node of dependent type type_D requires at least one node of type type_R among the required alternatives on the same route.

◆ AddSearchMonitor()

void AddSearchMonitor ( SearchMonitor *const  monitor)

Adds a search monitor to the search used to solve the routing model.

◆ AddTemporalRequiredTypeAlternatives()

void AddTemporalRequiredTypeAlternatives ( int  dependent_type,
absl::flat_hash_set< int >  required_type_alternatives 
)

If type_D temporally depends on type_R, any non-delivery node_D of type_D requires at least one non-delivered node of type_R on its vehicle at the time node_D is visited.

◆ AddTemporalTypeIncompatibility()

void AddTemporalTypeIncompatibility ( int  type1,
int  type2 
)

◆ AddToAssignment()

void AddToAssignment ( IntVar *const  var)

Adds an extra variable to the vehicle routing assignment.

◆ AddVariableMaximizedByFinalizer()

void AddVariableMaximizedByFinalizer ( IntVar *  var)

Adds a variable to maximize in the solution finalizer (see above for information on the solution finalizer).

◆ AddVariableMinimizedByFinalizer()

void AddVariableMinimizedByFinalizer ( IntVar *  var)

Adds a variable to minimize in the solution finalizer.

The solution finalizer is called each time a solution is found during the search and allows to instantiate secondary variables (such as dimension cumul variables).

◆ ApplyLocks()

IntVar* ApplyLocks ( const std::vector< int64 > &  locks)

Applies a lock chain to the next search.

'locks' represents an ordered vector of nodes representing a partial route which will be fixed during the next search; it will constrain next variables such that: next[locks[i]] == locks[i+1]. Returns the next variable at the end of the locked chain; this variable is not locked. An assignment containing the locks can be obtained by calling PreAssignment().

◆ ApplyLocksToAllVehicles()

bool ApplyLocksToAllVehicles ( const std::vector< std::vector< int64 >> &  locks,
bool  close_routes 
)

Applies lock chains to all vehicles to the next search, such that locks[p] is the lock chain for route p.

Returns false if the locks do not contain valid routes; expects that the routes do not contain the depots, i.e. there are empty vectors in place of empty routes. If close_routes is set to true, adds the end nodes to the route of each vehicle and deactivates other nodes. An assignment containing the locks can be obtained by calling PreAssignment().

◆ ArcIsMoreConstrainedThanArc()

bool ArcIsMoreConstrainedThanArc ( int64  from,
int64  to1,
int64  to2 
)

Returns whether the arc from->to1 is more constrained than from->to2, taking into account, in order:

  • whether the destination node isn't an end node
  • whether the destination node is mandatory
  • whether the destination node is bound to the same vehicle as the source
  • the "primary constrained" dimension (see SetPrimaryConstrainedDimension) It then breaks ties using, in order:
  • the arc cost (taking unperformed penalties into account)
  • the size of the vehicle vars of "to1" and "to2" (lowest size wins)
  • the value: the lowest value of the indices to1 and to2 wins. See the .cc for details. The more constrained arc is typically preferable when building a first solution. This method is intended to be used as a callback for the BestValueByComparisonSelector value selector. Args: from: the variable index of the source node to1: the variable index of the first candidate destination node. to2: the variable index of the second candidate destination node.

◆ AreEmptyRouteCostsConsideredForVehicle()

bool AreEmptyRouteCostsConsideredForVehicle ( int  vehicle) const

Definition at line 831 of file routing.h.

◆ AssignmentToRoutes()

void AssignmentToRoutes ( const Assignment &  assignment,
std::vector< std::vector< int64 >> *const  routes 
) const

Converts the solution in the given assignment to routes for all vehicles.

Expects that assignment contains a valid solution (i.e. routes for all vehicles end with an end index for that vehicle).

◆ CheckLimit()

bool CheckLimit ( )

Returns true if the search limit has been crossed.

Definition at line 1167 of file routing.h.

◆ CloseModel()

void CloseModel ( )

Closes the current routing model; after this method is called, no modification to the model can be done, but RoutesToAssignment becomes available.

Note that CloseModel() is automatically called by Solve() and other methods that produce solution. This is equivalent to calling CloseModelWithParameters(DefaultRoutingSearchParameters()).

◆ CloseModelWithParameters()

void CloseModelWithParameters ( const RoutingSearchParameters &  search_parameters)

Same as above taking search parameters (as of 10/2015 some the parameters have to be set when closing the model).

◆ CloseVisitTypes()

void CloseVisitTypes ( )

This function should be called once all node visit types have been set and prior to adding any incompatibilities/requirements.

Todo:
(user): Reconsider the logic and potentially remove the need to "close" types.

◆ CompactAndCheckAssignment()

Assignment* CompactAndCheckAssignment ( const Assignment &  assignment) const

Same as CompactAssignment() but also checks the validity of the final compact solution; if it is not valid, no attempts to repair it are made (instead, the method returns nullptr).

◆ CompactAssignment()

Assignment* CompactAssignment ( const Assignment &  assignment) const

Returns a compacted version of the given assignment, in which all vehicles with id lower or equal to some N have non-empty routes, and all vehicles with id greater than N have empty routes.

Does not take ownership of the returned object. If found, the cost of the compact assignment is the same as in the original assignment and it preserves the values of 'active' variables. Returns nullptr if a compact assignment was not found. This method only works in homogenous mode, and it only swaps equivalent vehicles (vehicles with the same start and end nodes). When creating the compact assignment, the empty plan is replaced by the route assigned to the compatible vehicle with the highest id. Note that with more complex constraints on vehicle variables, this method might fail even if a compact solution exists. This method changes the vehicle and dimension variables as necessary. While compacting the solution, only basic checks on vehicle variables are performed; if one of these checks fails no attempts to repair it are made (instead, the method returns nullptr).

◆ ComputeLowerBound()

int64 ComputeLowerBound ( )

Computes a lower bound to the routing problem solving a linear assignment problem.

The routing model must be closed before calling this method.

Note
problems with node disjunction constraints (including optional nodes) and non-homogenous costs are not supported (the method returns 0 in these cases).
Todo:
(user): Add support for non-homogeneous costs and disjunctions.

◆ ConsiderEmptyRouteCostsForVehicle()

void ConsiderEmptyRouteCostsForVehicle ( bool  consider_costs,
int  vehicle 
)

Definition at line 826 of file routing.h.

◆ CostsAreHomogeneousAcrossVehicles()

bool CostsAreHomogeneousAcrossVehicles ( ) const

Whether costs are homogeneous across all vehicles.

Definition at line 1085 of file routing.h.

◆ CostVar()

IntVar* CostVar ( ) const

Returns the global cost variable which is being minimized.

Definition at line 1078 of file routing.h.

◆ DebugOutputAssignment()

std::string DebugOutputAssignment ( const Assignment &  solution_assignment,
const std::string &  dimension_to_print 
) const

Print some debugging information about an assignment, including the feasible intervals of the CumulVar for dimension "dimension_to_print" at each step of the routes.

If "dimension_to_print" is omitted, all dimensions will be printed.

◆ End()

int64 End ( int  vehicle) const

Returns the variable index of the ending node of a vehicle route.

Definition at line 1041 of file routing.h.

◆ first_solution_evaluator()

const Solver::IndexEvaluator2& first_solution_evaluator ( ) const

Search Gets/sets the evaluator used during the search.

Only relevant when RoutingSearchParameters.first_solution_strategy = EVALUATOR_STRATEGY.

Definition at line 840 of file routing.h.

◆ GetAmortizedLinearCostFactorOfVehicles()

const std::vector<int64>& GetAmortizedLinearCostFactorOfVehicles ( ) const

Definition at line 819 of file routing.h.

◆ GetAmortizedQuadraticCostFactorOfVehicles()

const std::vector<int64>& GetAmortizedQuadraticCostFactorOfVehicles ( ) const

Definition at line 822 of file routing.h.

◆ GetArcCostForClass()

int64 GetArcCostForClass ( int64  from_index,
int64  to_index,
int64  cost_class_index 
) const

Returns the cost of the segment between two nodes for a given cost class.

Input are variable indices of nodes and the cost class. Unlike GetArcCostForVehicle(), if cost_class is kNoCost, then the returned cost won't necessarily be zero: only some of the components of the cost that depend on the cost class will be omited. See the code for details.

◆ GetArcCostForFirstSolution()

int64 GetArcCostForFirstSolution ( int64  from_index,
int64  to_index 
) const

Returns the cost of the arc in the context of the first solution strategy.

This is typically a simplification of the actual cost; see the .cc.

◆ GetArcCostForVehicle()

int64 GetArcCostForVehicle ( int64  from_index,
int64  to_index,
int64  vehicle 
) const

Returns the cost of the transit arc between two nodes for a given vehicle.

Input are variable indices of node. This returns 0 if vehicle < 0.

◆ GetCostClassesCount()

int GetCostClassesCount ( ) const

Returns the number of different cost classes in the model.

Definition at line 1119 of file routing.h.

◆ GetCostClassIndexOfVehicle()

CostClassIndex GetCostClassIndexOfVehicle ( int64  vehicle) const

Get the cost class index of the given vehicle.

Definition at line 1105 of file routing.h.

◆ GetDepot()

int64 GetDepot ( ) const

Returns the variable index of the first starting or ending node of all routes.

If all routes start and end at the same node (single depot), this is the node returned.

◆ GetFixedCostOfVehicle()

int64 GetFixedCostOfVehicle ( int  vehicle) const

Returns the route fixed cost taken into account if the route of the vehicle is not empty, aka there's at least one node on the route other than the first and last nodes.

◆ GetHardTypeIncompatibilitiesOfType()

const absl::flat_hash_set<int>& GetHardTypeIncompatibilitiesOfType ( int  type) const

Returns visit types incompatible with a given type.

◆ GetHomogeneousCost()

int64 GetHomogeneousCost ( int64  from_index,
int64  to_index 
) const

Returns the cost of the segment between two nodes supposing all vehicle costs are the same (returns the cost for the first vehicle otherwise).

Definition at line 1090 of file routing.h.

◆ GetNonZeroCostClassesCount()

int GetNonZeroCostClassesCount ( ) const

Ditto, minus the 'always zero', built-in cost class.

Definition at line 1121 of file routing.h.

◆ GetNumberOfDecisionsInFirstSolution()

int64 GetNumberOfDecisionsInFirstSolution ( const RoutingSearchParameters &  search_parameters) const

Returns statistics on first solution search, number of decisions sent to filters, number of decisions rejected by filters.

◆ GetNumberOfRejectsInFirstSolution()

int64 GetNumberOfRejectsInFirstSolution ( const RoutingSearchParameters &  search_parameters) const

◆ GetNumberOfVisitTypes()

int GetNumberOfVisitTypes ( ) const

Definition at line 706 of file routing.h.

◆ GetSameVehicleIndicesOfIndex()

const std::vector<int>& GetSameVehicleIndicesOfIndex ( int  node) const

Returns variable indices of nodes constrained to be on the same route.

Definition at line 1131 of file routing.h.

◆ GetSameVehicleRequiredTypeAlternativesOfType()

const std::vector<absl::flat_hash_set<int> >& GetSameVehicleRequiredTypeAlternativesOfType ( int  type) const

clang-format off Returns the sets of same-vehicle/temporal requirement alternatives for the given type.

◆ GetTemporalRequiredTypeAlternativesOfType()

const std::vector<absl::flat_hash_set<int> >& GetTemporalRequiredTypeAlternativesOfType ( int  type) const

◆ GetTemporalTypeIncompatibilitiesOfType()

const absl::flat_hash_set<int>& GetTemporalTypeIncompatibilitiesOfType ( int  type) const

◆ GetVehicleClassesCount()

int GetVehicleClassesCount ( ) const

Returns the number of different vehicle classes in the model.

Definition at line 1129 of file routing.h.

◆ GetVehicleClassIndexOfVehicle()

VehicleClassIndex GetVehicleClassIndexOfVehicle ( int64  vehicle) const

Definition at line 1124 of file routing.h.

◆ GetVisitType()

routing_no_lns (default: false) int GetVisitType ( int64  index) const

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.

You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. The vehicle routing library lets one model and solve generic vehicle routing problems ranging from the Traveling Salesman Problem to more complex problems such as the Capacitated Vehicle Routing Problem with Time Windows.

The objective of a vehicle routing problem is to build routes covering a set of nodes minimizing the overall cost of the routes (usually proportional to the sum of the lengths of each segment of the routes) while respecting some problem-specific constraints (such as the length of a route). A route is equivalent to a path connecting nodes, starting/ending at specific starting/ending nodes.

The term "vehicle routing" is historical and the category of problems solved is not limited to the routing of vehicles: any problem involving finding routes visiting a given number of nodes optimally falls under this category of problems, such as finding the optimal sequence in a playlist. The literature around vehicle routing problems is extremely dense but one can find some basic introductions in the following links:

The vehicle routing library is a vertical layer above the constraint programming library (ortools/constraint_programming:cp). One has access to all underlying constrained variables of the vehicle routing model which can therefore be enriched by adding any constraint available in the constraint programming library.

There are two sets of variables available:

  • path variables:
    • "next(i)" variables representing the immediate successor of the node corresponding to i; use IndexToNode() to get the node corresponding to a "next" variable value; note that node indices are strongly typed integers (cf. ortools/base/int_type.h);
    • "vehicle(i)" variables representing the vehicle route to which the node corresponding to i belongs;
    • "active(i)" boolean variables, true if the node corresponding to i is visited and false if not; this can be false when nodes are either optional or part of a disjunction;
    • The following relationships hold for all i: active(i) == 0 <=> next(i) == i <=> vehicle(i) == -1, next(i) == j => vehicle(j) == vehicle(i).
  • dimension variables, used when one is accumulating quantities along routes, such as weight or volume carried, distance or time:
    • "cumul(i,d)" variables representing the quantity of dimension d when arriving at the node corresponding to i;
    • "transit(i,d)" variables representing the quantity of dimension d added after visiting the node corresponding to i.
    • The following relationship holds for all (i,d): next(i) == j => cumul(j,d) == cumul(i,d) + transit(i,d). Solving the vehicle routing problems is mainly done using approximate methods (namely local search, cf. http://en.wikipedia.org/wiki/Local_search_(optimization) ), potentially combined with exact techniques based on dynamic programming and exhaustive tree search.
      Todo:
      (user): Add a section on costs (vehicle arc costs, span costs, disjunctions costs).

Advanced tips: Flags are available to tune the search used to solve routing problems. Here is a quick overview of the ones one might want to modify:

  • Limiting the search for solutions:
    • routing_solution_limit (default: kint64max): stop the search after finding 'routing_solution_limit' improving solutions;
    • routing_time_limit (default: kint64max): stop the search after 'routing_time_limit' milliseconds;
  • Customizing search:
    • routing_first_solution (default: select the first node with an unbound successor and connect it to the first available node): selects the heuristic to build a first solution which will then be improved by local search; possible values are GlobalCheapestArc (iteratively connect two nodes which produce the cheapest route segment), LocalCheapestArc (select the first node with an unbound successor and connect it to the node which produces the cheapest route segment), PathCheapestArc (starting from a route "start" node, connect it to the node which produces the cheapest route segment, then extend the route by iterating on the last node added to the route).
    • Local search neighborhoods: Search (LNS); LNS can find good solutions but is usually very slow. Refer to the description of PATHLNS in the LocalSearchOperators enum in constraint_solver.h for more information. solve "sub"-traveling salesman problems (TSPs) of the current model (such as sub-parts of a route, or one route in a multiple route problem). Uses dynamic programming to solve such TSPs with a maximum size (in number of nodes) up to cp_local_search_tsp_opt_size (flag with a default value of 13 nodes). It is not activated by default because it can slow down the search.
  • Meta-heuristics: used to guide the search out of local minima found by local search. Note that, in general, a search with metaheuristics activated never stops, therefore one must specify a search limit. Several types of metaheuristics are provided: search (cf. http://en.wikipedia.org/wiki/Guided_Local_Search); this is generally the most efficient metaheuristic for vehicle routing; accordingly.
    Note
    These incompatibilities and requirements are only handled when each node index appears in at most one pickup/delivery pair, i.e. when the same node isn't a pickup and/or delivery in multiple pickup/delivery pairs.
    Todo:
    (user): Support multiple visit types per node?

◆ HasHardTypeIncompatibilities()

bool HasHardTypeIncompatibilities ( ) const

Returns true iff any hard (resp.

temporal) type incompatibilities have been added to the model.

Definition at line 720 of file routing.h.

◆ HasSameVehicleTypeRequirements()

bool HasSameVehicleTypeRequirements ( ) const

clang-format on Returns true iff any same-route (resp.

temporal) type requirements have been added to the model.

Definition at line 753 of file routing.h.

◆ HasTemporalTypeIncompatibilities()

bool HasTemporalTypeIncompatibilities ( ) const

Definition at line 723 of file routing.h.

◆ HasTemporalTypeRequirements()

bool HasTemporalTypeRequirements ( ) const

Definition at line 756 of file routing.h.

◆ HasTypeRegulations()

bool HasTypeRegulations ( ) const

Returns true iff the model has any incompatibilities or requirements set on node types.

Definition at line 762 of file routing.h.

◆ HasVehicleWithCostClassIndex()

bool HasVehicleWithCostClassIndex ( CostClassIndex  cost_class_index) const

Returns true iff the model contains a vehicle with the given cost_class_index.

Definition at line 1111 of file routing.h.

◆ IsEnd()

bool IsEnd ( int64  index) const

Returns true if 'index' represents the last node of a route.

Definition at line 1045 of file routing.h.

◆ IsMatchingModel()

bool IsMatchingModel ( ) const

Returns true if a vehicle/node matching problem is detected.

◆ IsStart()

bool IsStart ( int64  index) const

Returns true if 'index' represents the first node of a route.

◆ IsVehicleUsed()

bool IsVehicleUsed ( const Assignment &  assignment,
int  vehicle 
) const

Returns true if the route of 'vehicle' is non empty in 'assignment'.

◆ MakeGreedyDescentLSOperator()

static std::unique_ptr<LocalSearchOperator> MakeGreedyDescentLSOperator ( std::vector< IntVar * >  variables)
static
Todo:
(user): MakeGreedyDescentLSOperator is too general for routing.h.

Perhaps move it to constraint_solver.h. MakeGreedyDescentLSOperator creates a local search operator that tries to improve the initial assignment by moving a logarithmically decreasing step away in each possible dimension.

◆ MakeGuidedSlackFinalizer()

DecisionBuilder* MakeGuidedSlackFinalizer ( const RoutingDimension dimension,
std::function< int64(int64)>  initializer 
)

The next few members are in the public section only for testing purposes.

Todo:
(user): Find a way to test and restrict the access at the same time.

MakeGuidedSlackFinalizer creates a DecisionBuilder for the slacks of a dimension using a callback to choose which values to start with. The finalizer works only when all next variables in the model have been fixed. It has the following two characteristics:

  1. It follows the routes defined by the nexts variables when choosing a variable to make a decision on.
  2. When it comes to choose a value for the slack of node i, the decision builder first calls the callback with argument i, and supposingly the returned value is x it creates decisions slack[i] = x, slack[i] = x + 1, slack[i] = x - 1, slack[i] = x + 2, etc.

◆ MakeSelfDependentDimensionFinalizer()

DecisionBuilder* MakeSelfDependentDimensionFinalizer ( const RoutingDimension dimension)

MakeSelfDependentDimensionFinalizer is a finalizer for the slacks of a self-dependent dimension.

It makes an extensive use of the caches of the state dependent transits. In detail, MakeSelfDependentDimensionFinalizer returns a composition of a local search decision builder with a greedy descent operator for the cumul of the start of each route and a guided slack finalizer. Provided there are no time windows and the maximum slacks are large enough, once the cumul of the start of route is fixed, the guided finalizer can find optimal values of the slacks for the rest of the route in time proportional to the length of the route. Therefore the composed finalizer generally works in time O(log(t)*n*m), where t is the latest possible departute time, n is the number of nodes in the network and m is the number of vehicles.

◆ MutablePreAssignment()

Assignment* MutablePreAssignment ( )

Definition at line 936 of file routing.h.

◆ Next()

int64 Next ( const Assignment &  assignment,
int64  index 
) const

Assignment inspection Returns the variable index of the node directly after the node corresponding to 'index' in 'assignment'.

◆ Nexts()

const std::vector<IntVar*>& Nexts ( ) const

Variables.

Returns all next variables of the model, such that Nexts(i) is the next variable of the node corresponding to i.

Definition at line 1059 of file routing.h.

◆ NextVar()

IntVar* NextVar ( int64  index) const

Returns the next variable of the node corresponding to index.

Note that NextVar(index) == index is equivalent to ActiveVar(index) == 0.

Definition at line 1066 of file routing.h.

◆ nodes()

int nodes ( ) const

Sizes and indices Returns the number of nodes in the model.

Definition at line 1180 of file routing.h.

◆ PackCumulsOfOptimizerDimensionsFromAssignment()

const Assignment* PackCumulsOfOptimizerDimensionsFromAssignment ( const Assignment *  original_assignment,
absl::Duration  duration_limit 
)

For every dimension in the model's dimensions_for_local/global_optimizer_, this method tries to pack the cumul values of the dimension, such that:

  • The cumul costs (span costs, soft lower and upper bound costs, etc) are minimized.
  • The cumuls of the ends of the routes are minimized for this given minimal cumul cost.
  • Given these minimal end cumuls, the route start cumuls are maximized. Returns the assignment resulting from allocating these packed cumuls with the solver, and nullptr if these cumuls could not be set by the solver.

◆ PreAssignment()

const Assignment* const PreAssignment ( ) const

Returns an assignment used to fix some of the variables of the problem.

In practice, this assignment locks partial routes of the problem. This can be used in the context of locking the parts of the routes which have already been driven in online routing problems.

Definition at line 935 of file routing.h.

◆ ReadAssignment()

Assignment* ReadAssignment ( const std::string &  file_name)

Reads an assignment from a file and returns the current solution.

Returns nullptr if the file cannot be opened or if the assignment is not valid.

◆ ReadAssignmentFromRoutes()

Assignment* ReadAssignmentFromRoutes ( const std::vector< std::vector< int64 >> &  routes,
bool  ignore_inactive_indices 
)

Restores the routes as the current solution.

Returns nullptr if the solution cannot be restored (routes do not contain a valid solution). Note that calling this method will run the solver to assign values to the dimension variables; this may take considerable amount of time, especially when using dimensions with slack.

◆ RemainingTime()

absl::Duration RemainingTime ( ) const

Returns the time left in the search limit.

Definition at line 1173 of file routing.h.

◆ RestoreAssignment()

Assignment* RestoreAssignment ( const Assignment &  solution)

Restores an assignment as a solution in the routing model and returns the new solution.

Returns nullptr if the assignment is not valid.

◆ RoutesToAssignment()

bool RoutesToAssignment ( const std::vector< std::vector< int64 >> &  routes,
bool  ignore_inactive_indices,
bool  close_routes,
Assignment *const  assignment 
) const

Fills an assignment from a specification of the routes of the vehicles.

The routes are specified as lists of variable indices that appear on the routes of the vehicles. The indices of the outer vector in 'routes' correspond to vehicles IDs, the inner vector contains the variable indices on the routes for the given vehicle. The inner vectors must not contain the start and end indices, as these are determined by the routing model. Sets the value of NextVars in the assignment, adding the variables to the assignment if necessary. The method does not touch other variables in the assignment. The method can only be called after the model is closed. With ignore_inactive_indices set to false, this method will fail (return nullptr) in case some of the route contain indices that are deactivated in the model; when set to true, these indices will be skipped. Returns true if routes were successfully loaded. However, such assignment still might not be a valid solution to the routing problem due to more complex constraints; it is advisible to call solver()->CheckSolution() afterwards.

◆ SetAmortizedCostFactorsOfAllVehicles()

quadratic_cost_factor_of_vehicle_* [v] square of length of route v void SetAmortizedCostFactorsOfAllVehicles ( int64  linear_cost_factor,
int64  quadratic_cost_factor 
)

The following methods set the linear and quadratic cost factors of vehicles (must be positive values).

The default value of these parameters is zero for all vehicles. When set, the cost_ of the model will contain terms aiming at reducing the number of vehicles used in the model, by adding the following to the objective for every vehicle v: INDICATOR(v used in the model) * [linear_cost_factor_of_vehicle_[v] i.e. for every used vehicle, we add the linear factor as fixed cost, and subtract the square of the route length multiplied by the quadratic factor. This second term aims at making the routes as dense as possible.

Sets the linear and quadratic cost factor of all vehicles.

◆ SetAmortizedCostFactorsOfVehicle()

void SetAmortizedCostFactorsOfVehicle ( int64  linear_cost_factor,
int64  quadratic_cost_factor,
int  vehicle 
)

Sets the linear and quadratic cost factor of the given vehicle.

◆ SetArcCostEvaluatorOfAllVehicles()

void SetArcCostEvaluatorOfAllVehicles ( int  evaluator_index)

Sets the cost function of the model such that the cost of a segment of a route between node 'from' and 'to' is evaluator(from, to), whatever the route or vehicle performing the route.

◆ SetArcCostEvaluatorOfVehicle()

void SetArcCostEvaluatorOfVehicle ( int  evaluator_index,
int  vehicle 
)

Sets the cost function for a given vehicle route.

◆ SetAssignmentFromOtherModelAssignment()

void SetAssignmentFromOtherModelAssignment ( Assignment *  target_assignment,
const RoutingModel *  source_model,
const Assignment *  source_assignment 
)

Given a "source_model" and its "source_assignment", resets "target_assignment" with the IntVar variables (nexts_, and vehicle_vars_ if costs aren't homogeneous across vehicles) of "this" model, with the values set according to those in "other_assignment".

The objective_element of target_assignment is set to this->cost_.

◆ SetFirstSolutionEvaluator()

void SetFirstSolutionEvaluator ( Solver::IndexEvaluator2  evaluator)

Takes ownership of evaluator.

Definition at line 845 of file routing.h.

◆ SetFixedCostOfAllVehicles()

void SetFixedCostOfAllVehicles ( int64  cost)

Sets the fixed cost of all vehicle routes.

It is equivalent to calling SetFixedCostOfVehicle on all vehicle routes.

◆ SetFixedCostOfVehicle()

void SetFixedCostOfVehicle ( int64  cost,
int  vehicle 
)

Sets the fixed cost of one vehicle route.

◆ SetSweepArranger()

void SetSweepArranger ( SweepArranger *  sweep_arranger)
Todo:
(user): Revisit if coordinates are added to the RoutingModel class.

Definition at line 1018 of file routing.h.

◆ SetTabuVarsCallback()

void SetTabuVarsCallback ( GetTabuVarsCallback  tabu_var_callback)

◆ Size()

int64 Size ( ) const

Returns the number of next variables in the model.

Definition at line 1184 of file routing.h.

◆ Solve()

const Assignment* Solve ( const Assignment *  assignment = nullptr)

Solves the current routing model; closes the current model.

This is equivalent to calling SolveWithParameters(DefaultRoutingSearchParameters()) or SolveFromAssignmentWithParameters(assignment, DefaultRoutingSearchParameters()).

◆ SolveFromAssignmentWithParameters()

const Assignment* SolveFromAssignmentWithParameters ( const Assignment *  assignment,
const RoutingSearchParameters &  search_parameters,
std::vector< const Assignment * > *  solutions = nullptr 
)

◆ solver()

Solver* solver ( ) const

Returns the underlying constraint solver.

Can be used to add extra constraints and/or modify search algoithms.

Definition at line 1164 of file routing.h.

◆ SolveWithParameters()

const Assignment* SolveWithParameters ( const RoutingSearchParameters &  search_parameters,
std::vector< const Assignment * > *  solutions = nullptr 
)

Solves the current routing model with the given parameters.

If 'solutions' is specified, it will contain the k best solutions found during the search (from worst to best, including the one returned by this method), where k corresponds to the 'number_of_solutions_to_collect' in 'search_parameters'.

Note
the Assignment returned by the method and the ones in solutions are owned by the underlying solver and should not be deleted.

◆ Start()

int64 Start ( int  vehicle) const

Model inspection.

Returns the variable index of the starting node of a vehicle route.

Definition at line 1039 of file routing.h.

◆ status()

Status status ( ) const

Returns the current status of the routing model.

Definition at line 912 of file routing.h.

◆ sweep_arranger()

SweepArranger* sweep_arranger ( ) const

Returns the sweep arranger to be used by routing heuristics.

Definition at line 1022 of file routing.h.

◆ UnperformedPenalty()

int64 UnperformedPenalty ( int64  var_index) const

Get the "unperformed" penalty of a node.

This is only well defined if the node is only part of a single Disjunction involving only itself, and that disjunction has a penalty. In all other cases, including forced active nodes, this returns 0.

◆ UnperformedPenaltyOrValue()

int64 UnperformedPenaltyOrValue ( int64  default_value,
int64  var_index 
) const

Same as above except that it returns default_value instead of 0 when penalty is not well defined (default value is passed as first argument to simplify the usage of the method in a callback).

◆ VehicleCostsConsideredVar()

IntVar* VehicleCostsConsideredVar ( int  vehicle) const

Returns the variable specifying whether or not costs are considered for vehicle.

Definition at line 1071 of file routing.h.

◆ VehicleIndex()

int VehicleIndex ( int  index) const

Returns the vehicle of the given start/end index, and -1 if the given index is not a vehicle start/end.

Definition at line 1048 of file routing.h.

◆ vehicles()

int vehicles ( ) const

Returns the number of vehicle routes in the model.

Definition at line 1182 of file routing.h.

◆ VehicleVar()

IntVar* VehicleVar ( int64  index) const

Returns the vehicle variable of the node corresponding to index.

Note that VehicleVar(index) == -1 is equivalent to ActiveVar(index) == 0.

Definition at line 1076 of file routing.h.

◆ VehicleVars()

const std::vector<IntVar*>& VehicleVars ( ) const

Returns all vehicle variables of the model, such that VehicleVars(i) is the vehicle variable of the node corresponding to i.

Definition at line 1062 of file routing.h.

◆ WriteAssignment()

bool WriteAssignment ( const std::string &  file_name) const

Writes the current solution to a file containing an AssignmentProto.

Returns false if the file cannot be opened or if there is no current solution.