001/*
002 * Copyright (C) 2014 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.graph;
018
019import com.google.common.annotations.Beta;
020import com.google.errorprone.annotations.DoNotMock;
021import java.util.Optional;
022import java.util.Set;
023import javax.annotation.CheckForNull;
024
025/**
026 * An interface for <a
027 * href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data,
028 * whose edges are unique objects.
029 *
030 * <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes.
031 *
032 * <p>There are three primary interfaces provided to represent graphs. In order of increasing
033 * complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally
034 * prefer the simplest interface that satisfies your use case. See the <a
035 * href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type">
036 * "Choosing the right graph type"</a> section of the Guava User Guide for more details.
037 *
038 * <h3>Capabilities</h3>
039 *
040 * <p>{@code Network} supports the following use cases (<a
041 * href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of
042 * terms</a>):
043 *
044 * <ul>
045 *   <li>directed graphs
046 *   <li>undirected graphs
047 *   <li>graphs that do/don't allow parallel edges
048 *   <li>graphs that do/don't allow self-loops
049 *   <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered
050 *   <li>graphs whose edges are unique objects
051 * </ul>
052 *
053 * <h3>Building a {@code Network}</h3>
054 *
055 * <p>The implementation classes that {@code common.graph} provides are not public, by design. To
056 * create an instance of one of the built-in implementations of {@code Network}, use the {@link
057 * NetworkBuilder} class:
058 *
059 * <pre>{@code
060 * MutableNetwork<Integer, MyEdge> graph = NetworkBuilder.directed().build();
061 * }</pre>
062 *
063 * <p>{@link NetworkBuilder#build()} returns an instance of {@link MutableNetwork}, which is a
064 * subtype of {@code Network} that provides methods for adding and removing nodes and edges. If you
065 * do not need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on the
066 * graph), you should use the non-mutating {@link Network} interface, or an {@link
067 * ImmutableNetwork}.
068 *
069 * <p>You can create an immutable copy of an existing {@code Network} using {@link
070 * ImmutableNetwork#copyOf(Network)}:
071 *
072 * <pre>{@code
073 * ImmutableNetwork<Integer, MyEdge> immutableGraph = ImmutableNetwork.copyOf(graph);
074 * }</pre>
075 *
076 * <p>Instances of {@link ImmutableNetwork} do not implement {@link MutableNetwork} (obviously!) and
077 * are contractually guaranteed to be unmodifiable and thread-safe.
078 *
079 * <p>The Guava User Guide has <a
080 * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more
081 * information on (and examples of) building graphs</a>.
082 *
083 * <h3>Additional documentation</h3>
084 *
085 * <p>See the Guava User Guide for the {@code common.graph} package (<a
086 * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for
087 * additional documentation, including:
088 *
089 * <ul>
090 *   <li><a
091 *       href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence">
092 *       {@code equals()}, {@code hashCode()}, and graph equivalence</a>
093 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization">
094 *       Synchronization policy</a>
095 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes
096 *       for implementors</a>
097 * </ul>
098 *
099 * @author James Sexton
100 * @author Joshua O'Madadhain
101 * @param <N> Node parameter type
102 * @param <E> Edge parameter type
103 * @since 20.0
104 */
105@Beta
106@DoNotMock("Use NetworkBuilder to create a real instance")
107@ElementTypesAreNonnullByDefault
108public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFunction<N> {
109  //
110  // Network-level accessors
111  //
112
113  /** Returns all nodes in this network, in the order specified by {@link #nodeOrder()}. */
114  Set<N> nodes();
115
116  /** Returns all edges in this network, in the order specified by {@link #edgeOrder()}. */
117  Set<E> edges();
118
119  /**
120   * Returns a live view of this network as a {@link Graph}. The resulting {@link Graph} will have
121   * an edge connecting node A to node B if this {@link Network} has an edge connecting A to B.
122   *
123   * <p>If this network {@link #allowsParallelEdges() allows parallel edges}, parallel edges will be
124   * treated as if collapsed into a single edge. For example, the {@link #degree(Object)} of a node
125   * in the {@link Graph} view may be less than the degree of the same node in this {@link Network}.
126   */
127  Graph<N> asGraph();
128
129  //
130  // Network properties
131  //
132
133  /**
134   * Returns true if the edges in this network are directed. Directed edges connect a {@link
135   * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while
136   * undirected edges connect a pair of nodes to each other.
137   */
138  boolean isDirected();
139
140  /**
141   * Returns true if this network allows parallel edges. Attempting to add a parallel edge to a
142   * network that does not allow them will throw an {@link IllegalArgumentException}.
143   */
144  boolean allowsParallelEdges();
145
146  /**
147   * Returns true if this network allows self-loops (edges that connect a node to itself).
148   * Attempting to add a self-loop to a network that does not allow them will throw an {@link
149   * IllegalArgumentException}.
150   */
151  boolean allowsSelfLoops();
152
153  /** Returns the order of iteration for the elements of {@link #nodes()}. */
154  ElementOrder<N> nodeOrder();
155
156  /** Returns the order of iteration for the elements of {@link #edges()}. */
157  ElementOrder<E> edgeOrder();
158
159  //
160  // Element-level accessors
161  //
162
163  /**
164   * Returns the nodes which have an incident edge in common with {@code node} in this network.
165   *
166   * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
167   *
168   * @throws IllegalArgumentException if {@code node} is not an element of this network
169   */
170  Set<N> adjacentNodes(N node);
171
172  /**
173   * Returns all nodes in this network adjacent to {@code node} which can be reached by traversing
174   * {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
175   *
176   * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
177   *
178   * @throws IllegalArgumentException if {@code node} is not an element of this network
179   */
180  @Override
181  Set<N> predecessors(N node);
182
183  /**
184   * Returns all nodes in this network adjacent to {@code node} which can be reached by traversing
185   * {@code node}'s outgoing edges in the direction (if any) of the edge.
186   *
187   * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
188   *
189   * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
190   * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
191   *
192   * @throws IllegalArgumentException if {@code node} is not an element of this network
193   */
194  @Override
195  Set<N> successors(N node);
196
197  /**
198   * Returns the edges whose {@link #incidentNodes(Object) incident nodes} in this network include
199   * {@code node}.
200   *
201   * <p>This is equal to the union of {@link #inEdges(Object)} and {@link #outEdges(Object)}.
202   *
203   * @throws IllegalArgumentException if {@code node} is not an element of this network
204   */
205  Set<E> incidentEdges(N node);
206
207  /**
208   * Returns all edges in this network which can be traversed in the direction (if any) of the edge
209   * to end at {@code node}.
210   *
211   * <p>In a directed network, an incoming edge's {@link EndpointPair#target()} equals {@code node}.
212   *
213   * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
214   *
215   * @throws IllegalArgumentException if {@code node} is not an element of this network
216   */
217  Set<E> inEdges(N node);
218
219  /**
220   * Returns all edges in this network which can be traversed in the direction (if any) of the edge
221   * starting from {@code node}.
222   *
223   * <p>In a directed network, an outgoing edge's {@link EndpointPair#source()} equals {@code node}.
224   *
225   * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
226   *
227   * @throws IllegalArgumentException if {@code node} is not an element of this network
228   */
229  Set<E> outEdges(N node);
230
231  /**
232   * Returns the count of {@code node}'s {@link #incidentEdges(Object) incident edges}, counting
233   * self-loops twice (equivalently, the number of times an edge touches {@code node}).
234   *
235   * <p>For directed networks, this is equal to {@code inDegree(node) + outDegree(node)}.
236   *
237   * <p>For undirected networks, this is equal to {@code incidentEdges(node).size()} + (number of
238   * self-loops incident to {@code node}).
239   *
240   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
241   *
242   * @throws IllegalArgumentException if {@code node} is not an element of this network
243   */
244  int degree(N node);
245
246  /**
247   * Returns the count of {@code node}'s {@link #inEdges(Object) incoming edges} in a directed
248   * network. In an undirected network, returns the {@link #degree(Object)}.
249   *
250   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
251   *
252   * @throws IllegalArgumentException if {@code node} is not an element of this network
253   */
254  int inDegree(N node);
255
256  /**
257   * Returns the count of {@code node}'s {@link #outEdges(Object) outgoing edges} in a directed
258   * network. In an undirected network, returns the {@link #degree(Object)}.
259   *
260   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
261   *
262   * @throws IllegalArgumentException if {@code node} is not an element of this network
263   */
264  int outDegree(N node);
265
266  /**
267   * Returns the nodes which are the endpoints of {@code edge} in this network.
268   *
269   * @throws IllegalArgumentException if {@code edge} is not an element of this network
270   */
271  EndpointPair<N> incidentNodes(E edge);
272
273  /**
274   * Returns the edges which have an {@link #incidentNodes(Object) incident node} in common with
275   * {@code edge}. An edge is not considered adjacent to itself.
276   *
277   * @throws IllegalArgumentException if {@code edge} is not an element of this network
278   */
279  Set<E> adjacentEdges(E edge);
280
281  /**
282   * Returns the set of edges that each directly connect {@code nodeU} to {@code nodeV}.
283   *
284   * <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}.
285   *
286   * <p>The resulting set of edges will be parallel (i.e. have equal {@link
287   * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
288   * edges}, the resulting set will contain at most one edge (equivalent to {@code
289   * edgeConnecting(nodeU, nodeV).asSet()}).
290   *
291   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
292   *     network
293   */
294  Set<E> edgesConnecting(N nodeU, N nodeV);
295
296  /**
297   * Returns the set of edges that each directly connect {@code endpoints} (in the order, if any,
298   * specified by {@code endpoints}).
299   *
300   * <p>The resulting set of edges will be parallel (i.e. have equal {@link
301   * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
302   * edges}, the resulting set will contain at most one edge (equivalent to {@code
303   * edgeConnecting(endpoints).asSet()}).
304   *
305   * <p>If this network is directed, {@code endpoints} must be ordered.
306   *
307   * @throws IllegalArgumentException if either endpoint is not an element of this network
308   * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
309   * @since 27.1
310   */
311  Set<E> edgesConnecting(EndpointPair<N> endpoints);
312
313  /**
314   * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
315   * present, or {@code Optional.empty()} if no such edge exists.
316   *
317   * <p>In an undirected network, this is equal to {@code edgeConnecting(nodeV, nodeU)}.
318   *
319   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
320   *     to {@code nodeV}
321   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
322   *     network
323   * @since 23.0
324   */
325  Optional<E> edgeConnecting(N nodeU, N nodeV);
326
327  /**
328   * Returns the single edge that directly connects {@code endpoints} (in the order, if any,
329   * specified by {@code endpoints}), if one is present, or {@code Optional.empty()} if no such edge
330   * exists.
331   *
332   * <p>If this graph is directed, the endpoints must be ordered.
333   *
334   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
335   *     to {@code nodeV}
336   * @throws IllegalArgumentException if either endpoint is not an element of this network
337   * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
338   * @since 27.1
339   */
340  Optional<E> edgeConnecting(EndpointPair<N> endpoints);
341
342  /**
343   * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
344   * present, or {@code null} if no such edge exists.
345   *
346   * <p>In an undirected network, this is equal to {@code edgeConnectingOrNull(nodeV, nodeU)}.
347   *
348   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
349   *     to {@code nodeV}
350   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
351   *     network
352   * @since 23.0
353   */
354  @CheckForNull
355  E edgeConnectingOrNull(N nodeU, N nodeV);
356
357  /**
358   * Returns the single edge that directly connects {@code endpoints} (in the order, if any,
359   * specified by {@code endpoints}), if one is present, or {@code null} if no such edge exists.
360   *
361   * <p>If this graph is directed, the endpoints must be ordered.
362   *
363   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
364   *     to {@code nodeV}
365   * @throws IllegalArgumentException if either endpoint is not an element of this network
366   * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
367   * @since 27.1
368   */
369  @CheckForNull
370  E edgeConnectingOrNull(EndpointPair<N> endpoints);
371
372  /**
373   * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
374   * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}, and to
375   * {@code edgeConnectingOrNull(nodeU, nodeV) != null}.
376   *
377   * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
378   *
379   * @since 23.0
380   */
381  boolean hasEdgeConnecting(N nodeU, N nodeV);
382
383  /**
384   * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
385   * any, specified by {@code endpoints}).
386   *
387   * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
388   * endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for
389   * consistency with {@link Graph#hasEdgeConnecting(EndpointPair)} and {@link
390   * ValueGraph#hasEdgeConnecting(EndpointPair)}.
391   *
392   * @since 27.1
393   */
394  boolean hasEdgeConnecting(EndpointPair<N> endpoints);
395
396  //
397  // Network identity
398  //
399
400  /**
401   * Returns {@code true} iff {@code object} is a {@link Network} that has the same elements and the
402   * same structural relationships as those in this network.
403   *
404   * <p>Thus, two networks A and B are equal if <b>all</b> of the following are true:
405   *
406   * <ul>
407   *   <li>A and B have equal {@link #isDirected() directedness}.
408   *   <li>A and B have equal {@link #nodes() node sets}.
409   *   <li>A and B have equal {@link #edges() edge sets}.
410   *   <li>Every edge in A and B connects the same nodes in the same direction (if any).
411   * </ul>
412   *
413   * <p>Network properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
414   * For example, two networks may be considered equal even if one allows parallel edges and the
415   * other doesn't. Additionally, the order in which nodes or edges are added to the network, and
416   * the order in which they are iterated over, are irrelevant.
417   *
418   * <p>A reference implementation of this is provided by {@link AbstractNetwork#equals(Object)}.
419   */
420  @Override
421  boolean equals(@CheckForNull Object object);
422
423  /**
424   * Returns the hash code for this network. The hash code of a network is defined as the hash code
425   * of a map from each of its {@link #edges() edges} to their {@link #incidentNodes(Object)
426   * incident nodes}.
427   *
428   * <p>A reference implementation of this is provided by {@link AbstractNetwork#hashCode()}.
429   */
430  @Override
431  int hashCode();
432}