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> network = 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 network (e.g. if you write a method than runs a read-only algorithm on
066 * the network), 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(network);
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 a live view of the nodes which have an incident edge in common with {@code node} in
165   * this graph.
166   *
167   * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
168   *
169   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
170   * {@code view} returned by this method will be invalidated, and will throw {@code
171   * IllegalStateException} if it is accessed in any way, with the following exceptions:
172   *
173   * <ul>
174   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
175   *       expression involving {@code view} will throw)
176   *   <li>{@code hashCode()} does not throw
177   *   <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
178   *       behavior is undefined
179   * </ul>
180   *
181   * @throws IllegalArgumentException if {@code node} is not an element of this network
182   */
183  Set<N> adjacentNodes(N node);
184
185  /**
186   * Returns a live view of all nodes in this network adjacent to {@code node} which can be reached
187   * by traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
188   *
189   * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
190   *
191   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
192   * returned by this method will be invalidated, and will throw {@code IllegalStateException} if it
193   * is accessed in any way.
194   *
195   * @throws IllegalArgumentException if {@code node} is not an element of this network
196   */
197  @Override
198  Set<N> predecessors(N node);
199
200  /**
201   * Returns a live view of all nodes in this network adjacent to {@code node} which can be reached
202   * by traversing {@code node}'s outgoing edges in the direction (if any) of the edge.
203   *
204   * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
205   *
206   * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
207   * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
208   *
209   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
210   * {@code view} returned by this method will be invalidated, and will throw {@code
211   * IllegalStateException} if it is accessed in any way, with the following exceptions:
212   *
213   * <ul>
214   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
215   *       expression involving {@code view} will throw)
216   *   <li>{@code hashCode()} does not throw
217   *   <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
218   *       behavior is undefined
219   * </ul>
220   *
221   * @throws IllegalArgumentException if {@code node} is not an element of this network
222   */
223  @Override
224  Set<N> successors(N node);
225
226  /**
227   * Returns a live view of the edges whose {@link #incidentNodes(Object) incident nodes} in this
228   * network include {@code node}.
229   *
230   * <p>This is equal to the union of {@link #inEdges(Object)} and {@link #outEdges(Object)}.
231   *
232   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
233   * {@code view} returned by this method will be invalidated, and will throw {@code
234   * IllegalStateException} if it is accessed in any way, with the following exceptions:
235   *
236   * <ul>
237   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
238   *       expression involving {@code view} will throw)
239   *   <li>{@code hashCode()} does not throw
240   *   <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
241   *       behavior is undefined
242   * </ul>
243   *
244   * @throws IllegalArgumentException if {@code node} is not an element of this network
245   * @since 24.0
246   */
247  Set<E> incidentEdges(N node);
248
249  /**
250   * Returns a live view of all edges in this network which can be traversed in the direction (if
251   * any) of the edge to end at {@code node}.
252   *
253   * <p>In a directed network, an incoming edge's {@link EndpointPair#target()} equals {@code node}.
254   *
255   * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
256   *
257   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
258   * {@code view} returned by this method will be invalidated, and will throw {@code
259   * IllegalStateException} if it is accessed in any way, with the following exceptions:
260   *
261   * <ul>
262   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
263   *       expression involving {@code view} will throw)
264   *   <li>{@code hashCode()} does not throw
265   *   <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
266   *       behavior is undefined
267   * </ul>
268   *
269   * @throws IllegalArgumentException if {@code node} is not an element of this network
270   */
271  Set<E> inEdges(N node);
272
273  /**
274   * Returns a live view of all edges in this network which can be traversed in the direction (if
275   * any) of the edge starting from {@code node}.
276   *
277   * <p>In a directed network, an outgoing edge's {@link EndpointPair#source()} equals {@code node}.
278   *
279   * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
280   *
281   * <p>If {@code node} is removed from the network after this method is called, the {@code Set}
282   * {@code view} returned by this method will be invalidated, and will throw {@code
283   * IllegalStateException} if it is accessed in any way, with the following exceptions:
284   *
285   * <ul>
286   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
287   *       expression involving {@code view} will throw)
288   *   <li>{@code hashCode()} does not throw
289   *   <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
290   *       behavior is undefined
291   * </ul>
292   *
293   * @throws IllegalArgumentException if {@code node} is not an element of this network
294   */
295  Set<E> outEdges(N node);
296
297  /**
298   * Returns the count of {@code node}'s {@link #incidentEdges(Object) incident edges}, counting
299   * self-loops twice (equivalently, the number of times an edge touches {@code node}).
300   *
301   * <p>For directed networks, this is equal to {@code inDegree(node) + outDegree(node)}.
302   *
303   * <p>For undirected networks, this is equal to {@code incidentEdges(node).size()} + (number of
304   * self-loops incident to {@code node}).
305   *
306   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
307   *
308   * @throws IllegalArgumentException if {@code node} is not an element of this network
309   */
310  int degree(N node);
311
312  /**
313   * Returns the count of {@code node}'s {@link #inEdges(Object) incoming edges} in a directed
314   * network. In an undirected network, returns the {@link #degree(Object)}.
315   *
316   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
317   *
318   * @throws IllegalArgumentException if {@code node} is not an element of this network
319   */
320  int inDegree(N node);
321
322  /**
323   * Returns the count of {@code node}'s {@link #outEdges(Object) outgoing edges} in a directed
324   * network. In an undirected network, returns the {@link #degree(Object)}.
325   *
326   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
327   *
328   * @throws IllegalArgumentException if {@code node} is not an element of this network
329   */
330  int outDegree(N node);
331
332  /**
333   * Returns the nodes which are the endpoints of {@code edge} in this network.
334   *
335   * @throws IllegalArgumentException if {@code edge} is not an element of this network
336   */
337  EndpointPair<N> incidentNodes(E edge);
338
339  /**
340   * Returns a live view of the edges which have an {@link #incidentNodes(Object) incident node} in
341   * common with {@code edge}. An edge is not considered adjacent to itself.
342   *
343   * <p>If {@code edge} is removed from the network after this method is called, the {@code Set}
344   * {@code view} returned by this method will be invalidated, and will throw {@code
345   * IllegalStateException} if it is accessed in any way, with the following exceptions:
346   *
347   * <ul>
348   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
349   *       expression involving {@code view} will throw)
350   *   <li>{@code hashCode()} does not throw
351   *   <li>if {@code edge} is re-added to the network after having been removed, {@code view}'s
352   *       behavior is undefined
353   * </ul>
354   *
355   * @throws IllegalArgumentException if {@code edge} is not an element of this network
356   */
357  Set<E> adjacentEdges(E edge);
358
359  /**
360   * Returns a live view of the set of edges that each directly connect {@code nodeU} to {@code
361   * nodeV}.
362   *
363   * <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}.
364   *
365   * <p>The resulting set of edges will be parallel (i.e. have equal {@link
366   * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
367   * edges}, the resulting set will contain at most one edge (equivalent to {@code
368   * edgeConnecting(nodeU, nodeV).asSet()}).
369   *
370   * <p>If either {@code nodeU} or {@code nodeV} are removed from the network after this method is
371   * called, the {@code Set} {@code view} returned by this method will be invalidated, and will
372   * throw {@code IllegalStateException} if it is accessed in any way, with the following
373   * exceptions:
374   *
375   * <ul>
376   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
377   *       expression involving {@code view} will throw)
378   *   <li>{@code hashCode()} does not throw
379   *   <li>if {@code nodeU} or {@code nodeV} are re-added to the network after having been removed,
380   *       {@code view}'s behavior is undefined
381   * </ul>
382   *
383   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
384   *     network
385   */
386  Set<E> edgesConnecting(N nodeU, N nodeV);
387
388  /**
389   * Returns a live view of the set of edges that each directly connect {@code endpoints} (in the
390   * order, if any, specified by {@code endpoints}).
391   *
392   * <p>The resulting set of edges will be parallel (i.e. have equal {@link
393   * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
394   * edges}, the resulting set will contain at most one edge (equivalent to {@code
395   * edgeConnecting(endpoints).asSet()}).
396   *
397   * <p>If this network is directed, {@code endpoints} must be ordered.
398   *
399   * <p>If either element of {@code endpoints} is removed from the network after this method is
400   * called, the {@code Set} {@code view} returned by this method will be invalidated, and will
401   * throw {@code IllegalStateException} if it is accessed in any way, with the following
402   * exceptions:
403   *
404   * <ul>
405   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
406   *       expression involving {@code view} will throw)
407   *   <li>{@code hashCode()} does not throw
408   *   <li>if either endpoint is re-added to the network after having been removed, {@code view}'s
409   *       behavior is undefined
410   * </ul>
411   *
412   * @throws IllegalArgumentException if either endpoint is not an element of this network
413   * @throws IllegalArgumentException if the endpoints are unordered and the network is directed
414   * @since 27.1
415   */
416  Set<E> edgesConnecting(EndpointPair<N> endpoints);
417
418  /**
419   * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
420   * present, or {@code Optional.empty()} if no such edge exists.
421   *
422   * <p>In an undirected network, this is equal to {@code edgeConnecting(nodeV, nodeU)}.
423   *
424   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
425   *     to {@code nodeV}
426   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
427   *     network
428   * @since 23.0
429   */
430  Optional<E> edgeConnecting(N nodeU, N nodeV);
431
432  /**
433   * Returns the single edge that directly connects {@code endpoints} (in the order, if any,
434   * specified by {@code endpoints}), if one is present, or {@code Optional.empty()} if no such edge
435   * exists.
436   *
437   * <p>If this network is directed, the endpoints must be ordered.
438   *
439   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
440   *     to {@code nodeV}
441   * @throws IllegalArgumentException if either endpoint is not an element of this network
442   * @throws IllegalArgumentException if the endpoints are unordered and the network is directed
443   * @since 27.1
444   */
445  Optional<E> edgeConnecting(EndpointPair<N> endpoints);
446
447  /**
448   * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
449   * present, or {@code null} if no such edge exists.
450   *
451   * <p>In an undirected network, this is equal to {@code edgeConnectingOrNull(nodeV, nodeU)}.
452   *
453   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
454   *     to {@code nodeV}
455   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
456   *     network
457   * @since 23.0
458   */
459  @CheckForNull
460  E edgeConnectingOrNull(N nodeU, N nodeV);
461
462  /**
463   * Returns the single edge that directly connects {@code endpoints} (in the order, if any,
464   * specified by {@code endpoints}), if one is present, or {@code null} if no such edge exists.
465   *
466   * <p>If this network is directed, the endpoints must be ordered.
467   *
468   * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
469   *     to {@code nodeV}
470   * @throws IllegalArgumentException if either endpoint is not an element of this network
471   * @throws IllegalArgumentException if the endpoints are unordered and the network is directed
472   * @since 27.1
473   */
474  @CheckForNull
475  E edgeConnectingOrNull(EndpointPair<N> endpoints);
476
477  /**
478   * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
479   * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}, and to
480   * {@code edgeConnectingOrNull(nodeU, nodeV) != null}.
481   *
482   * <p>In an undirected network, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
483   *
484   * @since 23.0
485   */
486  boolean hasEdgeConnecting(N nodeU, N nodeV);
487
488  /**
489   * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
490   * any, specified by {@code endpoints}).
491   *
492   * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
493   * endpoints are unordered and the network is directed; it simply returns {@code false}. This is
494   * for consistency with {@link Graph#hasEdgeConnecting(EndpointPair)} and {@link
495   * ValueGraph#hasEdgeConnecting(EndpointPair)}.
496   *
497   * @since 27.1
498   */
499  boolean hasEdgeConnecting(EndpointPair<N> endpoints);
500
501  //
502  // Network identity
503  //
504
505  /**
506   * Returns {@code true} iff {@code object} is a {@link Network} that has the same elements and the
507   * same structural relationships as those in this network.
508   *
509   * <p>Thus, two networks A and B are equal if <b>all</b> of the following are true:
510   *
511   * <ul>
512   *   <li>A and B have equal {@link #isDirected() directedness}.
513   *   <li>A and B have equal {@link #nodes() node sets}.
514   *   <li>A and B have equal {@link #edges() edge sets}.
515   *   <li>Every edge in A and B connects the same nodes in the same direction (if any).
516   * </ul>
517   *
518   * <p>Network properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
519   * For example, two networks may be considered equal even if one allows parallel edges and the
520   * other doesn't. Additionally, the order in which nodes or edges are added to the network, and
521   * the order in which they are iterated over, are irrelevant.
522   *
523   * <p>A reference implementation of this is provided by {@link AbstractNetwork#equals(Object)}.
524   */
525  @Override
526  boolean equals(@CheckForNull Object object);
527
528  /**
529   * Returns the hash code for this network. The hash code of a network is defined as the hash code
530   * of a map from each of its {@link #edges() edges} to their {@link #incidentNodes(Object)
531   * incident nodes}.
532   *
533   * <p>A reference implementation of this is provided by {@link AbstractNetwork#hashCode()}.
534   */
535  @Override
536  int hashCode();
537}