OR-Tools  9.6
cvrptw_with_precedences.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 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 //
15 // Capacitated Vehicle Routing Problem with Time Windows (and optional orders).
16 // A description of the problem can be found here:
17 // http://en.wikipedia.org/wiki/Vehicle_routing_problem.
18 // The variant which is tackled by this model includes a capacity dimension,
19 // time windows and optional orders, with a penalty cost if orders are not
20 // performed. For the sake of simplicty, orders are randomly located and
21 // distances are computed using the Manhattan distance. Distances are assumed
22 // to be in meters and times in seconds.
23 
24 #include <cstdint>
25 #include <random>
26 #include <utility>
27 #include <vector>
28 
29 #include "absl/random/random.h"
30 #include "google/protobuf/text_format.h"
34 #include "ortools/base/logging.h"
38 #include "ortools/constraint_solver/routing_parameters.pb.h"
39 #include "ortools/graph/graph_builder.h"
41 
50 using operations_research::RoutingNodeIndex;
51 using operations_research::RoutingSearchParameters;
53 
54 ABSL_FLAG(int, vrp_orders, 100, "Nodes in the problem.");
55 ABSL_FLAG(int, vrp_vehicles, 20,
56  "Size of Traveling Salesman Problem instance.");
57 ABSL_FLAG(bool, vrp_use_deterministic_random_seed, false,
58  "Use deterministic random seeds.");
59 ABSL_FLAG(bool, vrp_use_same_vehicle_costs, false,
60  "Use same vehicle costs in the routing model");
61 ABSL_FLAG(std::string, routing_search_parameters, "",
62  "Text proto RoutingSearchParameters (possibly partial) that will "
63  "override the DefaultRoutingSearchParameters()");
64 ABSL_FLAG(int, vrp_precedences, 5,
65  "Number of precedence indices. Precedences will be chosen "
66  "randomly with the constraint that they don't form cycles.");
67 ABSL_FLAG(int64_t, vrp_precedence_offset, 100,
68  "The offset that applies to the precedences. For each pair linked "
69  "by a precedence constraint, pair.second can only start after the "
70  "start of pair.first + offset.");
71 
72 const char* kTime = "Time";
73 const char* kCapacity = "Capacity";
74 const int64_t kMaxNodesPerGroup = 10;
75 const int64_t kSameVehicleCost = 1000;
76 
77 int main(int argc, char** argv) {
78  InitGoogle(argv[0], &argc, &argv, true);
79  CHECK_LT(0, absl::GetFlag(FLAGS_vrp_orders))
80  << "Specify an instance size greater than 0.";
81  CHECK_LT(0, absl::GetFlag(FLAGS_vrp_vehicles))
82  << "Specify a non-null vehicle fleet size.";
83  // VRP of size absl::GetFlag(FLAGS_vrp_size).
84  // Nodes are indexed from 0 to absl::GetFlag(FLAGS_vrp_orders), the starts and
85  // ends of the routes are at node 0.
86  const RoutingIndexManager::NodeIndex kDepot(0);
87  RoutingIndexManager manager(absl::GetFlag(FLAGS_vrp_orders) + 1,
88  absl::GetFlag(FLAGS_vrp_vehicles), kDepot);
89  RoutingModel routing(manager);
90 
91  // Setting up locations.
92  const int64_t kXMax = 100000;
93  const int64_t kYMax = 100000;
94  const int64_t kSpeed = 10;
95  LocationContainer locations(
96  kSpeed, absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed));
97  for (int location = 0; location <= absl::GetFlag(FLAGS_vrp_orders);
98  ++location) {
99  locations.AddRandomLocation(kXMax, kYMax);
100  }
101 
102  // Setting the cost function.
103  const int vehicle_cost = routing.RegisterTransitCallback(
104  [&locations, &manager](int64_t i, int64_t j) {
105  return locations.ManhattanDistance(manager.IndexToNode(i),
106  manager.IndexToNode(j));
107  });
108  routing.SetArcCostEvaluatorOfAllVehicles(vehicle_cost);
109 
110  // Adding capacity dimension constraints.
111  const int64_t kVehicleCapacity = 40;
112  const int64_t kNullCapacitySlack = 0;
113  RandomDemand demand(manager.num_nodes(), kDepot,
114  absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed));
115  demand.Initialize();
116  routing.AddDimension(routing.RegisterTransitCallback(
117  [&demand, &manager](int64_t i, int64_t j) {
118  return demand.Demand(manager.IndexToNode(i),
119  manager.IndexToNode(j));
120  }),
121  kNullCapacitySlack, kVehicleCapacity,
122  /*fix_start_cumul_to_zero=*/true, kCapacity);
123 
124  // Adding time dimension constraints.
125  const int64_t kTimePerDemandUnit = 300;
126  const int64_t kHorizon = 24 * 3600;
128  kTimePerDemandUnit,
129  [&demand](RoutingNodeIndex i, RoutingNodeIndex j) {
130  return demand.Demand(i, j);
131  },
132  [&locations](RoutingNodeIndex i, RoutingNodeIndex j) {
133  return locations.ManhattanTime(i, j);
134  });
135  routing.AddDimension(
136  routing.RegisterTransitCallback([&time, &manager](int64_t i, int64_t j) {
137  return time.Compute(manager.IndexToNode(i), manager.IndexToNode(j));
138  }),
139  kHorizon, kHorizon, /*fix_start_cumul_to_zero=*/true, kTime);
140  RoutingDimension* time_dimension = routing.GetMutableDimension(kTime);
141 
142  // Adding time windows.
143  std::mt19937 randomizer(
144  GetSeed(absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed)));
145  const int64_t kTWDuration = 5 * 3600;
146  for (int order = 1; order < manager.num_nodes(); ++order) {
147  const int64_t start =
148  absl::Uniform<int32_t>(randomizer, 0, kHorizon - kTWDuration);
149  time_dimension->CumulVar(order)->SetRange(start, start + kTWDuration);
150  }
151 
152  // Adding penalty costs to allow skipping orders.
153  const int64_t kPenalty = 10000000;
154  const RoutingIndexManager::NodeIndex kFirstNodeAfterDepot(1);
155  for (RoutingIndexManager::NodeIndex order = kFirstNodeAfterDepot;
156  order < manager.num_nodes(); ++order) {
157  std::vector<int64_t> orders(1, manager.NodeToIndex(order));
158  routing.AddDisjunction(orders, kPenalty);
159  }
160 
161  // Adding same vehicle constraint costs for consecutive nodes.
162  if (absl::GetFlag(FLAGS_vrp_use_same_vehicle_costs)) {
163  std::vector<int64_t> group;
164  for (RoutingIndexManager::NodeIndex order = kFirstNodeAfterDepot;
165  order < manager.num_nodes(); ++order) {
166  group.push_back(manager.NodeToIndex(order));
167  if (group.size() == kMaxNodesPerGroup) {
169  group.clear();
170  }
171  }
172  if (!group.empty()) {
174  }
175  }
176 
177  // If the flag is > 0, we create a DAG with random edges representing
178  // precedences. If it is not possible to meet the precedence constraints, for
179  // instance if the generated time window are incompatible, we expect one of
180  // the underlying orders to be skipped.
181  if (absl::GetFlag(FLAGS_vrp_precedences) > 0) {
182  // Randomly select edges in a graph that will act as precedences.
183  std::vector<std::pair<int, int>> precedences;
184  GraphBuilder::RandomEdges(
185  GraphBuilder::DISALLOW_ALL_CYCLES, absl::GetFlag(FLAGS_vrp_orders),
186  absl::GetFlag(FLAGS_vrp_precedences), randomizer, &precedences);
187 
188  LOG(INFO) << "Adding precedences: ";
189  for (const std::pair<int, int>& precedence : precedences) {
190  LOG(INFO) << precedence.first << " -> " << precedence.second;
191  time_dimension->AddNodePrecedence(
192  {precedence.first, precedence.second,
193  absl::GetFlag(FLAGS_vrp_precedence_offset)});
194  }
195  }
196  // Solve, returns a solution if any (owned by RoutingModel).
197  RoutingSearchParameters parameters = DefaultRoutingSearchParameters();
198  CHECK(google::protobuf::TextFormat::MergeFromString(
199  absl::GetFlag(FLAGS_routing_search_parameters), &parameters));
200  const Assignment* solution = routing.SolveWithParameters(parameters);
201  if (solution != nullptr) {
202  DisplayPlan(manager, routing, *solution,
203  absl::GetFlag(FLAGS_vrp_use_same_vehicle_costs),
205  routing.GetDimensionOrDie(kCapacity),
206  routing.GetDimensionOrDie(kTime));
207  } else {
208  LOG(INFO) << "No solution found.";
209  }
210 
211  return 0;
212 }
An Assignment is a variable -> domains mapping, used to report solutions to the user.
virtual void SetRange(int64_t l, int64_t u)
This method sets both the min and the max of the expression.
int64_t ManhattanTime(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const
Definition: cvrptw_lib.cc:72
void AddRandomLocation(int64_t x_max, int64_t y_max)
Definition: cvrptw_lib.cc:49
int64_t ManhattanDistance(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const
Definition: cvrptw_lib.cc:62
Dimensions represent quantities accumulated at nodes along the routes.
Definition: routing.h:2750
void AddNodePrecedence(NodePrecedence precedence)
Definition: routing.h:3053
IntVar * CumulVar(int64_t index) const
Get the cumul, transit and slack variables for the given node (given as int64_t var index).
Definition: routing.h:2769
Manager for any NodeIndex <-> variable index conversion.
NodeIndex IndexToNode(int64_t index) const
int64_t NodeToIndex(NodeIndex node) const
void AddSoftSameVehicleConstraint(const std::vector< int64_t > &indices, int64_t cost)
Adds a soft constraint to force a set of variable indices to be on the same vehicle.
Definition: routing.cc:2269
RoutingDimension * GetMutableDimension(const std::string &dimension_name) const
Returns a dimension from its name.
Definition: routing.cc:1690
DisjunctionIndex AddDisjunction(const std::vector< int64_t > &indices, int64_t penalty=kNoPenalty, int64_t max_cardinality=1)
Adds a disjunction constraint on the indices: exactly 'max_cardinality' of the indices are active.
Definition: routing.cc:2179
const Assignment * SolveWithParameters(const RoutingSearchParameters &search_parameters, std::vector< const Assignment * > *solutions=nullptr)
Solves the current routing model with the given parameters.
Definition: routing.cc:3311
int RegisterTransitCallback(TransitCallback2 callback)
Definition: routing.cc:1301
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' an...
Definition: routing.cc:1783
bool AddDimension(int evaluator_index, int64_t slack_max, int64_t capacity, bool fix_start_cumul_to_zero, const std::string &name)
Model creation.
Definition: routing.cc:1358
const RoutingDimension & GetDimensionOrDie(const std::string &dimension_name) const
Returns a dimension from its name. Dies if the dimension does not exist.
Definition: routing.cc:1685
SatParameters parameters
int main(int argc, char **argv)
const char * kCapacity
const char * kTime
const int64_t kMaxNodesPerGroup
ABSL_FLAG(int, vrp_orders, 100, "Nodes in the problem.")
const int64_t kSameVehicleCost
void InitGoogle(const char *usage, int *argc, char ***argv, bool deprecated)
Definition: init_google.h:34
void DisplayPlan(const RoutingIndexManager &manager, const RoutingModel &routing, const operations_research::Assignment &plan, bool use_same_vehicle_costs, int64_t max_nodes_per_group, int64_t same_vehicle_cost, const operations_research::RoutingDimension &capacity_dimension, const operations_research::RoutingDimension &time_dimension)
Definition: cvrptw_lib.cc:160
int32_t GetSeed(bool deterministic)
Definition: cvrptw_lib.cc:35
RoutingSearchParameters DefaultRoutingSearchParameters()
int64_t demand
Definition: resource.cc:126
int64_t time
Definition: resource.cc:1694
int64_t start