forked from google/or-tools
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCapacitatedVehicleRoutingProblemWithTimeWindows.java
More file actions
Latest commit
286 lines (261 loc) · 11.5 KB
/
Copy pathCapacitatedVehicleRoutingProblemWithTimeWindows.java
File metadata and controls
286 lines (261 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//
// Copyright 2012 Google
//
// 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.
packagecom.google.ortools.java;
importcom.google.ortools.Loader;
importcom.google.ortools.constraintsolver.Assignment;
importcom.google.ortools.constraintsolver.FirstSolutionStrategy;
importcom.google.ortools.constraintsolver.IntVar;
importcom.google.ortools.constraintsolver.RoutingDimension;
importcom.google.ortools.constraintsolver.RoutingIndexManager;
importcom.google.ortools.constraintsolver.RoutingModel;
importcom.google.ortools.constraintsolver.RoutingSearchParameters;
importcom.google.ortools.constraintsolver.main;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Random;
importjava.util.function.LongBinaryOperator;
importjava.util.function.LongUnaryOperator;
importjava.util.logging.Logger;
// A pair class
classPair<K, V> {
finalKfirst;
finalVsecond;
publicstatic <K, V> Pair<K, V> of(Kelement0, Velement1) {
returnnewPair<K, V>(element0, element1);
}
publicPair(Kelement0, Velement1) {
this.first = element0;
this.second = element1;
}
}
/**
* Sample showing how to model and solve a capacitated vehicle routing problem with time windows
* using the swig-wrapped version of the vehicle routing library in src/constraint_solver.
*/
publicclassCapacitatedVehicleRoutingProblemWithTimeWindows {
privatestaticLoggerlogger =
Logger.getLogger(CapacitatedVehicleRoutingProblemWithTimeWindows.class.getName());
// Locations representing either an order location or a vehicle route
// start/end.
privateList<Pair<Integer, Integer>> locations = newArrayList();
// Quantity to be picked up for each order.
privateList<Integer> orderDemands = newArrayList();
// Time window in which each order must be performed.
privateList<Pair<Integer, Integer>> orderTimeWindows = newArrayList();
// Penalty cost "paid" for dropping an order.
privateList<Integer> orderPenalties = newArrayList();
// Capacity of the vehicles.
privateintvehicleCapacity = 0;
// Latest time at which each vehicle must end its tour.
privateList<Integer> vehicleEndTime = newArrayList();
// Cost per unit of distance of each vehicle.
privateList<Integer> vehicleCostCoefficients = newArrayList();
// Vehicle start and end indices. They have to be implemented as int[] due
// to the available SWIG-ed interface.
privateintvehicleStarts[];
privateintvehicleEnds[];
// Random number generator to produce data.
privatefinalRandomrandomGenerator = newRandom(0xBEEF);
/**
* Creates a Manhattan Distance evaluator with 'costCoefficient'.
*
* @param manager Node Index Manager.
* @param costCoefficient The coefficient to apply to the evaluator.
*/
privateLongBinaryOperatorbuildManhattanCallback(
RoutingIndexManagermanager, intcostCoefficient) {
returnnewLongBinaryOperator() {
publiclongapplyAsLong(longfirstIndex, longsecondIndex) {
try {
intfirstNode = manager.indexToNode(firstIndex);
intsecondNode = manager.indexToNode(secondIndex);
Pair<Integer, Integer> firstLocation = locations.get(firstNode);
Pair<Integer, Integer> secondLocation = locations.get(secondNode);
return (long) costCoefficient
* (Math.abs(firstLocation.first - secondLocation.first)
+ Math.abs(firstLocation.second - secondLocation.second));
} catch (Throwablethrowed) {
logger.warning(throwed.getMessage());
return0;
}
}
};
}
/**
* Creates order data. Location of the order is random, as well as its demand (quantity), time
* window and penalty.
*
* @param numberOfOrders number of orders to build.
* @param xMax maximum x coordinate in which orders are located.
* @param yMax maximum y coordinate in which orders are located.
* @param demandMax maximum quantity of a demand.
* @param timeWindowMax maximum starting time of the order time window.
* @param timeWindowWidth duration of the order time window.
* @param penaltyMin minimum pernalty cost if order is dropped.
* @param penaltyMax maximum pernalty cost if order is dropped.
*/
privatevoidbuildOrders(intnumberOfOrders, intxMax, intyMax, intdemandMax, inttimeWindowMax,
inttimeWindowWidth, intpenaltyMin, intpenaltyMax) {
logger.info("Building orders.");
for (intorder = 0; order < numberOfOrders; ++order) {
locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1)));
orderDemands.add(randomGenerator.nextInt(demandMax + 1));
inttimeWindowStart = randomGenerator.nextInt(timeWindowMax + 1);
orderTimeWindows.add(Pair.of(timeWindowStart, timeWindowStart + timeWindowWidth));
orderPenalties.add(randomGenerator.nextInt(penaltyMax - penaltyMin + 1) + penaltyMin);
}
}
/**
* Creates fleet data. Vehicle starting and ending locations are random, as well as vehicle costs
* per distance unit.
*
* @param numberOfVehicles
* @param xMax maximum x coordinate in which orders are located.
* @param yMax maximum y coordinate in which orders are located.
* @param endTime latest end time of a tour of a vehicle.
* @param capacity capacity of a vehicle.
* @param costCoefficientMax maximum cost per distance unit of a vehicle (mimimum is 1),
*/
privatevoidbuildFleet(
intnumberOfVehicles, intxMax, intyMax, intendTime, intcapacity, intcostCoefficientMax) {
logger.info("Building fleet.");
vehicleCapacity = capacity;
vehicleStarts = newint[numberOfVehicles];
vehicleEnds = newint[numberOfVehicles];
for (intvehicle = 0; vehicle < numberOfVehicles; ++vehicle) {
vehicleStarts[vehicle] = locations.size();
locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1)));
vehicleEnds[vehicle] = locations.size();
locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1)));
vehicleEndTime.add(endTime);
vehicleCostCoefficients.add(randomGenerator.nextInt(costCoefficientMax) + 1);
}
}
/** Solves the current routing problem. */
privatevoidsolve(finalintnumberOfOrders, finalintnumberOfVehicles) {
logger.info(
"Creating model with " + numberOfOrders + " orders and " + numberOfVehicles + " vehicles.");
// Finalizing model
finalintnumberOfLocations = locations.size();
RoutingIndexManagermanager =
newRoutingIndexManager(numberOfLocations, numberOfVehicles, vehicleStarts, vehicleEnds);
RoutingModelmodel = newRoutingModel(manager);
// Setting up dimensions
finalintbigNumber = 100000;
finalLongBinaryOperatorcallback = buildManhattanCallback(manager, 1);
finalStringtimeStr = "time";
model.addDimension(
model.registerTransitCallback(callback), bigNumber, bigNumber, false, timeStr);
RoutingDimensiontimeDimension = model.getMutableDimension(timeStr);
LongUnaryOperatordemandCallback = newLongUnaryOperator() {
publiclongapplyAsLong(longindex) {
try {
intnode = manager.indexToNode(index);
if (node < numberOfOrders) {
returnorderDemands.get(node);
}
return0;
} catch (Throwablethrowed) {
logger.warning(throwed.getMessage());
return0;
}
}
};
finalStringcapacityStr = "capacity";
model.addDimension(
model.registerUnaryTransitCallback(demandCallback), 0, vehicleCapacity, true, capacityStr);
RoutingDimensioncapacityDimension = model.getMutableDimension(capacityStr);
// Setting up vehicles
LongBinaryOperator[] callbacks = newLongBinaryOperator[numberOfVehicles];
for (intvehicle = 0; vehicle < numberOfVehicles; ++vehicle) {
finalintcostCoefficient = vehicleCostCoefficients.get(vehicle);
callbacks[vehicle] = buildManhattanCallback(manager, costCoefficient);
finalintvehicleCost = model.registerTransitCallback(callbacks[vehicle]);
model.setArcCostEvaluatorOfVehicle(vehicleCost, vehicle);
timeDimension.cumulVar(model.end(vehicle)).setMax(vehicleEndTime.get(vehicle));
}
// Setting up orders
for (intorder = 0; order < numberOfOrders; ++order) {
timeDimension.cumulVar(order).setRange(
orderTimeWindows.get(order).first, orderTimeWindows.get(order).second);
long[] orderIndices = {manager.nodeToIndex(order)};
model.addDisjunction(orderIndices, orderPenalties.get(order));
}
// Solving
RoutingSearchParametersparameters =
main.defaultRoutingSearchParameters()
.toBuilder()
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.ALL_UNPERFORMED)
.build();
logger.info("Search");
Assignmentsolution = model.solveWithParameters(parameters);
if (solution != null) {
Stringoutput = "Total cost: " + solution.objectiveValue() + "\n";
// Dropped orders
Stringdropped = "";
for (intorder = 0; order < numberOfOrders; ++order) {
if (solution.value(model.nextVar(order)) == order) {
dropped += " " + order;
}
}
if (dropped.length() > 0) {
output += "Dropped orders:" + dropped + "\n";
}
// Routes
for (intvehicle = 0; vehicle < numberOfVehicles; ++vehicle) {
Stringroute = "Vehicle " + vehicle + ": ";
longorder = model.start(vehicle);
// Empty route has a minimum of two nodes: Start => End
if (model.isEnd(solution.value(model.nextVar(order)))) {
route += "Empty";
} else {
for (; !model.isEnd(order); order = solution.value(model.nextVar(order))) {
IntVarload = capacityDimension.cumulVar(order);
IntVartime = timeDimension.cumulVar(order);
route += order + " Load(" + solution.value(load) + ") "
+ "Time(" + solution.min(time) + ", " + solution.max(time) + ") -> ";
}
IntVarload = capacityDimension.cumulVar(order);
IntVartime = timeDimension.cumulVar(order);
route += order + " Load(" + solution.value(load) + ") "
+ "Time(" + solution.min(time) + ", " + solution.max(time) + ")";
}
output += route + "\n";
}
logger.info(output);
}
}
publicstaticvoidmain(String[] args) throwsException {
Loader.loadNativeLibraries();
CapacitatedVehicleRoutingProblemWithTimeWindowsproblem =
newCapacitatedVehicleRoutingProblemWithTimeWindows();
finalintxMax = 20;
finalintyMax = 20;
finalintdemandMax = 3;
finalinttimeWindowMax = 24 * 60;
finalinttimeWindowWidth = 4 * 60;
finalintpenaltyMin = 50;
finalintpenaltyMax = 100;
finalintendTime = 24 * 60;
finalintcostCoefficientMax = 3;
finalintorders = 100;
finalintvehicles = 20;
finalintcapacity = 50;
problem.buildOrders(
orders, xMax, yMax, demandMax, timeWindowMax, timeWindowWidth, penaltyMin, penaltyMax);
problem.buildFleet(vehicles, xMax, yMax, endTime, capacity, costCoefficientMax);
problem.solve(orders, vehicles);
}
}