blob: c01c0d03cb8d6e00f64d233a7e37e483abb99b26 [file] [log] [blame]
weibit0d0ef612014-11-03 14:39:25 -08001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19package org.onlab.graph;
20
21import java.util.ArrayList;
22//import java.util.HashMap;
23import java.util.Iterator;
24import java.util.List;
25//import java.util.Map;
26//import java.util.PriorityQueue;
27import java.util.Set;
28
weibit0d0ef612014-11-03 14:39:25 -080029/**
30 * K-shortest-path graph search algorithm capable of finding not just one,
weibit6c415d12014-11-03 19:15:42 -080031 * but K shortest paths with ascending order between the source and destinations.
weibit0d0ef612014-11-03 14:39:25 -080032 */
33
34public class KshortestPathSearch<V extends Vertex, E extends Edge<V>> {
35
36 // Define class variables.
37 private Graph<V, E> immutableGraph;
38 private MutableGraph<V, E> mutableGraph;
39 private List<List<E>> pathResults = new ArrayList<List<E>>();
40 private List<List<E>> pathCandidates = new ArrayList<List<E>>();
41 private V source;
42 private V sink;
43 private int numK = 0;
44 private EdgeWeight<V, E> weight = null;
45 // private PriorityQueue<List<E>> pathCandidates = new PriorityQueue<List<E>>();
46
47 // Initialize the graph.
48 public KshortestPathSearch(Graph<V, E> graph) {
49 immutableGraph = graph;
50 mutableGraph = new MutableAdjacencyListsGraph(graph.getVertexes(),
51 graph.getEdges());
52 }
53
54 public List<List<E>> search(V src,
55 V dst,
56 EdgeWeight<V, E> wei,
57 int k) {
58
59 weight = wei;
60 source = src;
61 sink = dst;
62 numK = k;
63 // pathCandidates = new PriorityQueue<List<E>>();
64
65 pathResults.clear();
66 pathCandidates.clear();
67
68 // Double check the parameters
69 checkArguments(immutableGraph, src, dst, numK);
70
71 // DefaultResult result = new DefaultResult(src, dst);
72
73 searchKShortestPaths();
74
75 return pathResults;
76 }
77
78 private void checkArguments(Graph<V, E> graph, V src, V dst, int k) {
79 if (graph == null) {
80 throw new NullPointerException("graph is null");
81 }
82 if (!graph.getVertexes().contains(src)) {
83 throw new NullPointerException("source node does not exist");
84 }
85 if (!graph.getVertexes().contains(dst)) {
86 throw new NullPointerException("target node does not exist");
87 }
88 if (k <= 0) {
89 throw new NullPointerException("K is negative or 0");
90 }
91 if (weight == null) {
92 throw new NullPointerException("the cost matrix is null");
93 }
94 }
95
96 private void searchKShortestPaths() {
97 // Step 1: find the shortest path.
98 List<E> shortestPath = searchShortestPath(immutableGraph, source, sink);
99 // no path exists, exit.
100 if (shortestPath == null) {
101 return;
102 }
103
104 // Step 2: update the results.
105 pathResults.add(shortestPath);
106 // pathCandidates.add(shortestPath);
107
108 // Step 3: find the other K-1 paths.
109 while (/*pathCandidates.size() > 0 &&*/pathResults.size() < numK) {
110 // 3.1 the spur node ranges from the first node to the last node in the previous k-shortest path.
111 List<E> lastPath = pathResults.get(pathResults.size() - 1);
112 for (int i = 0; i < lastPath.size(); i++) {
weibit6c415d12014-11-03 19:15:42 -0800113 // 3.1.1 convert the graph into mutable.
weibit0d0ef612014-11-03 14:39:25 -0800114 convertGraph();
weibit6c415d12014-11-03 19:15:42 -0800115 // 3.1.2 transform the graph.
weibit0d0ef612014-11-03 14:39:25 -0800116 List<E> rootPath = createSpurNode(lastPath, i);
117 transformGraph(rootPath);
weibit6c415d12014-11-03 19:15:42 -0800118 // 3.1.3 find the deviation node.
weibit0d0ef612014-11-03 14:39:25 -0800119 V devNode;
120 devNode = getDevNode(rootPath);
121 List<E> spurPath;
weibit6c415d12014-11-03 19:15:42 -0800122 // 3.1.4 find the shortest path in the transformed graph.
weibit0d0ef612014-11-03 14:39:25 -0800123 spurPath = searchShortestPath(mutableGraph, devNode, sink);
weibit6c415d12014-11-03 19:15:42 -0800124 // 3.1.5 update the path candidates.
weibit0d0ef612014-11-03 14:39:25 -0800125 if (spurPath != null) {
126 // totalPath = rootPath + spurPath;
127 rootPath.addAll(spurPath);
128 pathCandidates.add(rootPath);
129 }
130 }
131 // 3.2 if there is no spur path, exit.
132 if (pathCandidates.size() == 0) {
133 break;
134 }
135 // 3.3 add the path into the results.
136 addPathResult();
137 }
138 }
139
140 private List<E> searchShortestPath(Graph<V, E> graph, V src, V dst) {
141 // Determine the shortest path from the source to the destination by using the Dijkstra algorithm.
142 DijkstraGraphSearch dijkstraAlg = new DijkstraGraphSearch();
143 Set<Path> paths = dijkstraAlg.search(graph, src, dst, weight).paths();
144 Iterator<Path> itr = paths.iterator();
145 if (!itr.hasNext()) {
146 return null;
147 }
148 // return the first shortest path only.
149 return (List<E>) itr.next().edges();
150 }
151
152 private void convertGraph() {
153 // clear the mutableGraph first
154 if (mutableGraph != null) {
155 ((MutableAdjacencyListsGraph) mutableGraph).clear();
156 }
157
158 // create a immutableGraph
159 Set<E> copyEa = immutableGraph.getEdges();
160 Set<V> copyVa = immutableGraph.getVertexes();
161 for (V vertex : copyVa) {
162 mutableGraph.addVertex(vertex);
163 }
164 for (E edge : copyEa) {
165 mutableGraph.addEdge(edge);
166 }
167 }
168
169 private V getDevNode(List<E> path) {
170 V srcA;
171 V dstB;
172
173 if (path.size() == 0) {
174 return source;
175 }
176
177 E temp1 = path.get(path.size() - 1);
178 srcA = temp1.src();
179 dstB = temp1.dst();
180
181 if (path.size() == 1) {
182 if (srcA.equals(source)) {
183 return dstB;
184 } else {
185 return srcA;
186 }
187 } else {
188 E temp2 = path.get(path.size() - 2);
189 if (srcA.equals(temp2.src()) || srcA.equals(temp2.dst())) {
190 return dstB;
191 } else {
192 return srcA;
193 }
194 }
195 }
196
197 private List<E> createSpurNode(List<E> path, int n) {
198 List<E> root = new ArrayList<E>();
199
200 for (int i = 0; i < n; i++) {
201 root.add(path.get(i));
202 }
203 return root;
204 }
205
206 private void transformGraph(List<E> rootPath) {
207 List<E> prePath;
208 //remove edges
209 for (int i = 0; i < pathResults.size(); i++) {
210 prePath = pathResults.get(i);
211 if (prePath.size() == 1) {
212 mutableGraph.removeEdge(prePath.get(0));
213 } else if (comparePath(rootPath, prePath)) {
214 for (int j = 0; j <= rootPath.size(); j++) {
215 mutableGraph.removeEdge(prePath.get(j));
216 }
217 }
218 }
219 for (int i = 0; i < pathCandidates.size(); i++) {
220 prePath = pathCandidates.get(i);
221 if (prePath.size() == 1) {
222 mutableGraph.removeEdge(prePath.get(0));
223 } else if (comparePath(rootPath, prePath)) {
224 for (int j = 0; j <= rootPath.size(); j++) {
225 mutableGraph.removeEdge(prePath.get(j));
226 }
227 }
228 }
229
230 if (rootPath.size() == 0) {
231 return;
232 }
233
234 //remove nodes
235 List<V> nodes = new ArrayList<V>();
236 nodes.add(source);
237 V pre = source;
238 V srcA;
239 V dstB;
240 for (int i = 0; i < rootPath.size() - 1; i++) {
241 E temp = rootPath.get(i);
242 srcA = temp.src();
243 dstB = temp.dst();
244
245 if (srcA.equals(pre)) {
246 nodes.add(dstB);
247 pre = dstB;
248 } else {
249 nodes.add(srcA);
250 pre = srcA;
251 }
252 }
253 for (int i = 0; i < nodes.size(); i++) {
254 mutableGraph.removeVertex(nodes.get(i));
255 }
256 }
257
258 private boolean comparePath(List<E> path1, List<E> path2) {
259 if (path1.size() > path2.size()) {
260 return false;
261 }
262 if (path1.size() == 0) {
263 return true;
264 }
265 for (int i = 0; i < path1.size(); i++) {
266 if (path1.get(i) != path2.get(i)) {
267 return false;
268 }
269 }
270 return true;
271 }
272
273 private void addPathResult() {
274 List<E> sp;
275 sp = pathCandidates.get(0);
276 for (int i = 1; i < pathCandidates.size(); i++) {
277 if (sp.size() > pathCandidates.get(i).size()) {
278 sp = pathCandidates.get(i);
279 }
280 }
281 pathResults.add(sp);
282 // Log.info(sp.toString());
283 pathCandidates.remove(sp);
284 }
285
286}