tom

Added graph-related utility code.

Showing 26 changed files with 1701 additions and 0 deletions
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
17 <description>Miscellaneous ON.Lab utilities</description> 17 <description>Miscellaneous ON.Lab utilities</description>
18 18
19 <dependencies> 19 <dependencies>
20 + <dependency>
21 + <groupId>com.google.guava</groupId>
22 + <artifactId>guava-testlib</artifactId>
23 + <version>17.0</version>
24 + <scope>test</scope>
25 + </dependency>
20 </dependencies> 26 </dependencies>
21 27
22 </project> 28 </project>
......
1 +package org.onlab.graph;
2 +
3 +import java.util.Objects;
4 +
5 +import static com.google.common.base.Preconditions.checkNotNull;
6 +
7 +/**
8 + * Abstract graph edge implementation.
9 + */
10 +public abstract class AbstractEdge<V extends Vertex> implements Edge<V> {
11 +
12 + private final V src;
13 + private final V dst;
14 +
15 + /**
16 + * Creates a new edge between the specified source and destination vertexes.
17 + *
18 + * @param src source vertex
19 + * @param dst destination vertex
20 + */
21 + public AbstractEdge(V src, V dst) {
22 + this.src = checkNotNull(src, "Source vertex cannot be null");
23 + this.dst = checkNotNull(dst, "Destination vertex cannot be null");
24 + }
25 +
26 + @Override
27 + public V src() {
28 + return src;
29 + }
30 +
31 + @Override
32 + public V dst() {
33 + return dst;
34 + }
35 +
36 + @Override
37 + public int hashCode() {
38 + return Objects.hash(src, dst);
39 + }
40 +
41 + @Override
42 + public boolean equals(Object obj) {
43 + if (obj instanceof AbstractEdge) {
44 + final AbstractEdge other = (AbstractEdge) obj;
45 + return Objects.equals(this.src, other.src) && Objects.equals(this.dst, other.dst);
46 + }
47 + return false;
48 + }
49 +
50 + @Override
51 + public String toString() {
52 + return com.google.common.base.Objects.toStringHelper(this)
53 + .add("src", src)
54 + .add("dst", dst)
55 + .toString();
56 + }
57 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.HashMap;
4 +import java.util.HashSet;
5 +import java.util.Iterator;
6 +import java.util.Map;
7 +import java.util.Set;
8 +
9 +import static com.google.common.base.Preconditions.checkArgument;
10 +import static com.google.common.base.Preconditions.checkNotNull;
11 +
12 +/**
13 + * Basis for various graph path search algorithm implementations.
14 + *
15 + * @param <V> vertex type
16 + * @param <E> edge type
17 + */
18 +public abstract class AbstractPathSearch<V extends Vertex, E extends Edge<V>>
19 + implements GraphPathSearch<V, E> {
20 +
21 + private double samenessThreshold = 0.000000001;
22 +
23 + /**
24 + * Sets a new sameness threshold for comparing cost values; default is
25 + * is {@code 0.000000001}.
26 + *
27 + * @param threshold fractional double value
28 + */
29 + public void setSamenessThreshold(double threshold) {
30 + samenessThreshold = threshold;
31 + }
32 +
33 + /**
34 + * Returns the current sameness threshold for comparing cost values.
35 + *
36 + * @return current threshold
37 + */
38 + public double samenessThreshold() {
39 + return samenessThreshold;
40 + }
41 +
42 + /**
43 + * Default path search result that uses the DefaultPath to convey paths
44 + * in a graph.
45 + */
46 + protected class DefaultResult implements Result<V, E> {
47 +
48 + private final V src;
49 + private final V dst;
50 + protected final Set<Path<V, E>> paths = new HashSet<>();
51 + protected final Map<V, Double> costs = new HashMap<>();
52 + protected final Map<V, Set<E>> parents = new HashMap<>();
53 +
54 + /**
55 + * Creates the result of path search.
56 + *
57 + * @param src path source
58 + * @param dst optional path destination
59 + */
60 + public DefaultResult(V src, V dst) {
61 + checkNotNull(src, "Source cannot be null");
62 + this.src = src;
63 + this.dst = dst;
64 + }
65 +
66 + @Override
67 + public V src() {
68 + return src;
69 + }
70 +
71 + @Override
72 + public V dst() {
73 + return dst;
74 + }
75 +
76 + @Override
77 + public Set<Path<V, E>> paths() {
78 + return paths;
79 + }
80 +
81 + @Override
82 + public Map<V, Double> costs() {
83 + return costs;
84 + }
85 +
86 + @Override
87 + public Map<V, Set<E>> parents() {
88 + return parents;
89 + }
90 +
91 + /**
92 + * Indicates whether or not the given vertex has a cost yet.
93 + *
94 + * @param v vertex to test
95 + * @return true if the vertex has cost already
96 + */
97 + boolean hasCost(V v) {
98 + return costs.get(v) != null;
99 + }
100 +
101 + /**
102 + * Returns the current cost to reach the specified vertex.
103 + *
104 + * @return cost to reach the vertex
105 + */
106 + double cost(V v) {
107 + Double c = costs.get(v);
108 + return c == null ? Double.MAX_VALUE : c;
109 + }
110 +
111 + /**
112 + * Updates the cost of the vertex using its existing cost plus the
113 + * cost to traverse the specified edge.
114 + *
115 + * @param v vertex
116 + * @param edge edge through which vertex is reached
117 + * @param cost current cost to reach the vertex from the source
118 + * @param replace true to indicate that any accrued edges are to be
119 + * cleared; false to indicate that the edge should be
120 + * added to the previously accrued edges as they yield
121 + * the same cost
122 + */
123 + void updateVertex(V v, E edge, double cost, boolean replace) {
124 + costs.put(v, cost);
125 + if (edge != null) {
126 + Set<E> edges = parents.get(v);
127 + if (edges == null) {
128 + edges = new HashSet<>();
129 + parents.put(v, edges);
130 + }
131 + if (replace) {
132 + edges.clear();
133 + }
134 + edges.add(edge);
135 + }
136 + }
137 +
138 + /**
139 + * Removes the set of parent edges for the specified vertex.
140 + *
141 + * @param v vertex
142 + */
143 + void removeVertex(V v) {
144 + parents.remove(v);
145 + }
146 +
147 + /**
148 + * If possible, relax the specified edge using the supplied base cost
149 + * and edge-weight function.
150 + *
151 + * @param e edge to be relaxed
152 + * @param cost base cost to reach the edge destination vertex
153 + * @param ew optional edge weight function
154 + * @return true if the edge was relaxed; false otherwise
155 + */
156 + boolean relaxEdge(E e, double cost, EdgeWeight<V, E> ew) {
157 + V v = e.dst();
158 + double oldCost = cost(v);
159 + double newCost = cost + (ew == null ? 1.0 : ew.weight(e));
160 + boolean relaxed = newCost < oldCost;
161 + boolean same = Math.abs(newCost - oldCost) < samenessThreshold;
162 + if (same || relaxed) {
163 + updateVertex(v, e, newCost, !same);
164 + }
165 + return relaxed;
166 + }
167 +
168 + /**
169 + * Builds a set of paths for the specified src/dst vertex pair.
170 + */
171 + protected void buildPaths() {
172 + Set<V> destinations = new HashSet<>();
173 + if (dst == null) {
174 + destinations.addAll(costs.keySet());
175 + } else {
176 + destinations.add(dst);
177 + }
178 +
179 + // Build all paths between the source and all requested destinations.
180 + for (V v : destinations) {
181 + // Ignore the source, if it is among the destinations.
182 + if (!v.equals(src)) {
183 + buildAllPaths(this, src, v);
184 + }
185 + }
186 + }
187 +
188 + }
189 +
190 + /**
191 + * Builds a set of all paths between the source and destination using the
192 + * graph search result by applying breadth-first search through the parent
193 + * edges and vertex costs.
194 + *
195 + * @param result graph search result
196 + * @param src source vertex
197 + * @param dst destination vertex
198 + */
199 + private void buildAllPaths(DefaultResult result, V src, V dst) {
200 + DefaultMutablePath<V, E> basePath = new DefaultMutablePath<>();
201 + basePath.setCost(result.cost(dst));
202 +
203 + Set<DefaultMutablePath<V, E>> pendingPaths = new HashSet<>();
204 + pendingPaths.add(basePath);
205 +
206 + while (!pendingPaths.isEmpty()) {
207 + Set<DefaultMutablePath<V, E>> frontier = new HashSet<>();
208 +
209 + for (DefaultMutablePath<V, E> path : pendingPaths) {
210 + // For each pending path, locate its first vertex since we
211 + // will be moving backwards from it.
212 + V firstVertex = firstVertex(path, dst);
213 +
214 + // If the first vertex is our expected source, we have reached
215 + // the beginning, so add the this path to the result paths.
216 + if (firstVertex.equals(src)) {
217 + path.setCost(result.cost(dst));
218 + result.paths.add(new DefaultPath<>(path.edges(), path.cost()));
219 +
220 + } else {
221 + // If we have not reached the beginning, i.e. the source,
222 + // fetch the set of edges leading to the first vertex of
223 + // this pending path; if there are none, abandon processing
224 + // this path for good.
225 + Set<E> firstVertexParents = result.parents.get(firstVertex);
226 + if (firstVertexParents == null || firstVertexParents.isEmpty()) {
227 + break;
228 + }
229 +
230 + // Now iterate over all the edges and for each of them
231 + // cloning the current path and then insert that edge to
232 + // the path and then add that path to the pending ones.
233 + // When processing the last edge, modify the current
234 + // pending path rather than cloning a new one.
235 + Iterator<E> edges = firstVertexParents.iterator();
236 + while (edges.hasNext()) {
237 + E edge = edges.next();
238 + boolean isLast = !edges.hasNext();
239 + DefaultMutablePath<V, E> pendingPath = isLast ? path : new DefaultMutablePath<>(path);
240 + pendingPath.insertEdge(edge);
241 + frontier.add(pendingPath);
242 + }
243 + }
244 + }
245 +
246 + // All pending paths have been scanned so promote the next frontier
247 + pendingPaths = frontier;
248 + }
249 + }
250 +
251 + // Returns the first vertex of the specified path. This is either the source
252 + // of the first edge or, if there are no edges yet, the given destination.
253 + private V firstVertex(Path<V, E> path, V dst) {
254 + return path.edges().isEmpty() ? dst : path.edges().get(0).src();
255 + }
256 +
257 + /**
258 + * Checks the specified path search arguments for validity.
259 + *
260 + * @param graph graph; must not be null
261 + * @param src source vertex; must not be null and belong to graph
262 + * @param dst optional target vertex; must belong to graph
263 + */
264 + protected void checkArguments(Graph<V, E> graph, V src, V dst) {
265 + checkNotNull(graph, "Graph cannot be null");
266 + checkNotNull(src, "Source cannot be null");
267 + Set<V> vertices = graph.getVertexes();
268 + checkArgument(vertices.contains(src), "Source not in the graph");
269 + checkArgument(dst == null || vertices.contains(dst),
270 + "Destination not in graph");
271 + }
272 +
273 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableSet;
4 +import com.google.common.collect.ImmutableSetMultimap;
5 +
6 +import java.util.Objects;
7 +import java.util.Set;
8 +
9 +import static com.google.common.base.Preconditions.checkNotNull;
10 +
11 +/**
12 + * Immutable graph implemented using adjacency lists.
13 + *
14 + * @param <V> vertex type
15 + * @param <E> edge type
16 + */
17 +public class AdjacencyListsGraph<V extends Vertex, E extends Edge<V>> implements Graph<V, E> {
18 +
19 + private final Set<V> vertexes;
20 + private final Set<E> edges;
21 +
22 + private final ImmutableSetMultimap<V, E> sources;
23 + private final ImmutableSetMultimap<V, E> destinations;
24 +
25 + private final Set<E> noEdges = ImmutableSet.of();
26 +
27 + /**
28 + * Creates a graph comprising of the specified vertexes and edges.
29 + *
30 + * @param vertexes set of graph vertexes
31 + * @param edges set of graph edges
32 + */
33 + public AdjacencyListsGraph(Set<V> vertexes, Set<E> edges) {
34 + checkNotNull(vertexes, "Vertex set cannot be null");
35 + checkNotNull(edges, "Edge set cannot be null");
36 +
37 + // Record ingress/egress edges for each vertex.
38 + ImmutableSetMultimap.Builder<V, E> srcMap = ImmutableSetMultimap.builder();
39 + ImmutableSetMultimap.Builder<V, E> dstMap = ImmutableSetMultimap.builder();
40 +
41 + // Also make sure that all edge end-points are added as vertexes
42 + ImmutableSet.Builder<V> actualVertexes = ImmutableSet.builder();
43 + actualVertexes.addAll(vertexes);
44 +
45 + for (E edge : edges) {
46 + srcMap.put(edge.src(), edge);
47 + actualVertexes.add(edge.src());
48 + dstMap.put(edge.dst(), edge);
49 + actualVertexes.add(edge.dst());
50 + }
51 +
52 + // Make an immutable copy of the edge and vertex sets
53 + this.edges = ImmutableSet.copyOf(edges);
54 + this.vertexes = actualVertexes.build();
55 +
56 + // Build immutable copies of sources and destinations edge maps
57 + sources = srcMap.build();
58 + destinations = dstMap.build();
59 + }
60 +
61 + @Override
62 + public Set<V> getVertexes() {
63 + return vertexes;
64 + }
65 +
66 + @Override
67 + public Set<E> getEdges() {
68 + return edges;
69 + }
70 +
71 + @Override
72 + public Set<E> getEdgesFrom(V src) {
73 + return sources.get(src);
74 + }
75 +
76 + @Override
77 + public Set<E> getEdgesTo(V dst) {
78 + return destinations.get(dst);
79 + }
80 +
81 + @Override
82 + public boolean equals(Object obj) {
83 + if (obj instanceof AdjacencyListsGraph) {
84 + AdjacencyListsGraph that = (AdjacencyListsGraph) obj;
85 + return this.getClass() == that.getClass() &&
86 + Objects.equals(this.vertexes, that.vertexes) &&
87 + Objects.equals(this.edges, that.edges);
88 + }
89 + return false;
90 + }
91 +
92 + @Override
93 + public int hashCode() {
94 + return Objects.hash(vertexes, edges);
95 + }
96 +
97 + @Override
98 + public String toString() {
99 + return com.google.common.base.Objects.toStringHelper(this)
100 + .add("vertexes", vertexes)
101 + .add("edges", edges)
102 + .toString();
103 + }
104 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableList;
4 +
5 +import java.util.ArrayList;
6 +import java.util.List;
7 +import java.util.Objects;
8 +
9 +import static com.google.common.base.Preconditions.checkArgument;
10 +import static com.google.common.base.Preconditions.checkNotNull;
11 +
12 +/**
13 + * Simple concrete implementation of a directed graph path.
14 + */
15 +public class DefaultMutablePath<V extends Vertex, E extends Edge<V>> implements MutablePath<V, E> {
16 +
17 + private V src = null;
18 + private V dst = null;
19 + private final List<E> edges = new ArrayList<>();
20 + private double cost = 0.0;
21 +
22 + /**
23 + * Creates a new empty path.
24 + */
25 + public DefaultMutablePath() {
26 + }
27 +
28 + /**
29 + * Creates a new path as a copy of another path.
30 + *
31 + * @param path path to be copied
32 + */
33 + public DefaultMutablePath(Path<V, E> path) {
34 + checkNotNull(path, "Path cannot be null");
35 + this.src = path.src();
36 + this.dst = path.dst();
37 + this.cost = path.cost();
38 + edges.addAll(path.edges());
39 + }
40 +
41 + @Override
42 + public V src() {
43 + return src;
44 + }
45 +
46 + @Override
47 + public V dst() {
48 + return dst;
49 + }
50 +
51 + @Override
52 + public double cost() {
53 + return cost;
54 + }
55 +
56 + @Override
57 + public List<E> edges() {
58 + return ImmutableList.copyOf(edges);
59 + }
60 +
61 + @Override
62 + public void setCost(double cost) {
63 + this.cost = cost;
64 + }
65 +
66 + @Override
67 + public Path<V, E> toImmutable() {
68 + return new DefaultPath<>(edges, cost);
69 + }
70 +
71 + @Override
72 + public void appendEdge(E edge) {
73 + checkNotNull(edge, "Edge cannot be null");
74 + checkArgument(edges.isEmpty() || dst.equals(edge.src()),
75 + "Edge source must be the same as the current path destination");
76 + dst = edge.dst();
77 + edges.add(edge);
78 + }
79 +
80 + @Override
81 + public void insertEdge(E edge) {
82 + checkNotNull(edge, "Edge cannot be null");
83 + checkArgument(edges.isEmpty() || src.equals(edge.dst()),
84 + "Edge destination must be the same as the current path source");
85 + src = edge.src();
86 + edges.add(0, edge);
87 + }
88 +
89 + @Override
90 + public String toString() {
91 + return com.google.common.base.Objects.toStringHelper(this)
92 + .add("src", src)
93 + .add("dst", dst)
94 + .add("cost", cost)
95 + .add("edges", edges)
96 + .toString();
97 + }
98 +
99 + @Override
100 + public int hashCode() {
101 + return Objects.hash(src, dst, edges, cost);
102 + }
103 +
104 + @Override
105 + public boolean equals(Object obj) {
106 + if (obj instanceof DefaultMutablePath) {
107 + final DefaultMutablePath other = (DefaultMutablePath) obj;
108 + return super.equals(obj) &&
109 + Objects.equals(this.src, other.src) &&
110 + Objects.equals(this.dst, other.dst) &&
111 + Objects.equals(this.cost, other.cost) &&
112 + Objects.equals(this.edges, other.edges);
113 + }
114 + return false;
115 + }
116 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableList;
4 +
5 +import java.util.Collections;
6 +import java.util.List;
7 +import java.util.Objects;
8 +
9 +import static com.google.common.base.Preconditions.checkArgument;
10 +import static com.google.common.base.Preconditions.checkNotNull;
11 +
12 +/**
13 + * Simple concrete implementation of a directed graph path.
14 + */
15 +public class DefaultPath<V extends Vertex, E extends Edge<V>> implements Path<V, E> {
16 +
17 + private final V src;
18 + private final V dst;
19 + private final List<E> edges;
20 + private double cost = 0.0;
21 +
22 + /**
23 + * Creates a new path from the specified list of edges and cost.
24 + *
25 + * @param edges list of path edges
26 + * @param cost path cost as a unit-less number
27 + */
28 + public DefaultPath(List<E> edges, double cost) {
29 + checkNotNull(edges, "Edges list must not be null");
30 + checkArgument(!edges.isEmpty(), "There must be at least one edge");
31 + this.edges = ImmutableList.copyOf(edges);
32 + this.src = edges.get(0).src();
33 + this.dst = edges.get(edges.size() - 1).dst();
34 + this.cost = cost;
35 + }
36 +
37 + @Override
38 + public V src() {
39 + return src;
40 + }
41 +
42 + @Override
43 + public V dst() {
44 + return dst;
45 + }
46 +
47 + @Override
48 + public double cost() {
49 + return cost;
50 + }
51 +
52 + @Override
53 + public List<E> edges() {
54 + return Collections.unmodifiableList(edges);
55 + }
56 +
57 + @Override
58 + public String toString() {
59 + return com.google.common.base.Objects.toStringHelper(this)
60 + .add("src", src)
61 + .add("dst", dst)
62 + .add("cost", cost)
63 + .add("edges", edges)
64 + .toString();
65 + }
66 +
67 + @Override
68 + public int hashCode() {
69 + return Objects.hash(src, dst, edges, cost);
70 + }
71 +
72 + @Override
73 + public boolean equals(Object obj) {
74 + if (obj instanceof DefaultPath) {
75 + final DefaultPath other = (DefaultPath) obj;
76 + return super.equals(obj) &&
77 + Objects.equals(this.src, other.src) &&
78 + Objects.equals(this.dst, other.dst) &&
79 + Objects.equals(this.cost, other.cost) &&
80 + Objects.equals(this.edges, other.edges);
81 + }
82 + return false;
83 + }
84 +
85 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.ArrayList;
4 +import java.util.Comparator;
5 +import java.util.Set;
6 +
7 +/**
8 + * Dijkstra shortest-path graph search algorithm capable of finding not just
9 + * one, but all shortest paths between the source and destinations.
10 + */
11 +public class DijkstraGraphSearch<V extends Vertex, E extends Edge<V>>
12 + extends AbstractPathSearch<V, E> {
13 +
14 + @Override
15 + public Result<V, E> search(Graph<V, E> g, V src, V dst, EdgeWeight<V, E> ew) {
16 + checkArguments(g, src, dst);
17 +
18 + // Use the default result to remember cumulative costs and parent
19 + // edges to each each respective vertex.
20 + DefaultResult result = new DefaultResult(src, dst);
21 +
22 + // Cost to reach the source vertex is 0 of course.
23 + result.updateVertex(src, null, 0.0, false);
24 +
25 + // Use the min priority queue to progressively find each nearest
26 + // vertex until we reach the desired destination, if one was given,
27 + // or until we reach all possible destinations.
28 + Heap<V> minQueue = createMinQueue(g.getVertexes(),
29 + new PathCostComparator(result));
30 + while (!minQueue.isEmpty()) {
31 + // Get the nearest vertex
32 + V nearest = minQueue.extractExtreme();
33 + if (nearest.equals(dst)) {
34 + break;
35 + }
36 +
37 + // Find its cost and use it to determine if the vertex is reachable.
38 + double cost = result.cost(nearest);
39 + if (cost < Double.MAX_VALUE) {
40 + // If the vertex is reachable, relax all its egress edges.
41 + for (E e : g.getEdgesFrom(nearest)) {
42 + result.relaxEdge(e, cost, ew);
43 + }
44 + }
45 +
46 + // Re-prioritize the min queue.
47 + minQueue.heapify();
48 + }
49 +
50 + // Now construct a set of paths from the results.
51 + result.buildPaths();
52 + return result;
53 + }
54 +
55 + // Compares path weights using their accrued costs; used for sorting the
56 + // min priority queue.
57 + private final class PathCostComparator implements Comparator<V> {
58 + private final DefaultResult result;
59 +
60 + private PathCostComparator(DefaultResult result) {
61 + this.result = result;
62 + }
63 +
64 + @Override
65 + public int compare(V v1, V v2) {
66 + double delta = result.cost(v2) - result.cost(v1);
67 + return delta < 0 ? -1 : (delta > 0 ? 1 : 0);
68 + }
69 + }
70 +
71 + // Creates a min priority queue from the specified vertexes and comparator.
72 + private Heap<V> createMinQueue(Set<V> vertexes, Comparator<V> comparator) {
73 + return new Heap<>(new ArrayList<>(vertexes), comparator);
74 + }
75 +
76 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Representation of a graph edge.
5 + *
6 + * @param <V> vertex type
7 + */
8 +public interface Edge<V extends Vertex> {
9 +
10 + /**
11 + * Returns the edge source vertex.
12 + *
13 + * @return source vertex
14 + */
15 + V src();
16 +
17 + /**
18 + * Returns the edge destination vertex.
19 + *
20 + * @return destination vertex
21 + */
22 + V dst();
23 +
24 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Abstraction of a graph edge weight function.
5 + */
6 +public interface EdgeWeight<V extends Vertex, E extends Edge<V>> {
7 +
8 + /**
9 + * Returns the weight of the given edge as a unit-less number.
10 + *
11 + * @param edge edge to be weighed
12 + * @return edge weight as a unit-less number
13 + */
14 + double weight(E edge);
15 +
16 +}
1 +package org.onlab.graph;
2 +
3 +
4 +import java.util.Set;
5 +
6 +/**
7 + * Abstraction of a directed graph structure.
8 + *
9 + * @param <V> vertex type
10 + * @param <E> edge type
11 + */
12 +public interface Graph<V extends Vertex, E extends Edge> {
13 +
14 + /**
15 + * Returns the set of vertexes comprising the graph.
16 + *
17 + * @return set of vertexes
18 + */
19 + Set<V> getVertexes();
20 +
21 + /**
22 + * Returns the set of edges comprising the graph.
23 + *
24 + * @return set of edges
25 + */
26 + Set<E> getEdges();
27 +
28 + /**
29 + * Returns all edges leading out from the specified source vertex.
30 + *
31 + * @param src source vertex
32 + * @return set of egress edges; empty if no such edges
33 + */
34 + Set<E> getEdgesFrom(V src);
35 +
36 + /**
37 + * Returns all edges leading towards the specified destination vertex.
38 + *
39 + * @param dst destination vertex
40 + * @return set of ingress vertexes; empty if no such edges
41 + */
42 + Set<E> getEdgesTo(V dst);
43 +
44 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.Map;
4 +import java.util.Set;
5 +
6 +/**
7 + * Representation of a graph path search algorithm.
8 + *
9 + * @param <V> vertex type
10 + * @param <E> edge type
11 + */
12 +public interface GraphPathSearch<V extends Vertex, E extends Edge<V>> {
13 +
14 + /**
15 + * Abstraction of a path search result.
16 + */
17 + public interface Result<V extends Vertex, E extends Edge<V>> {
18 +
19 + /**
20 + * Returns the search source.
21 + *
22 + * @return search source
23 + */
24 + public V src();
25 +
26 + /**
27 + * Returns the search destination, if was was given.
28 + *
29 + * @return optional search destination
30 + */
31 + public V dst();
32 +
33 + /**
34 + * Returns the set of paths produced as a result of the graph search.
35 + *
36 + * @return set of paths
37 + */
38 + Set<Path<V, E>> paths();
39 +
40 + /**
41 + * Returns bindings of each vertex to its parent edges in the path.
42 + *
43 + * @return map of vertex to its parent edge bindings
44 + */
45 + public Map<V, Set<E>> parents();
46 +
47 + /**
48 + * Return a bindings of each vertex to its cost in the path.
49 + *
50 + * @return map of vertex to path cost bindings
51 + */
52 + public Map<V, Double> costs();
53 + }
54 +
55 + /**
56 + * Searches the specified graph.
57 + *
58 + * @param graph graph to be searched
59 + * @param src optional source vertex
60 + * @param dst optional destination vertex; if null paths to all vertex
61 + * destinations will be searched
62 + * @param weight optional edge-weight; if null cost of each edge will be
63 + * assumed to be 1.0
64 + * @return search results
65 + */
66 + Result<V, E> search(Graph<V, E> graph, V src, V dst, EdgeWeight<V, E> weight);
67 +
68 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Representation of a graph search algorithm and its outcome.
5 + *
6 + * @param <V> vertex type
7 + * @param <E> edge type
8 + */
9 +public interface GraphSearch<V extends Vertex, E extends Edge<V>> {
10 +
11 + /**
12 + * Notion of a graph search result.
13 + */
14 + public interface Result<V extends Vertex, E extends Edge<V>> {
15 + }
16 +
17 + /**
18 + * Searches the specified graph.
19 + *
20 + * @param graph graph to be searched
21 + * @param weight optional edge-weight; if null cost of each edge will be
22 + * assumed to be 1.0
23 + *
24 + * @return search results
25 + */
26 + Result search(Graph<V, E> graph, EdgeWeight<V, E> weight);
27 +
28 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableList;
4 +
5 +import java.util.Comparator;
6 +import java.util.Iterator;
7 +import java.util.List;
8 +import java.util.Objects;
9 +
10 +import static com.google.common.base.Preconditions.checkNotNull;
11 +
12 +/**
13 + * Implementation of an array-backed heap structure whose sense of order is
14 + * imposed by the provided comparator.
15 + * <p/>
16 + * While this provides similar functionality to {@link java.util.PriorityQueue}
17 + * data structure, one key difference is that external entities can control
18 + * when to restore the heap property, which is done through invocation of the
19 + * {@link #heapify} method.
20 + * <p/>
21 + * This class is not thread-safe and care must be taken to prevent concurrent
22 + * modifications.
23 + *
24 + * @param <T> type of the items on the heap
25 + */
26 +public class Heap<T> {
27 +
28 + private static final String E_HEAP_READONLY = "Heap iterator is read-only";
29 + private static final String E_HEAP_END = "Heap iterator reached end of heap";
30 +
31 + private final List<T> data;
32 + private final Comparator<T> comparator;
33 +
34 + /**
35 + * Creates a new heap backed by the specified list. In the interest of
36 + * efficiency, the list should be array-backed. Also, for the same reason,
37 + * the data is not copied and therefore, the caller must assure that the
38 + * backing data is not altered in any way.
39 + *
40 + * @param data backing data list
41 + * @param comparator comparator for ordering the heap items
42 + */
43 + public Heap(List<T> data, Comparator<T> comparator) {
44 + this.data = checkNotNull(data, "Data cannot be null");
45 + this.comparator = checkNotNull(comparator, "Comparator cannot be null");
46 + heapify();
47 + }
48 +
49 + /**
50 + * Restores the heap property by re-arranging the elements in the backing
51 + * array as necessary following any heap modifications.
52 + */
53 + public void heapify() {
54 + for (int i = data.size() / 2; i >= 0; i--) {
55 + heapify(i);
56 + }
57 + }
58 +
59 + /**
60 + * Returns the current size of the heap.
61 + *
62 + * @return number of items in the heap
63 + */
64 + public int size() {
65 + return data.size();
66 + }
67 +
68 + /**
69 + * Returns true if there are no items in the heap.
70 + *
71 + * @return true if heap is empty
72 + */
73 + public boolean isEmpty() {
74 + return data.isEmpty();
75 + }
76 +
77 + /**
78 + * Returns the most extreme item in the heap.
79 + *
80 + * @return heap extreme or null if the heap is empty
81 + */
82 + public T extreme() {
83 + return data.isEmpty() ? null : data.get(0);
84 + }
85 +
86 + /**
87 + * Extracts and returns the most extreme item from the heap.
88 + *
89 + * @return heap extreme or null if the heap is empty
90 + */
91 + public T extractExtreme() {
92 + if (!isEmpty()) {
93 + T extreme = extreme();
94 +
95 + data.set(0, data.get(data.size() - 1));
96 + data.remove(data.size() - 1);
97 + heapify();
98 + return extreme;
99 + }
100 + return null;
101 + }
102 +
103 + /**
104 + * Inserts the specified item into the heap and returns the modified heap.
105 + *
106 + * @param item item to be inserted
107 + * @return the heap self
108 + * @throws IllegalArgumentException if the heap is already full
109 + */
110 + public Heap<T> insert(T item) {
111 + data.add(item);
112 + bubbleUp();
113 + return this;
114 + }
115 +
116 + /**
117 + * Returns iterator to traverse the heap level-by-level. This iterator
118 + * does not permit removal of items.
119 + *
120 + * @return non-destructive heap iterator
121 + */
122 + public Iterator<T> iterator() {
123 + return ImmutableList.copyOf(data).iterator();
124 + }
125 +
126 + // Bubbles up the last item in the heap to its proper position to restore
127 + // the heap property.
128 + private void bubbleUp() {
129 + int child = data.size() - 1;
130 + while (child > 0) {
131 + int parent = child / 2;
132 + if (comparator.compare(data.get(child), data.get(parent)) < 0) {
133 + break;
134 + }
135 + swap(child, parent);
136 + child = parent;
137 + }
138 + }
139 +
140 + // Restores the heap property of the specified heap layer.
141 + private void heapify(int i) {
142 + int left = 2 * i + 1;
143 + int right = 2 * i;
144 + int extreme = i;
145 +
146 + if (left < data.size() &&
147 + comparator.compare(data.get(extreme), data.get(left)) < 0) {
148 + extreme = left;
149 + }
150 +
151 + if (right < data.size() &&
152 + comparator.compare(data.get(extreme), data.get(right)) < 0) {
153 + extreme = right;
154 + }
155 +
156 + if (extreme != i) {
157 + swap(i, extreme);
158 + heapify(extreme);
159 + }
160 + }
161 +
162 + // Swaps two heap items identified by their respective indexes.
163 + private void swap(int i, int k) {
164 + T aux = data.get(i);
165 + data.set(i, data.get(k));
166 + data.set(k, aux);
167 + }
168 +
169 + @Override
170 + public boolean equals(Object obj) {
171 + if (obj instanceof Heap) {
172 + Heap that = (Heap) obj;
173 + return this.getClass() == that.getClass() &&
174 + Objects.equals(this.comparator, that.comparator) &&
175 + Objects.deepEquals(this.data, that.data);
176 + }
177 + return false;
178 + }
179 +
180 + @Override
181 + public int hashCode() {
182 + return Objects.hash(comparator, data);
183 + }
184 +
185 + @Override
186 + public String toString() {
187 + return com.google.common.base.Objects.toStringHelper(this)
188 + .add("data", data)
189 + .add("comparator", comparator)
190 + .toString();
191 + }
192 +
193 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Abstraction of a mutable graph that can be constructed gradually.
5 + */
6 +public interface MutableGraph<V extends Vertex, E extends Edge> extends Graph<V, E> {
7 +
8 + /**
9 + * Adds the specified vertex to this graph.
10 + *
11 + * @param vertex new vertex
12 + */
13 + void addVertex(V vertex);
14 +
15 + /**
16 + * Removes the specified vertex from the graph.
17 + *
18 + * @param vertex vertex to be removed
19 + */
20 + void removeVertex(V vertex);
21 +
22 + /**
23 + * Adds the specified edge to this graph. If the edge vertexes are not
24 + * already in the graph, they will be added as well.
25 + *
26 + * @param edge new edge
27 + */
28 + void addEdge(E edge);
29 +
30 + /**
31 + * Removes the specified edge from the graph.
32 + *
33 + * @param edge edge to be removed
34 + */
35 + void removeEdge(E edge);
36 +
37 + /**
38 + * Returns an immutable copy of this graph.
39 + *
40 + * @return immutable copy
41 + */
42 + Graph<V, E> toImmutable();
43 +
44 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Abstraction of a mutable path that allows gradual construction.
5 + */
6 +public interface MutablePath<V extends Vertex, E extends Edge<V>> extends Path<V, E> {
7 +
8 + /**
9 + * Inserts a new edge at the beginning of this path. The edge must be
10 + * adjacent to the prior start of the path.
11 + *
12 + * @param edge edge to be inserted
13 + */
14 + void insertEdge(E edge);
15 +
16 + /**
17 + * Appends a new edge at the end of the this path. The edge must be
18 + * adjacent to the prior end of the path.
19 + *
20 + * @param edge edge to be inserted
21 + */
22 + void appendEdge(E edge);
23 +
24 + /**
25 + * Sets the total path cost as a unit-less double.
26 + *
27 + * @param cost new path cost
28 + */
29 + void setCost(double cost);
30 +
31 + /**
32 + * Returns an immutable copy of this path.
33 + *
34 + * @return immutable copy
35 + */
36 + Path<V, E> toImmutable();
37 +
38 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.List;
4 +
5 +/**
6 + * Representation of a path in a graph as a sequence of edges. Paths are
7 + * assumed to be continuous, where adjacent edges must share a vertex.
8 + *
9 + * @param <V> vertex type
10 + * @param <E> edge type
11 + */
12 +public interface Path<V extends Vertex, E extends Edge<V>> extends Edge<V> {
13 +
14 + /**
15 + * Returns the list of edges comprising the path. Adjacent edges will
16 + * share the same vertex, meaning that a source of one edge, will be the
17 + * same as the destination of the prior edge.
18 + *
19 + * @return list of path edges
20 + */
21 + List<E> edges();
22 +
23 + /**
24 + * Returns the total cost of the path as a unit-less number.
25 + *
26 + * @return path cost as a unit-less number
27 + */
28 + double cost();
29 +
30 +}
1 +package org.onlab.graph;
2 +
3 +/**
4 + * Representation of a graph vertex.
5 + */
6 +public interface Vertex {
7 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.testing.EqualsTester;
4 +import org.junit.Test;
5 +
6 +/**
7 + * Test of the base edge implementation.
8 + */
9 +public class AbstractEdgeTest {
10 +
11 + @Test
12 + public void equality() {
13 + TestVertex v1 = new TestVertex("1");
14 + TestVertex v2 = new TestVertex("2");
15 + new EqualsTester()
16 + .addEqualityGroup(new TestEdge(v1, v2, 1),
17 + new TestEdge(v1, v2, 1))
18 + .addEqualityGroup(new TestEdge(v2, v1, 1))
19 + .testEquals();
20 + }
21 +
22 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableSet;
4 +import org.junit.Test;
5 +
6 +/**
7 + * Base for all graph search tests.
8 + */
9 +public abstract class AbstractGraphSearchTest extends GraphTest {
10 +
11 + /**
12 + * Creates a graph search to be tested.
13 + *
14 + * @return graph search
15 + */
16 + protected abstract GraphPathSearch<TestVertex, TestEdge> graphSearch();
17 +
18 + @Test(expected = IllegalArgumentException.class)
19 + public void badSource() {
20 + graphSearch().search(new AdjacencyListsGraph<>(ImmutableSet.of(B, C),
21 + ImmutableSet.of(new TestEdge(B, C, 1))),
22 + A, H, weight);
23 + }
24 +
25 + @Test(expected = NullPointerException.class)
26 + public void nullSource() {
27 + graphSearch().search(new AdjacencyListsGraph<>(ImmutableSet.of(B, C),
28 + ImmutableSet.of(new TestEdge(B, C, 1))),
29 + null, H, weight);
30 + }
31 +
32 + @Test(expected = NullPointerException.class)
33 + public void nullGraph() {
34 + graphSearch().search(null, A, H, weight);
35 + }
36 +
37 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableSet;
4 +import com.google.common.testing.EqualsTester;
5 +import org.junit.Test;
6 +
7 +import java.util.Set;
8 +
9 +import static org.junit.Assert.assertEquals;
10 +
11 +/**
12 + * Tests of the graph implementation.
13 + */
14 +public class AdjacencyListsGraphTest {
15 +
16 + private static final TestVertex A = new TestVertex("A");
17 + private static final TestVertex B = new TestVertex("B");
18 + private static final TestVertex C = new TestVertex("C");
19 + private static final TestVertex D = new TestVertex("D");
20 + private static final TestVertex E = new TestVertex("E");
21 + private static final TestVertex F = new TestVertex("F");
22 + private static final TestVertex G = new TestVertex("G");
23 +
24 + private final Set<TestEdge> edges =
25 + ImmutableSet.of(new TestEdge(A, B, 1), new TestEdge(A, C, 1),
26 + new TestEdge(B, C, 1), new TestEdge(C, D, 1),
27 + new TestEdge(D, A, 1));
28 +
29 + @Test
30 + public void basics() {
31 + Set<TestVertex> vertexes = ImmutableSet.of(A, B, C, D, E, F);
32 + AdjacencyListsGraph<TestVertex, TestEdge> graph = new AdjacencyListsGraph<>(vertexes, edges);
33 + assertEquals("incorrect vertex count", 6, graph.getVertexes().size());
34 + assertEquals("incorrect edge count", 5, graph.getEdges().size());
35 +
36 + assertEquals("incorrect egress edge count", 2, graph.getEdgesFrom(A).size());
37 + assertEquals("incorrect ingress edge count", 1, graph.getEdgesTo(A).size());
38 + assertEquals("incorrect ingress edge count", 2, graph.getEdgesTo(C).size());
39 + assertEquals("incorrect egress edge count", 1, graph.getEdgesFrom(C).size());
40 + }
41 +
42 + @Test
43 + public void equality() {
44 + Set<TestVertex> vertexes = ImmutableSet.of(A, B, C, D, E, F);
45 + Set<TestVertex> vertexes2 = ImmutableSet.of(A, B, C, D, E, F, G);
46 +
47 + AdjacencyListsGraph<TestVertex, TestEdge> graph = new AdjacencyListsGraph<>(vertexes, edges);
48 + AdjacencyListsGraph<TestVertex, TestEdge> same = new AdjacencyListsGraph<>(vertexes, edges);
49 + AdjacencyListsGraph<TestVertex, TestEdge> different = new AdjacencyListsGraph<>(vertexes2, edges);
50 +
51 + new EqualsTester()
52 + .addEqualityGroup(graph, same)
53 + .addEqualityGroup(different)
54 + .testEquals();
55 + }
56 +}
1 +package org.onlab.graph;
2 +
3 +import org.junit.Test;
4 +
5 +import java.util.Set;
6 +
7 +import static org.junit.Assert.assertEquals;
8 +
9 +/**
10 + * Test of the BFS algorithm.
11 + */
12 +public abstract class BreadthFirstSearchTest extends AbstractGraphSearchTest {
13 +
14 + @Override
15 + protected GraphPathSearch<TestVertex, TestEdge> graphSearch() {
16 + return null; // new BreadthFirstSearch();
17 + }
18 +
19 + @Test
20 + public void basics() {
21 + runBasics(3, 8.0, 7);
22 + }
23 +
24 + @Test
25 + public void defaultWeight() {
26 + weight = null;
27 + runBasics(3, 3.0, 7);
28 + }
29 +
30 + protected void runBasics(int expectedLength, double expectedCost, int expectedPaths) {
31 + g = new AdjacencyListsGraph<>(vertices(), edges());
32 +
33 + GraphPathSearch<TestVertex, TestEdge> search = graphSearch();
34 + Set<Path<TestVertex, TestEdge>> paths = search.search(g, A, H, weight).paths();
35 + assertEquals("incorrect paths count", 1, paths.size());
36 +
37 + Path p = paths.iterator().next();
38 + assertEquals("incorrect src", A, p.src());
39 + assertEquals("incorrect dst", H, p.dst());
40 + assertEquals("incorrect path length", expectedLength, p.edges().size());
41 + assertEquals("incorrect path cost", expectedCost, p.cost(), 0.1);
42 +
43 + paths = search.search(g, A, null, weight).paths();
44 + printPaths(paths);
45 + assertEquals("incorrect paths count", expectedPaths, paths.size());
46 + }
47 +
48 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableSet;
4 +import org.junit.Test;
5 +
6 +import java.util.Set;
7 +
8 +import static org.junit.Assert.assertEquals;
9 +
10 +/**
11 + * Test of the Dijkstra algorithm.
12 + */
13 +public class DijkstraGraphSearchTest extends BreadthFirstSearchTest {
14 +
15 + @Override
16 + protected GraphPathSearch<TestVertex, TestEdge> graphSearch() {
17 + return new DijkstraGraphSearch<>();
18 + }
19 +
20 + @Test
21 + @Override
22 + public void basics() {
23 + runBasics(5, 5.0, 7);
24 + }
25 +
26 + @Test
27 + public void defaultWeight() {
28 + weight = null;
29 + runBasics(3, 3.0, 10);
30 + }
31 +
32 + @Test
33 + public void noPath() {
34 + g = new AdjacencyListsGraph<>(ImmutableSet.of(A, B, C, D),
35 + ImmutableSet.of(new TestEdge(A, B, 1),
36 + new TestEdge(B, A, 1),
37 + new TestEdge(C, D, 1),
38 + new TestEdge(D, C, 1)));
39 +
40 + GraphPathSearch<TestVertex, TestEdge> gs = graphSearch();
41 + Set<Path<TestVertex, TestEdge>> paths = gs.search(g, A, B, weight).paths();
42 + printPaths(paths);
43 + assertEquals("incorrect paths count", 1, paths.size());
44 + assertEquals("incorrect path cost", 1.0, paths.iterator().next().cost(), 0.1);
45 +
46 + paths = gs.search(g, A, D, weight).paths();
47 + printPaths(paths);
48 + assertEquals("incorrect paths count", 0, paths.size());
49 +
50 + paths = gs.search(g, A, null, weight).paths();
51 + printPaths(paths);
52 + assertEquals("incorrect paths count", 1, paths.size());
53 + assertEquals("incorrect path cost", 1.0, paths.iterator().next().cost(), 0.1);
54 + }
55 +
56 + @Test
57 + public void multiPath1() {
58 + g = new AdjacencyListsGraph<>(ImmutableSet.of(A, B, C, D),
59 + ImmutableSet.of(new TestEdge(A, B, 1),
60 + new TestEdge(A, C, 1),
61 + new TestEdge(B, D, 1),
62 + new TestEdge(C, D, 1)));
63 +
64 + GraphPathSearch<TestVertex, TestEdge> gs = graphSearch();
65 + Set<Path<TestVertex, TestEdge>> paths = gs.search(g, A, D, weight).paths();
66 + printPaths(paths);
67 + assertEquals("incorrect paths count", 2, paths.size());
68 + assertEquals("incorrect path cost", 2.0, paths.iterator().next().cost(), 0.1);
69 + }
70 +
71 + @Test
72 + public void multiPath2() {
73 + g = new AdjacencyListsGraph<>(ImmutableSet.of(A, B, C, D, E, F, G),
74 + ImmutableSet.of(new TestEdge(A, B, 1),
75 + new TestEdge(A, C, 1),
76 + new TestEdge(B, D, 1),
77 + new TestEdge(C, D, 1),
78 + new TestEdge(D, E, 1),
79 + new TestEdge(D, F, 1),
80 + new TestEdge(E, G, 1),
81 + new TestEdge(F, G, 1),
82 + new TestEdge(A, G, 4)));
83 +
84 + GraphPathSearch<TestVertex, TestEdge> gs = graphSearch();
85 + GraphPathSearch.Result<TestVertex, TestEdge> gsr = gs.search(g, A, G, weight);
86 + Set<Path<TestVertex, TestEdge>> paths = gsr.paths();
87 + printPaths(paths);
88 + assertEquals("incorrect paths count", 5, paths.size());
89 + assertEquals("incorrect path cost", 4.0, paths.iterator().next().cost(), 0.1);
90 + }
91 +
92 + @Test
93 + public void multiPath3() {
94 + g = new AdjacencyListsGraph<>(ImmutableSet.of(A, B, C, D, E, F, G, H),
95 + ImmutableSet.of(new TestEdge(A, B, 1), new TestEdge(A, C, 3),
96 + new TestEdge(B, D, 2), new TestEdge(B, C, 1),
97 + new TestEdge(B, E, 4), new TestEdge(C, E, 1),
98 + new TestEdge(D, H, 5), new TestEdge(D, E, 1),
99 + new TestEdge(E, F, 1), new TestEdge(F, D, 1),
100 + new TestEdge(F, G, 1), new TestEdge(F, H, 1),
101 + new TestEdge(A, E, 3), new TestEdge(B, D, 1)));
102 +
103 + GraphPathSearch<TestVertex, TestEdge> gs = graphSearch();
104 + Set<Path<TestVertex, TestEdge>> paths = gs.search(g, A, E, weight).paths();
105 + printPaths(paths);
106 + assertEquals("incorrect paths count", 3, paths.size());
107 + assertEquals("incorrect path cost", 3.0, paths.iterator().next().cost(), 0.1);
108 + }
109 +
110 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableSet;
4 +
5 +import java.util.Set;
6 +
7 +/**
8 + * Base class for various graph-related tests.
9 + */
10 +public class GraphTest {
11 +
12 + static final TestVertex A = new TestVertex("A");
13 + static final TestVertex B = new TestVertex("B");
14 + static final TestVertex C = new TestVertex("C");
15 + static final TestVertex D = new TestVertex("D");
16 + static final TestVertex E = new TestVertex("E");
17 + static final TestVertex F = new TestVertex("F");
18 + static final TestVertex G = new TestVertex("G");
19 + static final TestVertex H = new TestVertex("H");
20 +
21 + protected Graph<TestVertex, TestEdge> g;
22 +
23 + protected EdgeWeight<TestVertex, TestEdge> weight =
24 + new EdgeWeight<TestVertex, TestEdge>() {
25 + @Override
26 + public double weight(TestEdge edge) {
27 + return edge.weight();
28 + }
29 + };
30 +
31 + protected void printPaths(Set<Path<TestVertex, TestEdge>> paths) {
32 + for (Path p : paths) {
33 + System.out.println(p);
34 + }
35 + }
36 +
37 + protected Set<TestVertex> vertices() {
38 + return ImmutableSet.of(A, B, C, D, E, F, G, H);
39 + }
40 +
41 + protected Set<TestEdge> edges() {
42 + return ImmutableSet.of(new TestEdge(A, B, 1), new TestEdge(A, C, 3),
43 + new TestEdge(B, D, 2), new TestEdge(B, C, 1),
44 + new TestEdge(B, E, 4), new TestEdge(C, E, 1),
45 + new TestEdge(D, H, 5), new TestEdge(D, E, 1),
46 + new TestEdge(E, F, 1), new TestEdge(F, D, 1),
47 + new TestEdge(F, G, 1), new TestEdge(F, H, 1));
48 + }
49 +
50 +}
1 +package org.onlab.graph;
2 +
3 +import com.google.common.collect.ImmutableList;
4 +import com.google.common.collect.Ordering;
5 +import com.google.common.testing.EqualsTester;
6 +import org.junit.Test;
7 +
8 +import java.util.ArrayList;
9 +import java.util.Comparator;
10 +import java.util.Iterator;
11 +
12 +import static org.junit.Assert.*;
13 +
14 +/**
15 + * Heap data structure tests.
16 + */
17 +public class HeapTest {
18 +
19 + private ArrayList<Integer> data =
20 + new ArrayList<>(ImmutableList.of(6, 4, 5, 9, 8, 3, 2, 1, 7, 0));
21 +
22 + private static final Comparator<Integer> ASCENDING = Ordering.natural().reverse();
23 + private static final Comparator<Integer> DESCENDING = Ordering.natural();
24 +
25 + @Test
26 + public void equality() {
27 + new EqualsTester()
28 + .addEqualityGroup(new Heap<>(data, ASCENDING),
29 + new Heap<>(data, ASCENDING))
30 + .addEqualityGroup(new Heap<>(data, DESCENDING))
31 + .testEquals();
32 + }
33 +
34 + @Test
35 + public void ascending() {
36 + Heap<Integer> h = new Heap<>(data, ASCENDING);
37 + assertEquals("incorrect size", 10, h.size());
38 + assertFalse("should not be empty", h.isEmpty());
39 + assertEquals("incorrect extreme", (Integer) 0, h.extreme());
40 +
41 + for (int i = 0, n = h.size(); i < n; i++) {
42 + assertEquals("incorrect element", (Integer) i, h.extractExtreme());
43 + }
44 + assertTrue("should be empty", h.isEmpty());
45 + }
46 +
47 + @Test
48 + public void descending() {
49 + Heap<Integer> h = new Heap<>(data, DESCENDING);
50 + assertEquals("incorrect size", 10, h.size());
51 + assertFalse("should not be empty", h.isEmpty());
52 + assertEquals("incorrect extreme", (Integer) 9, h.extreme());
53 +
54 + for (int i = h.size(); i > 0; i--) {
55 + assertEquals("incorrect element", (Integer) (i - 1), h.extractExtreme());
56 + }
57 + assertTrue("should be empty", h.isEmpty());
58 + }
59 +
60 + @Test
61 + public void empty() {
62 + Heap<Integer> h = new Heap<>(new ArrayList<Integer>(), ASCENDING);
63 + assertEquals("incorrect size", 0, h.size());
64 + assertTrue("should be empty", h.isEmpty());
65 + assertNull("no item expected", h.extreme());
66 + assertNull("no item expected", h.extractExtreme());
67 + }
68 +
69 + @Test
70 + public void insert() {
71 + Heap<Integer> h = new Heap<>(data, ASCENDING);
72 + assertEquals("incorrect size", 10, h.size());
73 + h.insert(3);
74 + assertEquals("incorrect size", 11, h.size());
75 + }
76 +
77 + @Test
78 + public void iterator() {
79 + Heap<Integer> h = new Heap<>(data, ASCENDING);
80 + Iterator<Integer> it = h.iterator();
81 + while (it.hasNext()) {
82 + int item = it.next();
83 + }
84 + }
85 +
86 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.Objects;
4 +
5 +/**
6 + * Test edge.
7 + */
8 +public class TestEdge extends AbstractEdge<TestVertex> {
9 +
10 + private final double weight;
11 +
12 + /**
13 + * Creates a new edge between the specified source and destination vertexes.
14 + *
15 + * @param src source vertex
16 + * @param dst destination vertex
17 + * @param weight edge weight
18 + */
19 + public TestEdge(TestVertex src, TestVertex dst, double weight) {
20 + super(src, dst);
21 + this.weight = weight;
22 + }
23 +
24 + /**
25 + * Returns the edge weight.
26 + *
27 + * @return edge weight
28 + */
29 + public double weight() {
30 + return weight;
31 + }
32 +
33 + @Override
34 + public int hashCode() {
35 + return 31 * super.hashCode() + Objects.hash(weight);
36 + }
37 +
38 + @Override
39 + public boolean equals(Object obj) {
40 + if (obj instanceof TestEdge) {
41 + final TestEdge other = (TestEdge) obj;
42 + return super.equals(obj) && Objects.equals(this.weight, other.weight);
43 + }
44 + return false;
45 + }
46 +}
1 +package org.onlab.graph;
2 +
3 +import java.util.Objects;
4 +
5 +import static com.google.common.base.Objects.toStringHelper;
6 +
7 +/**
8 + * Test vertex.
9 + */
10 +public class TestVertex implements Vertex {
11 +
12 + private final String name;
13 +
14 + public TestVertex(String name) {
15 + this.name = name;
16 + }
17 +
18 + @Override
19 + public String toString() {
20 + return toStringHelper(this).add("name", name).toString();
21 + }
22 +
23 + @Override
24 + public int hashCode() {
25 + return Objects.hash(name);
26 + }
27 +
28 + @Override
29 + public boolean equals(Object obj) {
30 + if (obj instanceof TestVertex) {
31 + final TestVertex other = (TestVertex) obj;
32 + return Objects.equals(this.name, other.name);
33 + }
34 + return false;
35 + }
36 +
37 +}