OR-Tools  7.1
Tsp.java
Go to the documentation of this file.
1 // Copyright 2010-2018 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 // [START program]
15 // [START import]
16 import static java.lang.Math.abs;
17 
24 import java.util.function.LongBinaryOperator;
25 import java.util.logging.Logger;
26 // [END import]
27 
29 public class Tsp {
30  static {
31  System.loadLibrary("jniortools");
32  }
33 
34  private static final Logger logger = Logger.getLogger(Tsp.class.getName());
35 
36  // [START data_model]
37  static class DataModel {
38  public final int[][] locations = {
39  {4, 4},
40  {2, 0},
41  {8, 0},
42  {0, 1},
43  {1, 1},
44  {5, 2},
45  {7, 2},
46  {3, 3},
47  {6, 3},
48  {5, 5},
49  {8, 5},
50  {1, 6},
51  {2, 6},
52  {3, 7},
53  {6, 7},
54  {0, 8},
55  {7, 8},
56  };
57  public final int vehicleNumber = 1;
58  public final int depot = 0;
59  public DataModel() {
60  // Convert locations in meters using a city block dimension of 114m x 80m.
61  for (int[] element : locations) {
62  element[0] *= 114;
63  element[1] *= 80;
64  }
65  }
66  }
67  // [END data_model]
68 
69  // [START manhattan_distance]
74  static class ManhattanDistance implements LongBinaryOperator {
75  public ManhattanDistance(DataModel data, RoutingIndexManager manager) {
76  // precompute distance between location to have distance callback in O(1)
77  distanceMatrix = new long[data.locations.length][data.locations.length];
78  indexManager = manager;
79  for (int fromNode = 0; fromNode < data.locations.length; ++fromNode) {
80  for (int toNode = 0; toNode < data.locations.length; ++toNode) {
81  if (fromNode == toNode) {
82  distanceMatrix[fromNode][toNode] = 0;
83  } else {
84  distanceMatrix[fromNode][toNode] =
85  (long) abs(data.locations[toNode][0] - data.locations[fromNode][0])
86  + (long) abs(data.locations[toNode][1] - data.locations[fromNode][1]);
87  }
88  }
89  }
90  }
91  @Override
92  public long applyAsLong(long fromIndex, long toIndex) {
93  // Convert from routing variable Index to distance matrix NodeIndex.
94  int fromNode = indexManager.indexToNode(fromIndex);
95  int toNode = indexManager.indexToNode(toIndex);
96  return distanceMatrix[fromNode][toNode];
97  }
98  private final long[][] distanceMatrix;
99  private final RoutingIndexManager indexManager;
100  }
101  // [END manhattan_distance]
102 
103  // [START solution_printer]
105  static void printSolution(
106  DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
107  // Solution cost.
108  logger.info("Objective : " + solution.objectiveValue());
109  // Inspect solution.
110  logger.info("Route for Vehicle 0:");
111  long routeDistance = 0;
112  String route = "";
113  long index = routing.start(0);
114  while (!routing.isEnd(index)) {
115  route += manager.indexToNode(index) + " -> ";
116  long previousIndex = index;
117  index = solution.value(routing.nextVar(index));
118  routeDistance += routing.getArcCostForVehicle(previousIndex, index, 0);
119  }
120  route += manager.indexToNode(routing.end(0));
121  logger.info(route);
122  logger.info("Distance of the route: " + routeDistance + "m");
123  }
124  // [END solution_printer]
125 
126  public static void main(String[] args) throws Exception {
127  // Instantiate the data problem.
128  // [START data]
129  final DataModel data = new DataModel();
130  // [END data]
131 
132  // Create Routing Index Manager
133  // [START index_manager]
134  RoutingIndexManager manager =
135  new RoutingIndexManager(data.locations.length, data.vehicleNumber, data.depot);
136  // [END index_manager]
137 
138  // Create Routing Model.
139  // [START routing_model]
140  RoutingModel routing = new RoutingModel(manager);
141  // [END routing_model]
142 
143  // Create and register a transit callback.
144  // [START transit_callback]
145  final int transitCallbackIndex =
146  routing.registerTransitCallback(new ManhattanDistance(data, manager));
147  // [END transit_callback]
148 
149  // Define cost of each arc.
150  // [START arc_cost]
151  routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
152  // [END arc_cost]
153 
154  // Setting first solution heuristic.
155  // [START parameters]
156  RoutingSearchParameters searchParameters =
158  .toBuilder()
160  .build();
161  // [END parameters]
162 
163  // Solve the problem.
164  // [START solve]
165  Assignment solution = routing.solveWithParameters(searchParameters);
166  // [END solve]
167 
168  // Print solution on console.
169  // [START print_solution]
170  printSolution(data, routing, manager, solution);
171  // [END print_solution]
172  }
173 }
174 // [END program]
static com.google.ortools.constraintsolver.RoutingSearchParameters defaultRoutingSearchParameters()
int registerTransitCallback(LongBinaryOperator callback)
long getArcCostForVehicle(long from_index, long to_index, long vehicle)
.lang.Override com.google.ortools.constraintsolver.RoutingSearchParameters build()
static void main(String[] args)
Definition: Tsp.java:126
Builder setFirstSolutionStrategy(com.google.ortools.constraintsolver.FirstSolutionStrategy.Value value)
Assignment solveWithParameters(com.google.ortools.constraintsolver.RoutingSearchParameters search_parameters)
Minimal TSP.
Definition: Tsp.java:29
void setArcCostEvaluatorOfAllVehicles(int evaluator_index)