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