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