001/*
002 * Copyright (C) 2016 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.Collection;
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 have associated non-unique values.
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 ValueGraph} 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 self-loops
047 *   <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered
048 *   <li>graphs whose edges have associated values
049 * </ul>
050 *
051 * <p>{@code ValueGraph}, as a subtype of {@code Graph}, explicitly does not support parallel edges,
052 * and forbids implementations or extensions with parallel edges. If you need parallel edges, use
053 * {@link Network}. (You can use a positive {@code Integer} edge value as a loose representation of
054 * edge multiplicity, but the {@code *degree()} and mutation methods will not reflect your
055 * interpretation of the edge value as its multiplicity.)
056 *
057 * <h3>Building a {@code ValueGraph}</h3>
058 *
059 * <p>The implementation classes that {@code common.graph} provides are not public, by design. To
060 * create an instance of one of the built-in implementations of {@code ValueGraph}, use the {@link
061 * ValueGraphBuilder} class:
062 *
063 * <pre>{@code
064 * MutableValueGraph<Integer, Double> graph = ValueGraphBuilder.directed().build();
065 * }</pre>
066 *
067 * <p>{@link ValueGraphBuilder#build()} returns an instance of {@link MutableValueGraph}, which is a
068 * subtype of {@code ValueGraph} that provides methods for adding and removing nodes and edges. If
069 * you do not need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on
070 * the graph), you should use the non-mutating {@link ValueGraph} interface, or an {@link
071 * ImmutableValueGraph}.
072 *
073 * <p>You can create an immutable copy of an existing {@code ValueGraph} using {@link
074 * ImmutableValueGraph#copyOf(ValueGraph)}:
075 *
076 * <pre>{@code
077 * ImmutableValueGraph<Integer, Double> immutableGraph = ImmutableValueGraph.copyOf(graph);
078 * }</pre>
079 *
080 * <p>Instances of {@link ImmutableValueGraph} do not implement {@link MutableValueGraph}
081 * (obviously!) and are contractually guaranteed to be unmodifiable and thread-safe.
082 *
083 * <p>The Guava User Guide has <a
084 * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more
085 * information on (and examples of) building graphs</a>.
086 *
087 * <h3>Additional documentation</h3>
088 *
089 * <p>See the Guava User Guide for the {@code common.graph} package (<a
090 * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for
091 * additional documentation, including:
092 *
093 * <ul>
094 *   <li><a
095 *       href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence">
096 *       {@code equals()}, {@code hashCode()}, and graph equivalence</a>
097 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization">
098 *       Synchronization policy</a>
099 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes
100 *       for implementors</a>
101 * </ul>
102 *
103 * @author James Sexton
104 * @author Joshua O'Madadhain
105 * @param <N> Node parameter type
106 * @param <V> Value parameter type
107 * @since 20.0
108 */
109@Beta
110public interface ValueGraph<N, V> extends BaseGraph<N> {
111  //
112  // ValueGraph-level accessors
113  //
114
115  /** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */
116  @Override
117  Set<N> nodes();
118
119  /** Returns all edges in this graph. */
120  @Override
121  Set<EndpointPair<N>> edges();
122
123  /**
124   * Returns a live view of this graph as a {@link Graph}. The resulting {@link Graph} will have an
125   * edge connecting node A to node B if this {@link ValueGraph} has an edge connecting A to B.
126   */
127  Graph<N> asGraph();
128
129  //
130  // ValueGraph properties
131  //
132
133  /**
134   * Returns true if the edges in this graph 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  @Override
139  boolean isDirected();
140
141  /**
142   * Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting
143   * to add a self-loop to a graph that does not allow them will throw an {@link
144   * IllegalArgumentException}.
145   */
146  @Override
147  boolean allowsSelfLoops();
148
149  /** Returns the order of iteration for the elements of {@link #nodes()}. */
150  @Override
151  ElementOrder<N> nodeOrder();
152
153  /**
154   * Returns an {@link ElementOrder} that specifies the order of iteration for the elements of
155   * {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link
156   * #successors(Object)} and {@link #incidentEdges(Object)}.
157   *
158   * @since 29.0
159   */
160  @Override
161  ElementOrder<N> incidentEdgeOrder();
162
163  //
164  // Element-level accessors
165  //
166
167  /**
168   * Returns a live view of the nodes which have an incident edge in common with {@code node} in
169   * this graph.
170   *
171   * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
172   *
173   * <p>If {@code node} is removed from the graph 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 graph 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 graph
186   */
187  @Override
188  Set<N> adjacentNodes(N node);
189
190  /**
191   * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
192   * traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
193   *
194   * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
195   *
196   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
197   * returned by this method will be invalidated, and will throw {@code IllegalStateException} if it
198   * is accessed in any way.
199   *
200   * @throws IllegalArgumentException if {@code node} is not an element of this graph
201   */
202  @Override
203  Set<N> predecessors(N node);
204
205  /**
206   * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
207   * traversing {@code node}'s outgoing edges in the direction (if any) of the edge.
208   *
209   * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
210   *
211   * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
212   * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
213   *
214   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
215   * {@code view} returned by this method will be invalidated, and will throw {@code
216   * IllegalStateException} if it is accessed in any way, with the following exceptions:
217   *
218   * <ul>
219   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
220   *       expression involving {@code view} will throw)
221   *   <li>{@code hashCode()} does not throw
222   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
223   *       behavior is undefined
224   * </ul>
225   *
226   * @throws IllegalArgumentException if {@code node} is not an element of this graph
227   */
228  @Override
229  Set<N> successors(N node);
230
231  /**
232   * Returns a live view of the edges in this graph whose endpoints include {@code node}.
233   *
234   * <p>This is equal to the union of incoming and outgoing edges.
235   *
236   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
237   * {@code view} returned by this method will be invalidated, and will throw {@code
238   * IllegalStateException} if it is accessed in any way, with the following exceptions:
239   *
240   * <ul>
241   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
242   *       expression involving {@code view} will throw)
243   *   <li>{@code hashCode()} does not throw
244   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
245   *       behavior is undefined
246   * </ul>
247   *
248   * @throws IllegalArgumentException if {@code node} is not an element of this graph
249   * @since 24.0
250   */
251  @Override
252  Set<EndpointPair<N>> incidentEdges(N node);
253
254  /**
255   * Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently,
256   * the number of times an edge touches {@code node}).
257   *
258   * <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}.
259   *
260   * <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of
261   * self-loops incident to {@code node}).
262   *
263   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
264   *
265   * @throws IllegalArgumentException if {@code node} is not an element of this graph
266   */
267  @Override
268  int degree(N node);
269
270  /**
271   * Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()})
272   * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
273   *
274   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
275   *
276   * @throws IllegalArgumentException if {@code node} is not an element of this graph
277   */
278  @Override
279  int inDegree(N node);
280
281  /**
282   * Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()})
283   * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
284   *
285   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
286   *
287   * @throws IllegalArgumentException if {@code node} is not an element of this graph
288   */
289  @Override
290  int outDegree(N node);
291
292  /**
293   * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
294   * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}.
295   *
296   * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
297   *
298   * @since 23.0
299   */
300  @Override
301  boolean hasEdgeConnecting(N nodeU, N nodeV);
302
303  /**
304   * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
305   * any, specified by {@code endpoints}). This is equivalent to {@code
306   * edges().contains(endpoints)}.
307   *
308   * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
309   * endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for
310   * consistency with the behavior of {@link Collection#contains(Object)} (which does not generally
311   * throw if the object cannot be present in the collection), and the desire to have this method's
312   * behavior be compatible with {@code edges().contains(endpoints)}.
313   *
314   * @since 27.1
315   */
316  @Override
317  boolean hasEdgeConnecting(EndpointPair<N> endpoints);
318
319  /**
320   * Returns the value of the edge that connects {@code nodeU} to {@code nodeV}, if one is present;
321   * otherwise, returns {@code defaultValue}.
322   *
323   * <p>In an undirected graph, this is equal to {@code edgeValueOrDefault(nodeV, nodeU,
324   * defaultValue)}.
325   *
326   * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
327   *     graph
328   */
329  @Nullable V edgeValueOrDefault(N nodeU, N nodeV, @Nullable V defaultValue);
330
331  /**
332   * Returns the value of the edge that connects {@code endpoints} (in the order, if any, specified
333   * by {@code endpoints}), if one is present; otherwise, returns {@code defaultValue}.
334   *
335   * <p>If this graph is directed, the endpoints must be ordered.
336   *
337   * @throws IllegalArgumentException if either endpoint is not an element of this graph
338   * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
339   * @since 27.1
340   */
341  @Nullable V edgeValueOrDefault(EndpointPair<N> endpoints, @Nullable V defaultValue);
342
343  //
344  // ValueGraph identity
345  //
346
347  /**
348   * Returns {@code true} iff {@code object} is a {@link ValueGraph} that has the same elements and
349   * the same structural relationships as those in this graph.
350   *
351   * <p>Thus, two value graphs A and B are equal if <b>all</b> of the following are true:
352   *
353   * <ul>
354   *   <li>A and B have equal {@link #isDirected() directedness}.
355   *   <li>A and B have equal {@link #nodes() node sets}.
356   *   <li>A and B have equal {@link #edges() edge sets}.
357   *   <li>The {@link #edgeValueOrDefault(N, N, V) value} of a given edge is the same in both A and
358   *       B.
359   * </ul>
360   *
361   * <p>Graph properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
362   * For example, two graphs may be considered equal even if one allows self-loops and the other
363   * doesn't. Additionally, the order in which nodes or edges are added to the graph, and the order
364   * in which they are iterated over, are irrelevant.
365   *
366   * <p>A reference implementation of this is provided by {@link AbstractValueGraph#equals(Object)}.
367   */
368  @Override
369  boolean equals(@Nullable Object object);
370
371  /**
372   * Returns the hash code for this graph. The hash code of a graph is defined as the hash code of a
373   * map from each of its {@link #edges() edges} to the associated {@link #edgeValueOrDefault(N, N,
374   * V) edge value}.
375   *
376   * <p>A reference implementation of this is provided by {@link AbstractValueGraph#hashCode()}.
377   */
378  @Override
379  int hashCode();
380}