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 static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.Objects;
024import com.google.common.collect.Iterables;
025import com.google.common.collect.Maps;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import java.util.ArrayDeque;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.HashSet;
031import java.util.LinkedHashSet;
032import java.util.Map;
033import java.util.Queue;
034import java.util.Set;
035import org.checkerframework.checker.nullness.compatqual.NullableDecl;
036
037/**
038 * Static utility methods for {@link Graph}, {@link ValueGraph}, and {@link Network} instances.
039 *
040 * @author James Sexton
041 * @author Joshua O'Madadhain
042 * @since 20.0
043 */
044@Beta
045public final class Graphs {
046
047  private Graphs() {}
048
049  // Graph query methods
050
051  /**
052   * Returns true if {@code graph} has at least one cycle. A cycle is defined as a non-empty subset
053   * of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) starting
054   * and ending with the same node.
055   *
056   * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
057   */
058  public static <N> boolean hasCycle(Graph<N> graph) {
059    int numEdges = graph.edges().size();
060    if (numEdges == 0) {
061      return false; // An edge-free graph is acyclic by definition.
062    }
063    if (!graph.isDirected() && numEdges >= graph.nodes().size()) {
064      return true; // Optimization for the undirected case: at least one cycle must exist.
065    }
066
067    Map<Object, NodeVisitState> visitedNodes =
068        Maps.newHashMapWithExpectedSize(graph.nodes().size());
069    for (N node : graph.nodes()) {
070      if (subgraphHasCycle(graph, visitedNodes, node, null)) {
071        return true;
072      }
073    }
074    return false;
075  }
076
077  /**
078   * Returns true if {@code network} has at least one cycle. A cycle is defined as a non-empty
079   * subset of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges)
080   * starting and ending with the same node.
081   *
082   * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
083   */
084  public static boolean hasCycle(Network<?, ?> network) {
085    // In a directed graph, parallel edges cannot introduce a cycle in an acyclic graph.
086    // However, in an undirected graph, any parallel edge induces a cycle in the graph.
087    if (!network.isDirected()
088        && network.allowsParallelEdges()
089        && network.edges().size() > network.asGraph().edges().size()) {
090      return true;
091    }
092    return hasCycle(network.asGraph());
093  }
094
095  /**
096   * Performs a traversal of the nodes reachable from {@code node}. If we ever reach a node we've
097   * already visited (following only outgoing edges and without reusing edges), we know there's a
098   * cycle in the graph.
099   */
100  private static <N> boolean subgraphHasCycle(
101      Graph<N> graph,
102      Map<Object, NodeVisitState> visitedNodes,
103      N node,
104      @NullableDecl N previousNode) {
105    NodeVisitState state = visitedNodes.get(node);
106    if (state == NodeVisitState.COMPLETE) {
107      return false;
108    }
109    if (state == NodeVisitState.PENDING) {
110      return true;
111    }
112
113    visitedNodes.put(node, NodeVisitState.PENDING);
114    for (N nextNode : graph.successors(node)) {
115      if (canTraverseWithoutReusingEdge(graph, nextNode, previousNode)
116          && subgraphHasCycle(graph, visitedNodes, nextNode, node)) {
117        return true;
118      }
119    }
120    visitedNodes.put(node, NodeVisitState.COMPLETE);
121    return false;
122  }
123
124  /**
125   * Determines whether an edge has already been used during traversal. In the directed case a cycle
126   * is always detected before reusing an edge, so no special logic is required. In the undirected
127   * case, we must take care not to "backtrack" over an edge (i.e. going from A to B and then going
128   * from B to A).
129   */
130  private static boolean canTraverseWithoutReusingEdge(
131      Graph<?> graph, Object nextNode, @NullableDecl Object previousNode) {
132    if (graph.isDirected() || !Objects.equal(previousNode, nextNode)) {
133      return true;
134    }
135    // This falls into the undirected A->B->A case. The Graph interface does not support parallel
136    // edges, so this traversal would require reusing the undirected AB edge.
137    return false;
138  }
139
140  /**
141   * Returns the transitive closure of {@code graph}. The transitive closure of a graph is another
142   * graph with an edge connecting node A to node B if node B is {@link #reachableNodes(Graph,
143   * Object) reachable} from node A.
144   *
145   * <p>This is a "snapshot" based on the current topology of {@code graph}, rather than a live view
146   * of the transitive closure of {@code graph}. In other words, the returned {@link Graph} will not
147   * be updated after modifications to {@code graph}.
148   */
149  // TODO(b/31438252): Consider potential optimizations for this algorithm.
150  public static <N> Graph<N> transitiveClosure(Graph<N> graph) {
151    MutableGraph<N> transitiveClosure = GraphBuilder.from(graph).allowsSelfLoops(true).build();
152    // Every node is, at a minimum, reachable from itself. Since the resulting transitive closure
153    // will have no isolated nodes, we can skip adding nodes explicitly and let putEdge() do it.
154
155    if (graph.isDirected()) {
156      // Note: works for both directed and undirected graphs, but we only use in the directed case.
157      for (N node : graph.nodes()) {
158        for (N reachableNode : reachableNodes(graph, node)) {
159          transitiveClosure.putEdge(node, reachableNode);
160        }
161      }
162    } else {
163      // An optimization for the undirected case: for every node B reachable from node A,
164      // node A and node B have the same reachability set.
165      Set<N> visitedNodes = new HashSet<N>();
166      for (N node : graph.nodes()) {
167        if (!visitedNodes.contains(node)) {
168          Set<N> reachableNodes = reachableNodes(graph, node);
169          visitedNodes.addAll(reachableNodes);
170          int pairwiseMatch = 1; // start at 1 to include self-loops
171          for (N nodeU : reachableNodes) {
172            for (N nodeV : Iterables.limit(reachableNodes, pairwiseMatch++)) {
173              transitiveClosure.putEdge(nodeU, nodeV);
174            }
175          }
176        }
177      }
178    }
179
180    return transitiveClosure;
181  }
182
183  /**
184   * Returns the set of nodes that are reachable from {@code node}. Node B is defined as reachable
185   * from node A if there exists a path (a sequence of adjacent outgoing edges) starting at node A
186   * and ending at node B. Note that a node is always reachable from itself via a zero-length path.
187   *
188   * <p>This is a "snapshot" based on the current topology of {@code graph}, rather than a live view
189   * of the set of nodes reachable from {@code node}. In other words, the returned {@link Set} will
190   * not be updated after modifications to {@code graph}.
191   *
192   * @throws IllegalArgumentException if {@code node} is not present in {@code graph}
193   */
194  public static <N> Set<N> reachableNodes(Graph<N> graph, N node) {
195    checkArgument(graph.nodes().contains(node), NODE_NOT_IN_GRAPH, node);
196    Set<N> visitedNodes = new LinkedHashSet<N>();
197    Queue<N> queuedNodes = new ArrayDeque<N>();
198    visitedNodes.add(node);
199    queuedNodes.add(node);
200    // Perform a breadth-first traversal rooted at the input node.
201    while (!queuedNodes.isEmpty()) {
202      N currentNode = queuedNodes.remove();
203      for (N successor : graph.successors(currentNode)) {
204        if (visitedNodes.add(successor)) {
205          queuedNodes.add(successor);
206        }
207      }
208    }
209    return Collections.unmodifiableSet(visitedNodes);
210  }
211
212  /**
213   * @deprecated Use {@link Graph#equals(Object)} instead. This method will be removed in January
214   *     2018.
215   */
216  // TODO(user): Delete this method.
217  @Deprecated
218  public static boolean equivalent(@NullableDecl Graph<?> graphA, @NullableDecl Graph<?> graphB) {
219    return Objects.equal(graphA, graphB);
220  }
221
222  /**
223   * @deprecated Use {@link ValueGraph#equals(Object)} instead. This method will be removed in
224   *     January 2018.
225   */
226  // TODO(user): Delete this method.
227  @Deprecated
228  public static boolean equivalent(
229      @NullableDecl ValueGraph<?, ?> graphA, @NullableDecl ValueGraph<?, ?> graphB) {
230    return Objects.equal(graphA, graphB);
231  }
232
233  /**
234   * @deprecated Use {@link Network#equals(Object)} instead. This method will be removed in January
235   *     2018.
236   */
237  // TODO(user): Delete this method.
238  @Deprecated
239  public static boolean equivalent(
240      @NullableDecl Network<?, ?> networkA, @NullableDecl Network<?, ?> networkB) {
241    return Objects.equal(networkA, networkB);
242  }
243
244  // Graph mutation methods
245
246  // Graph view methods
247
248  /**
249   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
250   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
251   */
252  public static <N> Graph<N> transpose(Graph<N> graph) {
253    if (!graph.isDirected()) {
254      return graph; // the transpose of an undirected graph is an identical graph
255    }
256
257    if (graph instanceof TransposedGraph) {
258      return ((TransposedGraph<N>) graph).graph;
259    }
260
261    return new TransposedGraph<N>(graph);
262  }
263
264  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
265  // AbstractGraph) derives its behavior from calling successors().
266  private static class TransposedGraph<N> extends ForwardingGraph<N> {
267    private final Graph<N> graph;
268
269    TransposedGraph(Graph<N> graph) {
270      this.graph = graph;
271    }
272
273    @Override
274    protected Graph<N> delegate() {
275      return graph;
276    }
277
278    @Override
279    public Set<N> predecessors(N node) {
280      return delegate().successors(node); // transpose
281    }
282
283    @Override
284    public Set<N> successors(N node) {
285      return delegate().predecessors(node); // transpose
286    }
287
288    @Override
289    public int inDegree(N node) {
290      return delegate().outDegree(node); // transpose
291    }
292
293    @Override
294    public int outDegree(N node) {
295      return delegate().inDegree(node); // transpose
296    }
297
298    @Override
299    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
300      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
301    }
302  }
303
304  /**
305   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
306   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
307   */
308  public static <N, V> ValueGraph<N, V> transpose(ValueGraph<N, V> graph) {
309    if (!graph.isDirected()) {
310      return graph; // the transpose of an undirected graph is an identical graph
311    }
312
313    if (graph instanceof TransposedValueGraph) {
314      return ((TransposedValueGraph<N, V>) graph).graph;
315    }
316
317    return new TransposedValueGraph<>(graph);
318  }
319
320  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
321  // AbstractValueGraph) derives its behavior from calling successors().
322  private static class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> {
323    private final ValueGraph<N, V> graph;
324
325    TransposedValueGraph(ValueGraph<N, V> graph) {
326      this.graph = graph;
327    }
328
329    @Override
330    protected ValueGraph<N, V> delegate() {
331      return graph;
332    }
333
334    @Override
335    public Set<N> predecessors(N node) {
336      return delegate().successors(node); // transpose
337    }
338
339    @Override
340    public Set<N> successors(N node) {
341      return delegate().predecessors(node); // transpose
342    }
343
344    @Override
345    public int inDegree(N node) {
346      return delegate().outDegree(node); // transpose
347    }
348
349    @Override
350    public int outDegree(N node) {
351      return delegate().inDegree(node); // transpose
352    }
353
354    @Override
355    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
356      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
357    }
358
359    @Override
360    @NullableDecl
361    public V edgeValueOrDefault(N nodeU, N nodeV, @NullableDecl V defaultValue) {
362      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
363    }
364  }
365
366  /**
367   * Returns a view of {@code network} with the direction (if any) of every edge reversed. All other
368   * properties remain intact, and further updates to {@code network} will be reflected in the view.
369   */
370  public static <N, E> Network<N, E> transpose(Network<N, E> network) {
371    if (!network.isDirected()) {
372      return network; // the transpose of an undirected network is an identical network
373    }
374
375    if (network instanceof TransposedNetwork) {
376      return ((TransposedNetwork<N, E>) network).network;
377    }
378
379    return new TransposedNetwork<>(network);
380  }
381
382  private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
383    private final Network<N, E> network;
384
385    TransposedNetwork(Network<N, E> network) {
386      this.network = network;
387    }
388
389    @Override
390    protected Network<N, E> delegate() {
391      return network;
392    }
393
394    @Override
395    public Set<N> predecessors(N node) {
396      return delegate().successors(node); // transpose
397    }
398
399    @Override
400    public Set<N> successors(N node) {
401      return delegate().predecessors(node); // transpose
402    }
403
404    @Override
405    public int inDegree(N node) {
406      return delegate().outDegree(node); // transpose
407    }
408
409    @Override
410    public int outDegree(N node) {
411      return delegate().inDegree(node); // transpose
412    }
413
414    @Override
415    public Set<E> inEdges(N node) {
416      return delegate().outEdges(node); // transpose
417    }
418
419    @Override
420    public Set<E> outEdges(N node) {
421      return delegate().inEdges(node); // transpose
422    }
423
424    @Override
425    public EndpointPair<N> incidentNodes(E edge) {
426      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
427      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
428    }
429
430    @Override
431    public Set<E> edgesConnecting(N nodeU, N nodeV) {
432      return delegate().edgesConnecting(nodeV, nodeU); // transpose
433    }
434
435    @Override
436    public E edgeConnectingOrNull(N nodeU, N nodeV) {
437      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
438    }
439
440    @Override
441    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
442      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
443    }
444  }
445
446  // Graph copy methods
447
448  /**
449   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
450   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
451   * from {@code graph} for which both nodes are contained by {@code nodes}.
452   *
453   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
454   */
455  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
456    MutableGraph<N> subgraph =
457        (nodes instanceof Collection)
458            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
459            : GraphBuilder.from(graph).build();
460    for (N node : nodes) {
461      subgraph.addNode(node);
462    }
463    for (N node : subgraph.nodes()) {
464      for (N successorNode : graph.successors(node)) {
465        if (subgraph.nodes().contains(successorNode)) {
466          subgraph.putEdge(node, successorNode);
467        }
468      }
469    }
470    return subgraph;
471  }
472
473  /**
474   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
475   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
476   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
477   * nodes}.
478   *
479   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
480   */
481  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
482      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
483    MutableValueGraph<N, V> subgraph =
484        (nodes instanceof Collection)
485            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
486            : ValueGraphBuilder.from(graph).build();
487    for (N node : nodes) {
488      subgraph.addNode(node);
489    }
490    for (N node : subgraph.nodes()) {
491      for (N successorNode : graph.successors(node)) {
492        if (subgraph.nodes().contains(successorNode)) {
493          subgraph.putEdgeValue(
494              node, successorNode, graph.edgeValueOrDefault(node, successorNode, null));
495        }
496      }
497    }
498    return subgraph;
499  }
500
501  /**
502   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
503   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
504   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
505   * both contained by {@code nodes}.
506   *
507   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
508   */
509  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
510      Network<N, E> network, Iterable<? extends N> nodes) {
511    MutableNetwork<N, E> subgraph =
512        (nodes instanceof Collection)
513            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
514            : NetworkBuilder.from(network).build();
515    for (N node : nodes) {
516      subgraph.addNode(node);
517    }
518    for (N node : subgraph.nodes()) {
519      for (E edge : network.outEdges(node)) {
520        N successorNode = network.incidentNodes(edge).adjacentNode(node);
521        if (subgraph.nodes().contains(successorNode)) {
522          subgraph.addEdge(node, successorNode, edge);
523        }
524      }
525    }
526    return subgraph;
527  }
528
529  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
530  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
531    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
532    for (N node : graph.nodes()) {
533      copy.addNode(node);
534    }
535    for (EndpointPair<N> edge : graph.edges()) {
536      copy.putEdge(edge.nodeU(), edge.nodeV());
537    }
538    return copy;
539  }
540
541  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
542  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
543    MutableValueGraph<N, V> copy =
544        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
545    for (N node : graph.nodes()) {
546      copy.addNode(node);
547    }
548    for (EndpointPair<N> edge : graph.edges()) {
549      copy.putEdgeValue(
550          edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
551    }
552    return copy;
553  }
554
555  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
556  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
557    MutableNetwork<N, E> copy =
558        NetworkBuilder.from(network)
559            .expectedNodeCount(network.nodes().size())
560            .expectedEdgeCount(network.edges().size())
561            .build();
562    for (N node : network.nodes()) {
563      copy.addNode(node);
564    }
565    for (E edge : network.edges()) {
566      EndpointPair<N> endpointPair = network.incidentNodes(edge);
567      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
568    }
569    return copy;
570  }
571
572  @CanIgnoreReturnValue
573  static int checkNonNegative(int value) {
574    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
575    return value;
576  }
577
578  @CanIgnoreReturnValue
579  static int checkPositive(int value) {
580    checkArgument(value > 0, "Not true that %s is positive.", value);
581    return value;
582  }
583
584  @CanIgnoreReturnValue
585  static long checkNonNegative(long value) {
586    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
587    return value;
588  }
589
590  @CanIgnoreReturnValue
591  static long checkPositive(long value) {
592    checkArgument(value > 0, "Not true that %s is positive.", value);
593    return value;
594  }
595
596  /**
597   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
598   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
599   * been already explored. Any node that has not been explored will not have a state at all.
600   */
601  private enum NodeVisitState {
602    PENDING,
603    COMPLETE
604  }
605}