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