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