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