OR-Tools  9.6
cvrp_disjoint_tw.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 Disjoint Time Windows (and optional
16 // orders).
17 // A description of the problem can be found here:
18 // http://en.wikipedia.org/wiki/Vehicle_routing_problem.
19 // The variant which is tackled by this model includes a capacity dimension,
20 // disjoint time windows and optional orders, with a penalty cost if orders are
21 // not performed. For the sake of simplicity, orders are randomly located and
22 // distances are computed using the Manhattan distance. Distances are assumed
23 // to be in meters and times in seconds.
24 
25 #include <algorithm>
26 #include <cstdint>
27 #include <random>
28 #include <vector>
29 
30 #include "absl/random/random.h"
31 #include "google/protobuf/text_format.h"
35 #include "ortools/base/logging.h"
39 #include "ortools/constraint_solver/routing_parameters.pb.h"
41 
50 using operations_research::RoutingNodeIndex;
51 using operations_research::RoutingSearchParameters;
54 
55 ABSL_FLAG(int, vrp_orders, 100, "Number of nodes in the problem.");
56 ABSL_FLAG(int, vrp_vehicles, 20, "Number of vehicles in the problem.");
57 ABSL_FLAG(int, vrp_windows, 5, "Number of disjoint windows per node.");
58 ABSL_FLAG(bool, vrp_use_deterministic_random_seed, false,
59  "Use deterministic random seeds.");
60 ABSL_FLAG(bool, vrp_use_same_vehicle_costs, false,
61  "Use same vehicle costs in the routing model");
62 ABSL_FLAG(std::string, routing_search_parameters, "",
63  "Text proto RoutingSearchParameters (possibly partial) that will "
64  "override the DefaultRoutingSearchParameters()");
65 
66 const char* kTime = "Time";
67 const char* kCapacity = "Capacity";
68 const int64_t kMaxNodesPerGroup = 10;
69 const int64_t kSameVehicleCost = 1000;
70 
71 int main(int argc, char** argv) {
72  InitGoogle(argv[0], &argc, &argv, true);
73  CHECK_LT(0, absl::GetFlag(FLAGS_vrp_orders))
74  << "Specify an instance size greater than 0.";
75  CHECK_LT(0, absl::GetFlag(FLAGS_vrp_vehicles))
76  << "Specify a non-null vehicle fleet size.";
77  // VRP of size absl::GetFlag(FLAGS_vrp_size).
78  // Nodes are indexed from 0 to absl::GetFlag(FLAGS_vrp_orders), the starts and
79  // ends of the routes are at node 0.
80  const RoutingIndexManager::NodeIndex kDepot(0);
81  RoutingIndexManager manager(absl::GetFlag(FLAGS_vrp_orders) + 1,
82  absl::GetFlag(FLAGS_vrp_vehicles), kDepot);
83  RoutingModel routing(manager);
84 
85  // Setting up locations.
86  const int64_t kXMax = 100000;
87  const int64_t kYMax = 100000;
88  const int64_t kSpeed = 10;
89  LocationContainer locations(
90  kSpeed, absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed));
91  for (int location = 0; location <= absl::GetFlag(FLAGS_vrp_orders);
92  ++location) {
93  locations.AddRandomLocation(kXMax, kYMax);
94  }
95 
96  // Setting the cost function.
97  const int vehicle_cost = routing.RegisterTransitCallback(
98  [&locations, &manager](int64_t i, int64_t j) {
99  return locations.ManhattanDistance(manager.IndexToNode(i),
100  manager.IndexToNode(j));
101  });
102  routing.SetArcCostEvaluatorOfAllVehicles(vehicle_cost);
103 
104  // Adding capacity dimension constraints.
105  const int64_t kVehicleCapacity = 40;
106  const int64_t kNullCapacitySlack = 0;
107  RandomDemand demand(manager.num_nodes(), kDepot,
108  absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed));
109  demand.Initialize();
110  routing.AddDimension(routing.RegisterTransitCallback(
111  [&demand, &manager](int64_t i, int64_t j) {
112  return demand.Demand(manager.IndexToNode(i),
113  manager.IndexToNode(j));
114  }),
115  kNullCapacitySlack, kVehicleCapacity,
116  /*fix_start_cumul_to_zero=*/true, kCapacity);
117 
118  // Adding time dimension constraints.
119  const int64_t kTimePerDemandUnit = 300;
120  const int64_t kHorizon = 24 * 3600;
122  kTimePerDemandUnit,
123  [&demand](RoutingNodeIndex i, RoutingNodeIndex j) {
124  return demand.Demand(i, j);
125  },
126  [&locations](RoutingNodeIndex i, RoutingNodeIndex j) {
127  return locations.ManhattanTime(i, j);
128  });
129  routing.AddDimension(
130  routing.RegisterTransitCallback([&time, &manager](int64_t i, int64_t j) {
131  return time.Compute(manager.IndexToNode(i), manager.IndexToNode(j));
132  }),
133  kHorizon, kHorizon, /*fix_start_cumul_to_zero=*/false, kTime);
134  const RoutingDimension& time_dimension = routing.GetDimensionOrDie(kTime);
135 
136  // Adding disjoint time windows.
137  Solver* solver = routing.solver();
138  std::mt19937 randomizer(
139  GetSeed(absl::GetFlag(FLAGS_vrp_use_deterministic_random_seed)));
140  for (int order = 1; order < manager.num_nodes(); ++order) {
141  std::vector<int64_t> forbid_points(2 * absl::GetFlag(FLAGS_vrp_windows), 0);
142  for (int i = 0; i < forbid_points.size(); ++i) {
143  forbid_points[i] = absl::Uniform<int32_t>(randomizer, 0, kHorizon);
144  }
145  std::sort(forbid_points.begin(), forbid_points.end());
146  std::vector<int64_t> forbid_starts(1, 0);
147  std::vector<int64_t> forbid_ends;
148  for (int i = 0; i < forbid_points.size(); i += 2) {
149  forbid_ends.push_back(forbid_points[i]);
150  forbid_starts.push_back(forbid_points[i + 1]);
151  }
152  forbid_ends.push_back(kHorizon);
153  solver->AddConstraint(solver->MakeNotMemberCt(
154  time_dimension.CumulVar(order), forbid_starts, forbid_ends));
155  }
156 
157  // Adding penalty costs to allow skipping orders.
158  const int64_t kPenalty = 10000000;
159  const RoutingIndexManager::NodeIndex kFirstNodeAfterDepot(1);
160  for (RoutingIndexManager::NodeIndex order = kFirstNodeAfterDepot;
161  order < manager.num_nodes(); ++order) {
162  std::vector<int64_t> orders(1, manager.NodeToIndex(order));
163  routing.AddDisjunction(orders, kPenalty);
164  }
165 
166  // Adding same vehicle constraint costs for consecutive nodes.
167  if (absl::GetFlag(FLAGS_vrp_use_same_vehicle_costs)) {
168  std::vector<int64_t> group;
169  for (RoutingIndexManager::NodeIndex order = kFirstNodeAfterDepot;
170  order < manager.num_nodes(); ++order) {
171  group.push_back(manager.NodeToIndex(order));
172  if (group.size() == kMaxNodesPerGroup) {
174  group.clear();
175  }
176  }
177  if (!group.empty()) {
179  }
180  }
181 
182  // Solve, returns a solution if any (owned by RoutingModel).
183  RoutingSearchParameters parameters = DefaultRoutingSearchParameters();
184  CHECK(google::protobuf::TextFormat::MergeFromString(
185  absl::GetFlag(FLAGS_routing_search_parameters), &parameters));
186  const Assignment* solution = routing.SolveWithParameters(parameters);
187  if (solution != nullptr) {
188  DisplayPlan(manager, routing, *solution,
189  absl::GetFlag(FLAGS_vrp_use_same_vehicle_costs),
191  routing.GetDimensionOrDie(kCapacity),
192  routing.GetDimensionOrDie(kTime));
193  } else {
194  LOG(INFO) << "No solution found.";
195  }
196  return EXIT_SUCCESS;
197 }
An Assignment is a variable -> domains mapping, used to report solutions to the user.
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
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
Solver * solver() const
Returns the underlying constraint solver.
Definition: routing.h:1630
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
Constraint * MakeNotMemberCt(IntExpr *const expr, const std::vector< int64_t > &values)
expr not in set.
Definition: expr_cst.cc:1235
void AddConstraint(Constraint *const c)
Adds the constraint 'c' to the model.
SatParameters parameters
int main(int argc, char **argv)
const char * kCapacity
const char * kTime
ABSL_FLAG(int, vrp_orders, 100, "Number of nodes in the problem.")
const int64_t kMaxNodesPerGroup
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