blob: 0d6e5080bf2c44e4fbd23d90fccdf8933392a6d9 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tome3489412014-08-29 02:30:38 -070016package org.onlab.graph;
17
18import java.util.HashMap;
19import java.util.HashSet;
20import java.util.Iterator;
21import java.util.Map;
22import java.util.Set;
23
24import static com.google.common.base.Preconditions.checkArgument;
25import static com.google.common.base.Preconditions.checkNotNull;
26
27/**
28 * Basis for various graph path search algorithm implementations.
29 *
30 * @param <V> vertex type
31 * @param <E> edge type
32 */
tom144de692014-08-29 11:38:44 -070033public abstract class AbstractGraphPathSearch<V extends Vertex, E extends Edge<V>>
tome3489412014-08-29 02:30:38 -070034 implements GraphPathSearch<V, E> {
35
Thomas Vachuska4353a5a2014-10-27 15:18:10 -070036 private double samenessThreshold = Double.MIN_VALUE;
tome3489412014-08-29 02:30:38 -070037
38 /**
39 * Sets a new sameness threshold for comparing cost values; default is
40 * is {@code 0.000000001}.
41 *
42 * @param threshold fractional double value
43 */
44 public void setSamenessThreshold(double threshold) {
45 samenessThreshold = threshold;
46 }
47
48 /**
49 * Returns the current sameness threshold for comparing cost values.
50 *
51 * @return current threshold
52 */
53 public double samenessThreshold() {
54 return samenessThreshold;
55 }
56
57 /**
58 * Default path search result that uses the DefaultPath to convey paths
59 * in a graph.
60 */
61 protected class DefaultResult implements Result<V, E> {
62
63 private final V src;
64 private final V dst;
65 protected final Set<Path<V, E>> paths = new HashSet<>();
66 protected final Map<V, Double> costs = new HashMap<>();
67 protected final Map<V, Set<E>> parents = new HashMap<>();
68
69 /**
70 * Creates the result of path search.
71 *
72 * @param src path source
73 * @param dst optional path destination
74 */
75 public DefaultResult(V src, V dst) {
76 checkNotNull(src, "Source cannot be null");
77 this.src = src;
78 this.dst = dst;
79 }
80
81 @Override
82 public V src() {
83 return src;
84 }
85
86 @Override
87 public V dst() {
88 return dst;
89 }
90
91 @Override
92 public Set<Path<V, E>> paths() {
93 return paths;
94 }
95
96 @Override
97 public Map<V, Double> costs() {
98 return costs;
99 }
100
101 @Override
102 public Map<V, Set<E>> parents() {
103 return parents;
104 }
105
106 /**
107 * Indicates whether or not the given vertex has a cost yet.
108 *
109 * @param v vertex to test
110 * @return true if the vertex has cost already
111 */
112 boolean hasCost(V v) {
113 return costs.get(v) != null;
114 }
115
116 /**
117 * Returns the current cost to reach the specified vertex.
118 *
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700119 * @param v vertex to reach
tome3489412014-08-29 02:30:38 -0700120 * @return cost to reach the vertex
121 */
122 double cost(V v) {
123 Double c = costs.get(v);
124 return c == null ? Double.MAX_VALUE : c;
125 }
126
127 /**
128 * Updates the cost of the vertex using its existing cost plus the
129 * cost to traverse the specified edge.
130 *
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700131 * @param vertex vertex to update
tome3489412014-08-29 02:30:38 -0700132 * @param edge edge through which vertex is reached
133 * @param cost current cost to reach the vertex from the source
134 * @param replace true to indicate that any accrued edges are to be
135 * cleared; false to indicate that the edge should be
136 * added to the previously accrued edges as they yield
137 * the same cost
138 */
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700139 void updateVertex(V vertex, E edge, double cost, boolean replace) {
140 costs.put(vertex, cost);
tome3489412014-08-29 02:30:38 -0700141 if (edge != null) {
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700142 Set<E> edges = parents.get(vertex);
tome3489412014-08-29 02:30:38 -0700143 if (edges == null) {
144 edges = new HashSet<>();
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700145 parents.put(vertex, edges);
tome3489412014-08-29 02:30:38 -0700146 }
147 if (replace) {
148 edges.clear();
149 }
150 edges.add(edge);
151 }
152 }
153
154 /**
155 * Removes the set of parent edges for the specified vertex.
156 *
157 * @param v vertex
158 */
159 void removeVertex(V v) {
160 parents.remove(v);
161 }
162
163 /**
164 * If possible, relax the specified edge using the supplied base cost
165 * and edge-weight function.
166 *
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700167 * @param edge edge to be relaxed
Thomas Vachuska4d690872014-10-27 08:57:08 -0700168 * @param cost base cost to reach the edge destination vertex
169 * @param ew optional edge weight function
170 * @param forbidNegatives if true negative values will forbid the link
tome3489412014-08-29 02:30:38 -0700171 * @return true if the edge was relaxed; false otherwise
172 */
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700173 boolean relaxEdge(E edge, double cost, EdgeWeight<V, E> ew,
Thomas Vachuska4d690872014-10-27 08:57:08 -0700174 boolean... forbidNegatives) {
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700175 V v = edge.dst();
tome3489412014-08-29 02:30:38 -0700176 double oldCost = cost(v);
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700177 double hopCost = ew == null ? 1.0 : ew.weight(edge);
Thomas Vachuska4d690872014-10-27 08:57:08 -0700178 if (hopCost < 0 && forbidNegatives.length == 1 && forbidNegatives[0]) {
179 return false;
180 }
181
182 double newCost = cost + hopCost;
tome3489412014-08-29 02:30:38 -0700183 boolean relaxed = newCost < oldCost;
Thomas Vachuska4353a5a2014-10-27 15:18:10 -0700184 boolean same = Math.abs(newCost - oldCost) <= samenessThreshold;
tome3489412014-08-29 02:30:38 -0700185 if (same || relaxed) {
Thomas Vachuska7b652ad2014-10-30 14:10:51 -0700186 updateVertex(v, edge, newCost, !same);
tome3489412014-08-29 02:30:38 -0700187 }
188 return relaxed;
189 }
190
191 /**
192 * Builds a set of paths for the specified src/dst vertex pair.
193 */
194 protected void buildPaths() {
195 Set<V> destinations = new HashSet<>();
196 if (dst == null) {
197 destinations.addAll(costs.keySet());
198 } else {
199 destinations.add(dst);
200 }
201
202 // Build all paths between the source and all requested destinations.
203 for (V v : destinations) {
204 // Ignore the source, if it is among the destinations.
205 if (!v.equals(src)) {
206 buildAllPaths(this, src, v);
207 }
208 }
209 }
210
211 }
212
213 /**
214 * Builds a set of all paths between the source and destination using the
215 * graph search result by applying breadth-first search through the parent
216 * edges and vertex costs.
217 *
218 * @param result graph search result
219 * @param src source vertex
220 * @param dst destination vertex
221 */
222 private void buildAllPaths(DefaultResult result, V src, V dst) {
223 DefaultMutablePath<V, E> basePath = new DefaultMutablePath<>();
224 basePath.setCost(result.cost(dst));
225
226 Set<DefaultMutablePath<V, E>> pendingPaths = new HashSet<>();
227 pendingPaths.add(basePath);
228
229 while (!pendingPaths.isEmpty()) {
230 Set<DefaultMutablePath<V, E>> frontier = new HashSet<>();
231
232 for (DefaultMutablePath<V, E> path : pendingPaths) {
233 // For each pending path, locate its first vertex since we
234 // will be moving backwards from it.
235 V firstVertex = firstVertex(path, dst);
236
237 // If the first vertex is our expected source, we have reached
238 // the beginning, so add the this path to the result paths.
239 if (firstVertex.equals(src)) {
240 path.setCost(result.cost(dst));
241 result.paths.add(new DefaultPath<>(path.edges(), path.cost()));
242
243 } else {
244 // If we have not reached the beginning, i.e. the source,
245 // fetch the set of edges leading to the first vertex of
246 // this pending path; if there are none, abandon processing
247 // this path for good.
248 Set<E> firstVertexParents = result.parents.get(firstVertex);
249 if (firstVertexParents == null || firstVertexParents.isEmpty()) {
250 break;
251 }
252
253 // Now iterate over all the edges and for each of them
254 // cloning the current path and then insert that edge to
255 // the path and then add that path to the pending ones.
256 // When processing the last edge, modify the current
257 // pending path rather than cloning a new one.
258 Iterator<E> edges = firstVertexParents.iterator();
259 while (edges.hasNext()) {
260 E edge = edges.next();
261 boolean isLast = !edges.hasNext();
262 DefaultMutablePath<V, E> pendingPath = isLast ? path : new DefaultMutablePath<>(path);
263 pendingPath.insertEdge(edge);
264 frontier.add(pendingPath);
265 }
266 }
267 }
268
269 // All pending paths have been scanned so promote the next frontier
270 pendingPaths = frontier;
271 }
272 }
273
274 // Returns the first vertex of the specified path. This is either the source
275 // of the first edge or, if there are no edges yet, the given destination.
276 private V firstVertex(Path<V, E> path, V dst) {
277 return path.edges().isEmpty() ? dst : path.edges().get(0).src();
278 }
279
280 /**
281 * Checks the specified path search arguments for validity.
282 *
283 * @param graph graph; must not be null
284 * @param src source vertex; must not be null and belong to graph
285 * @param dst optional target vertex; must belong to graph
286 */
287 protected void checkArguments(Graph<V, E> graph, V src, V dst) {
288 checkNotNull(graph, "Graph cannot be null");
289 checkNotNull(src, "Source cannot be null");
290 Set<V> vertices = graph.getVertexes();
291 checkArgument(vertices.contains(src), "Source not in the graph");
292 checkArgument(dst == null || vertices.contains(dst),
293 "Destination not in graph");
294 }
295
296}