blob: bcbe9411b3c87e1f483b71f93967910aebdf500d [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
29//import org.apache.commons.lang3.tuple.Pair;
30//import org.onlab.graph.AbstractGraphPathSearch.DefaultResult;
31
32/**
33 * K-shortest-path graph search algorithm capable of finding not just one,
34 * but K shortest paths with descending order between the source and destinations.
35 */
36
37public class KshortestPathSearch<V extends Vertex, E extends Edge<V>> {
38
39 // Define class variables.
40 private Graph<V, E> immutableGraph;
41 private MutableGraph<V, E> mutableGraph;
42 private List<List<E>> pathResults = new ArrayList<List<E>>();
43 private List<List<E>> pathCandidates = new ArrayList<List<E>>();
44 private V source;
45 private V sink;
46 private int numK = 0;
47 private EdgeWeight<V, E> weight = null;
48 // private PriorityQueue<List<E>> pathCandidates = new PriorityQueue<List<E>>();
49
50 // Initialize the graph.
51 public KshortestPathSearch(Graph<V, E> graph) {
52 immutableGraph = graph;
53 mutableGraph = new MutableAdjacencyListsGraph(graph.getVertexes(),
54 graph.getEdges());
55 }
56
57 public List<List<E>> search(V src,
58 V dst,
59 EdgeWeight<V, E> wei,
60 int k) {
61
62 weight = wei;
63 source = src;
64 sink = dst;
65 numK = k;
66 // pathCandidates = new PriorityQueue<List<E>>();
67
68 pathResults.clear();
69 pathCandidates.clear();
70
71 // Double check the parameters
72 checkArguments(immutableGraph, src, dst, numK);
73
74 // DefaultResult result = new DefaultResult(src, dst);
75
76 searchKShortestPaths();
77
78 return pathResults;
79 }
80
81 private void checkArguments(Graph<V, E> graph, V src, V dst, int k) {
82 if (graph == null) {
83 throw new NullPointerException("graph is null");
84 }
85 if (!graph.getVertexes().contains(src)) {
86 throw new NullPointerException("source node does not exist");
87 }
88 if (!graph.getVertexes().contains(dst)) {
89 throw new NullPointerException("target node does not exist");
90 }
91 if (k <= 0) {
92 throw new NullPointerException("K is negative or 0");
93 }
94 if (weight == null) {
95 throw new NullPointerException("the cost matrix is null");
96 }
97 }
98
99 private void searchKShortestPaths() {
100 // Step 1: find the shortest path.
101 List<E> shortestPath = searchShortestPath(immutableGraph, source, sink);
102 // no path exists, exit.
103 if (shortestPath == null) {
104 return;
105 }
106
107 // Step 2: update the results.
108 pathResults.add(shortestPath);
109 // pathCandidates.add(shortestPath);
110
111 // Step 3: find the other K-1 paths.
112 while (/*pathCandidates.size() > 0 &&*/pathResults.size() < numK) {
113 // 3.1 the spur node ranges from the first node to the last node in the previous k-shortest path.
114 List<E> lastPath = pathResults.get(pathResults.size() - 1);
115 for (int i = 0; i < lastPath.size(); i++) {
116 // 4.1 convert the graph into mutable.
117 convertGraph();
118 // 4.2 transform the graph.
119 List<E> rootPath = createSpurNode(lastPath, i);
120 transformGraph(rootPath);
121 // 4.3 find the deviation node.
122 V devNode;
123 devNode = getDevNode(rootPath);
124 List<E> spurPath;
125 // 4.4 find the shortest path in the transformed graph.
126 spurPath = searchShortestPath(mutableGraph, devNode, sink);
127 // 4.5 update the path candidates.
128 if (spurPath != null) {
129 // totalPath = rootPath + spurPath;
130 rootPath.addAll(spurPath);
131 pathCandidates.add(rootPath);
132 }
133 }
134 // 3.2 if there is no spur path, exit.
135 if (pathCandidates.size() == 0) {
136 break;
137 }
138 // 3.3 add the path into the results.
139 addPathResult();
140 }
141 }
142
143 private List<E> searchShortestPath(Graph<V, E> graph, V src, V dst) {
144 // Determine the shortest path from the source to the destination by using the Dijkstra algorithm.
145 DijkstraGraphSearch dijkstraAlg = new DijkstraGraphSearch();
146 Set<Path> paths = dijkstraAlg.search(graph, src, dst, weight).paths();
147 Iterator<Path> itr = paths.iterator();
148 if (!itr.hasNext()) {
149 return null;
150 }
151 // return the first shortest path only.
152 return (List<E>) itr.next().edges();
153 }
154
155 private void convertGraph() {
156 // clear the mutableGraph first
157 if (mutableGraph != null) {
158 ((MutableAdjacencyListsGraph) mutableGraph).clear();
159 }
160
161 // create a immutableGraph
162 Set<E> copyEa = immutableGraph.getEdges();
163 Set<V> copyVa = immutableGraph.getVertexes();
164 for (V vertex : copyVa) {
165 mutableGraph.addVertex(vertex);
166 }
167 for (E edge : copyEa) {
168 mutableGraph.addEdge(edge);
169 }
170 }
171
172 private V getDevNode(List<E> path) {
173 V srcA;
174 V dstB;
175
176 if (path.size() == 0) {
177 return source;
178 }
179
180 E temp1 = path.get(path.size() - 1);
181 srcA = temp1.src();
182 dstB = temp1.dst();
183
184 if (path.size() == 1) {
185 if (srcA.equals(source)) {
186 return dstB;
187 } else {
188 return srcA;
189 }
190 } else {
191 E temp2 = path.get(path.size() - 2);
192 if (srcA.equals(temp2.src()) || srcA.equals(temp2.dst())) {
193 return dstB;
194 } else {
195 return srcA;
196 }
197 }
198 }
199
200 private List<E> createSpurNode(List<E> path, int n) {
201 List<E> root = new ArrayList<E>();
202
203 for (int i = 0; i < n; i++) {
204 root.add(path.get(i));
205 }
206 return root;
207 }
208
209 private void transformGraph(List<E> rootPath) {
210 List<E> prePath;
211 //remove edges
212 for (int i = 0; i < pathResults.size(); i++) {
213 prePath = pathResults.get(i);
214 if (prePath.size() == 1) {
215 mutableGraph.removeEdge(prePath.get(0));
216 } else if (comparePath(rootPath, prePath)) {
217 for (int j = 0; j <= rootPath.size(); j++) {
218 mutableGraph.removeEdge(prePath.get(j));
219 }
220 }
221 }
222 for (int i = 0; i < pathCandidates.size(); i++) {
223 prePath = pathCandidates.get(i);
224 if (prePath.size() == 1) {
225 mutableGraph.removeEdge(prePath.get(0));
226 } else if (comparePath(rootPath, prePath)) {
227 for (int j = 0; j <= rootPath.size(); j++) {
228 mutableGraph.removeEdge(prePath.get(j));
229 }
230 }
231 }
232
233 if (rootPath.size() == 0) {
234 return;
235 }
236
237 //remove nodes
238 List<V> nodes = new ArrayList<V>();
239 nodes.add(source);
240 V pre = source;
241 V srcA;
242 V dstB;
243 for (int i = 0; i < rootPath.size() - 1; i++) {
244 E temp = rootPath.get(i);
245 srcA = temp.src();
246 dstB = temp.dst();
247
248 if (srcA.equals(pre)) {
249 nodes.add(dstB);
250 pre = dstB;
251 } else {
252 nodes.add(srcA);
253 pre = srcA;
254 }
255 }
256 for (int i = 0; i < nodes.size(); i++) {
257 mutableGraph.removeVertex(nodes.get(i));
258 }
259 }
260
261 private boolean comparePath(List<E> path1, List<E> path2) {
262 if (path1.size() > path2.size()) {
263 return false;
264 }
265 if (path1.size() == 0) {
266 return true;
267 }
268 for (int i = 0; i < path1.size(); i++) {
269 if (path1.get(i) != path2.get(i)) {
270 return false;
271 }
272 }
273 return true;
274 }
275
276 private void addPathResult() {
277 List<E> sp;
278 sp = pathCandidates.get(0);
279 for (int i = 1; i < pathCandidates.size(); i++) {
280 if (sp.size() > pathCandidates.get(i).size()) {
281 sp = pathCandidates.get(i);
282 }
283 }
284 pathResults.add(sp);
285 // Log.info(sp.toString());
286 pathCandidates.remove(sp);
287 }
288
289}