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  // Graph mutation methods
213
214  // Graph view methods
215
216  /**
217   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
218   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
219   */
220  public static <N> Graph<N> transpose(Graph<N> graph) {
221    if (!graph.isDirected()) {
222      return graph; // the transpose of an undirected graph is an identical graph
223    }
224
225    if (graph instanceof TransposedGraph) {
226      return ((TransposedGraph<N>) graph).graph;
227    }
228
229    return new TransposedGraph<N>(graph);
230  }
231
232  /**
233   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
234   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
235   */
236  public static <N, V> ValueGraph<N, V> transpose(ValueGraph<N, V> graph) {
237    if (!graph.isDirected()) {
238      return graph; // the transpose of an undirected graph is an identical graph
239    }
240
241    if (graph instanceof TransposedValueGraph) {
242      return ((TransposedValueGraph<N, V>) graph).graph;
243    }
244
245    return new TransposedValueGraph<>(graph);
246  }
247
248  /**
249   * Returns a view of {@code network} with the direction (if any) of every edge reversed. All other
250   * properties remain intact, and further updates to {@code network} will be reflected in the view.
251   */
252  public static <N, E> Network<N, E> transpose(Network<N, E> network) {
253    if (!network.isDirected()) {
254      return network; // the transpose of an undirected network is an identical network
255    }
256
257    if (network instanceof TransposedNetwork) {
258      return ((TransposedNetwork<N, E>) network).network;
259    }
260
261    return new TransposedNetwork<>(network);
262  }
263
264  static <N> EndpointPair<N> transpose(EndpointPair<N> endpoints) {
265    if (endpoints.isOrdered()) {
266      return EndpointPair.ordered(endpoints.target(), endpoints.source());
267    }
268    return endpoints;
269  }
270
271  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
272  // AbstractGraph) derives its behavior from calling successors().
273  private static class TransposedGraph<N> extends ForwardingGraph<N> {
274    private final Graph<N> graph;
275
276    TransposedGraph(Graph<N> graph) {
277      this.graph = graph;
278    }
279
280    @Override
281    protected Graph<N> delegate() {
282      return graph;
283    }
284
285    @Override
286    public Set<N> predecessors(N node) {
287      return delegate().successors(node); // transpose
288    }
289
290    @Override
291    public Set<N> successors(N node) {
292      return delegate().predecessors(node); // transpose
293    }
294
295    @Override
296    public int inDegree(N node) {
297      return delegate().outDegree(node); // transpose
298    }
299
300    @Override
301    public int outDegree(N node) {
302      return delegate().inDegree(node); // transpose
303    }
304
305    @Override
306    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
307      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
308    }
309
310    @Override
311    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
312      return delegate().hasEdgeConnecting(transpose(endpoints));
313    }
314  }
315
316  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
317  // AbstractValueGraph) derives its behavior from calling successors().
318  private static class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> {
319    private final ValueGraph<N, V> graph;
320
321    TransposedValueGraph(ValueGraph<N, V> graph) {
322      this.graph = graph;
323    }
324
325    @Override
326    protected ValueGraph<N, V> delegate() {
327      return graph;
328    }
329
330    @Override
331    public Set<N> predecessors(N node) {
332      return delegate().successors(node); // transpose
333    }
334
335    @Override
336    public Set<N> successors(N node) {
337      return delegate().predecessors(node); // transpose
338    }
339
340    @Override
341    public int inDegree(N node) {
342      return delegate().outDegree(node); // transpose
343    }
344
345    @Override
346    public int outDegree(N node) {
347      return delegate().inDegree(node); // transpose
348    }
349
350    @Override
351    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
352      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
353    }
354
355    @Override
356    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
357      return delegate().hasEdgeConnecting(transpose(endpoints));
358    }
359
360    @Override
361    @NullableDecl
362    public V edgeValueOrDefault(N nodeU, N nodeV, @NullableDecl V defaultValue) {
363      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
364    }
365
366    @Override
367    @NullableDecl
368    public V edgeValueOrDefault(EndpointPair<N> endpoints, @NullableDecl V defaultValue) {
369      return delegate().edgeValueOrDefault(transpose(endpoints), defaultValue);
370    }
371  }
372
373  private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
374    private final Network<N, E> network;
375
376    TransposedNetwork(Network<N, E> network) {
377      this.network = network;
378    }
379
380    @Override
381    protected Network<N, E> delegate() {
382      return network;
383    }
384
385    @Override
386    public Set<N> predecessors(N node) {
387      return delegate().successors(node); // transpose
388    }
389
390    @Override
391    public Set<N> successors(N node) {
392      return delegate().predecessors(node); // transpose
393    }
394
395    @Override
396    public int inDegree(N node) {
397      return delegate().outDegree(node); // transpose
398    }
399
400    @Override
401    public int outDegree(N node) {
402      return delegate().inDegree(node); // transpose
403    }
404
405    @Override
406    public Set<E> inEdges(N node) {
407      return delegate().outEdges(node); // transpose
408    }
409
410    @Override
411    public Set<E> outEdges(N node) {
412      return delegate().inEdges(node); // transpose
413    }
414
415    @Override
416    public EndpointPair<N> incidentNodes(E edge) {
417      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
418      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
419    }
420
421    @Override
422    public Set<E> edgesConnecting(N nodeU, N nodeV) {
423      return delegate().edgesConnecting(nodeV, nodeU); // transpose
424    }
425
426    @Override
427    public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
428      return delegate().edgesConnecting(transpose(endpoints));
429    }
430
431    @Override
432    public E edgeConnectingOrNull(N nodeU, N nodeV) {
433      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
434    }
435
436    @Override
437    public E edgeConnectingOrNull(EndpointPair<N> endpoints) {
438      return delegate().edgeConnectingOrNull(transpose(endpoints));
439    }
440
441    @Override
442    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
443      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
444    }
445
446    @Override
447    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
448      return delegate().hasEdgeConnecting(transpose(endpoints));
449    }
450  }
451
452  // Graph copy methods
453
454  /**
455   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
456   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
457   * from {@code graph} for which both nodes are contained by {@code nodes}.
458   *
459   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
460   */
461  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
462    MutableGraph<N> subgraph =
463        (nodes instanceof Collection)
464            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
465            : GraphBuilder.from(graph).build();
466    for (N node : nodes) {
467      subgraph.addNode(node);
468    }
469    for (N node : subgraph.nodes()) {
470      for (N successorNode : graph.successors(node)) {
471        if (subgraph.nodes().contains(successorNode)) {
472          subgraph.putEdge(node, successorNode);
473        }
474      }
475    }
476    return subgraph;
477  }
478
479  /**
480   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
481   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
482   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
483   * nodes}.
484   *
485   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
486   */
487  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
488      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
489    MutableValueGraph<N, V> subgraph =
490        (nodes instanceof Collection)
491            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
492            : ValueGraphBuilder.from(graph).build();
493    for (N node : nodes) {
494      subgraph.addNode(node);
495    }
496    for (N node : subgraph.nodes()) {
497      for (N successorNode : graph.successors(node)) {
498        if (subgraph.nodes().contains(successorNode)) {
499          subgraph.putEdgeValue(
500              node, successorNode, graph.edgeValueOrDefault(node, successorNode, null));
501        }
502      }
503    }
504    return subgraph;
505  }
506
507  /**
508   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
509   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
510   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
511   * both contained by {@code nodes}.
512   *
513   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
514   */
515  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
516      Network<N, E> network, Iterable<? extends N> nodes) {
517    MutableNetwork<N, E> subgraph =
518        (nodes instanceof Collection)
519            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
520            : NetworkBuilder.from(network).build();
521    for (N node : nodes) {
522      subgraph.addNode(node);
523    }
524    for (N node : subgraph.nodes()) {
525      for (E edge : network.outEdges(node)) {
526        N successorNode = network.incidentNodes(edge).adjacentNode(node);
527        if (subgraph.nodes().contains(successorNode)) {
528          subgraph.addEdge(node, successorNode, edge);
529        }
530      }
531    }
532    return subgraph;
533  }
534
535  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
536  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
537    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
538    for (N node : graph.nodes()) {
539      copy.addNode(node);
540    }
541    for (EndpointPair<N> edge : graph.edges()) {
542      copy.putEdge(edge.nodeU(), edge.nodeV());
543    }
544    return copy;
545  }
546
547  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
548  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
549    MutableValueGraph<N, V> copy =
550        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
551    for (N node : graph.nodes()) {
552      copy.addNode(node);
553    }
554    for (EndpointPair<N> edge : graph.edges()) {
555      copy.putEdgeValue(
556          edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
557    }
558    return copy;
559  }
560
561  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
562  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
563    MutableNetwork<N, E> copy =
564        NetworkBuilder.from(network)
565            .expectedNodeCount(network.nodes().size())
566            .expectedEdgeCount(network.edges().size())
567            .build();
568    for (N node : network.nodes()) {
569      copy.addNode(node);
570    }
571    for (E edge : network.edges()) {
572      EndpointPair<N> endpointPair = network.incidentNodes(edge);
573      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
574    }
575    return copy;
576  }
577
578  @CanIgnoreReturnValue
579  static int checkNonNegative(int value) {
580    checkArgument(value >= 0, "Not true that %s is non-negative.", 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 int checkPositive(int value) {
592    checkArgument(value > 0, "Not true that %s is positive.", value);
593    return value;
594  }
595
596  @CanIgnoreReturnValue
597  static long checkPositive(long value) {
598    checkArgument(value > 0, "Not true that %s is positive.", value);
599    return value;
600  }
601
602  /**
603   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
604   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
605   * been already explored. Any node that has not been explored will not have a state at all.
606   */
607  private enum NodeVisitState {
608    PENDING,
609    COMPLETE
610  }
611}