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  // 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  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
305  // AbstractValueGraph) derives its behavior from calling successors().
306  private static class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> {
307    private final ValueGraph<N, V> graph;
308
309    TransposedValueGraph(ValueGraph<N, V> graph) {
310      this.graph = graph;
311    }
312
313    @Override
314    protected ValueGraph<N, V> delegate() {
315      return graph;
316    }
317
318    @Override
319    public Set<N> predecessors(N node) {
320      return delegate().successors(node); // transpose
321    }
322
323    @Override
324    public Set<N> successors(N node) {
325      return delegate().predecessors(node); // transpose
326    }
327
328    @Override
329    public int inDegree(N node) {
330      return delegate().outDegree(node); // transpose
331    }
332
333    @Override
334    public int outDegree(N node) {
335      return delegate().inDegree(node); // transpose
336    }
337
338    @Override
339    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
340      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
341    }
342
343    @Override
344    @NullableDecl
345    public V edgeValueOrDefault(N nodeU, N nodeV, @NullableDecl V defaultValue) {
346      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
347    }
348  }
349
350  private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
351    private final Network<N, E> network;
352
353    TransposedNetwork(Network<N, E> network) {
354      this.network = network;
355    }
356
357    @Override
358    protected Network<N, E> delegate() {
359      return network;
360    }
361
362    @Override
363    public Set<N> predecessors(N node) {
364      return delegate().successors(node); // transpose
365    }
366
367    @Override
368    public Set<N> successors(N node) {
369      return delegate().predecessors(node); // transpose
370    }
371
372    @Override
373    public int inDegree(N node) {
374      return delegate().outDegree(node); // transpose
375    }
376
377    @Override
378    public int outDegree(N node) {
379      return delegate().inDegree(node); // transpose
380    }
381
382    @Override
383    public Set<E> inEdges(N node) {
384      return delegate().outEdges(node); // transpose
385    }
386
387    @Override
388    public Set<E> outEdges(N node) {
389      return delegate().inEdges(node); // transpose
390    }
391
392    @Override
393    public EndpointPair<N> incidentNodes(E edge) {
394      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
395      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
396    }
397
398    @Override
399    public Set<E> edgesConnecting(N nodeU, N nodeV) {
400      return delegate().edgesConnecting(nodeV, nodeU); // transpose
401    }
402
403    @Override
404    public E edgeConnectingOrNull(N nodeU, N nodeV) {
405      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
406    }
407
408    @Override
409    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
410      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
411    }
412  }
413
414  // Graph copy methods
415
416  /**
417   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
418   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
419   * from {@code graph} for which both nodes are contained by {@code nodes}.
420   *
421   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
422   */
423  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
424    MutableGraph<N> subgraph =
425        (nodes instanceof Collection)
426            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
427            : GraphBuilder.from(graph).build();
428    for (N node : nodes) {
429      subgraph.addNode(node);
430    }
431    for (N node : subgraph.nodes()) {
432      for (N successorNode : graph.successors(node)) {
433        if (subgraph.nodes().contains(successorNode)) {
434          subgraph.putEdge(node, successorNode);
435        }
436      }
437    }
438    return subgraph;
439  }
440
441  /**
442   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
443   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
444   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
445   * nodes}.
446   *
447   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
448   */
449  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
450      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
451    MutableValueGraph<N, V> subgraph =
452        (nodes instanceof Collection)
453            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
454            : ValueGraphBuilder.from(graph).build();
455    for (N node : nodes) {
456      subgraph.addNode(node);
457    }
458    for (N node : subgraph.nodes()) {
459      for (N successorNode : graph.successors(node)) {
460        if (subgraph.nodes().contains(successorNode)) {
461          subgraph.putEdgeValue(
462              node, successorNode, graph.edgeValueOrDefault(node, successorNode, null));
463        }
464      }
465    }
466    return subgraph;
467  }
468
469  /**
470   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
471   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
472   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
473   * both contained by {@code nodes}.
474   *
475   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
476   */
477  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
478      Network<N, E> network, Iterable<? extends N> nodes) {
479    MutableNetwork<N, E> subgraph =
480        (nodes instanceof Collection)
481            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
482            : NetworkBuilder.from(network).build();
483    for (N node : nodes) {
484      subgraph.addNode(node);
485    }
486    for (N node : subgraph.nodes()) {
487      for (E edge : network.outEdges(node)) {
488        N successorNode = network.incidentNodes(edge).adjacentNode(node);
489        if (subgraph.nodes().contains(successorNode)) {
490          subgraph.addEdge(node, successorNode, edge);
491        }
492      }
493    }
494    return subgraph;
495  }
496
497  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
498  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
499    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
500    for (N node : graph.nodes()) {
501      copy.addNode(node);
502    }
503    for (EndpointPair<N> edge : graph.edges()) {
504      copy.putEdge(edge.nodeU(), edge.nodeV());
505    }
506    return copy;
507  }
508
509  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
510  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
511    MutableValueGraph<N, V> copy =
512        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
513    for (N node : graph.nodes()) {
514      copy.addNode(node);
515    }
516    for (EndpointPair<N> edge : graph.edges()) {
517      copy.putEdgeValue(
518          edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
519    }
520    return copy;
521  }
522
523  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
524  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
525    MutableNetwork<N, E> copy =
526        NetworkBuilder.from(network)
527            .expectedNodeCount(network.nodes().size())
528            .expectedEdgeCount(network.edges().size())
529            .build();
530    for (N node : network.nodes()) {
531      copy.addNode(node);
532    }
533    for (E edge : network.edges()) {
534      EndpointPair<N> endpointPair = network.incidentNodes(edge);
535      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
536    }
537    return copy;
538  }
539
540  @CanIgnoreReturnValue
541  static int checkNonNegative(int value) {
542    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
543    return value;
544  }
545
546  @CanIgnoreReturnValue
547  static long checkNonNegative(long value) {
548    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
549    return value;
550  }
551
552  @CanIgnoreReturnValue
553  static int checkPositive(int value) {
554    checkArgument(value > 0, "Not true that %s is positive.", value);
555    return value;
556  }
557
558  @CanIgnoreReturnValue
559  static long checkPositive(long value) {
560    checkArgument(value > 0, "Not true that %s is positive.", value);
561    return value;
562  }
563
564  /**
565   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
566   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
567   * been already explored. Any node that has not been explored will not have a state at all.
568   */
569  private enum NodeVisitState {
570    PENDING,
571    COMPLETE
572  }
573}