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