All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.topicus.jdbc.shaded.com.google.common.graph.Graphs Maven / Gradle / Ivy

There is a newer version: 1.1.6
Show newest version
/*
 * Copyright (C) 2014 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in nl.topicus.jdbc.shaded.com.liance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.nl.topicus.jdbc.shaded.org.licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.graph;

import static nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.base.Preconditions.checkArgument;
import static nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.graph.GraphConstants.NODE_NOT_IN_GRAPH;

import nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.annotations.Beta;
import nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.base.Objects;
import nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.collect.Iterables;
import nl.topicus.jdbc.shaded.com.google.nl.topicus.jdbc.shaded.com.on.collect.Maps;
import nl.topicus.jdbc.shaded.com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import nl.topicus.jdbc.shaded.javax.annotation.Nullable;

/**
 * Static utility methods for {@link Graph} and {@link Network} instances.
 *
 * @author James Sexton
 * @author Joshua O'Madadhain
 * @since 20.0
 */
@Beta
public final class Graphs {

  private Graphs() {}

  // Graph query methods

  /**
   * Returns true if {@code graph} has at least one cycle. A cycle is defined as a non-empty subset
   * of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) starting
   * and ending with the same node.
   *
   * 

This method will detect any non-empty cycle, including self-loops (a cycle of length 1). */ public static boolean hasCycle(Graph graph) { int numEdges = graph.edges().size(); if (numEdges == 0) { return false; // An edge-free graph is acyclic by definition. } if (!graph.isDirected() && numEdges >= graph.nodes().size()) { return true; // Optimization for the undirected case: at least one cycle must exist. } Map visitedNodes = Maps.newHashMapWithExpectedSize(graph.nodes().size()); for (Object node : graph.nodes()) { if (subgraphHasCycle(graph, visitedNodes, node, null)) { return true; } } return false; } /** * Returns true if {@code nl.topicus.jdbc.shaded.net.ork} has at least one cycle. A cycle is defined as a non-empty * subset of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) * starting and ending with the same node. * *

This method will detect any non-empty cycle, including self-loops (a cycle of length 1). */ public static boolean hasCycle(Network nl.topicus.jdbc.shaded.net.ork) { // In a directed graph, parallel edges cannot introduce a cycle in an acyclic graph. // However, in an undirected graph, any parallel edge induces a cycle in the graph. if (!nl.topicus.jdbc.shaded.net.ork.isDirected() && nl.topicus.jdbc.shaded.net.ork.allowsParallelEdges() && nl.topicus.jdbc.shaded.net.ork.edges().size() > nl.topicus.jdbc.shaded.net.ork.asGraph().edges().size()) { return true; } return hasCycle(nl.topicus.jdbc.shaded.net.ork.asGraph()); } /** * Performs a traversal of the nodes reachable from {@code node}. If we ever reach a node we've * already visited (following only outgoing edges and without reusing edges), we know there's a * cycle in the graph. */ private static boolean subgraphHasCycle( Graph graph, Map visitedNodes, Object node, @Nullable Object previousNode) { NodeVisitState state = visitedNodes.get(node); if (state == NodeVisitState.COMPLETE) { return false; } if (state == NodeVisitState.PENDING) { return true; } visitedNodes.put(node, NodeVisitState.PENDING); for (Object nextNode : graph.successors(node)) { if (canTraverseWithoutReusingEdge(graph, nextNode, previousNode) && subgraphHasCycle(graph, visitedNodes, nextNode, node)) { return true; } } visitedNodes.put(node, NodeVisitState.COMPLETE); return false; } /** * Determines whether an edge has already been used during traversal. In the directed case a cycle * is always detected before reusing an edge, so no special logic is required. In the undirected * case, we must take care not to "backtrack" over an edge (i.e. going from A to B and then going * from B to A). */ private static boolean canTraverseWithoutReusingEdge( Graph graph, Object nextNode, @Nullable Object previousNode) { if (graph.isDirected() || !Objects.equal(previousNode, nextNode)) { return true; } // This falls into the undirected A->B->A case. The Graph interface does not support parallel // edges, so this traversal would require reusing the undirected AB edge. return false; } /** * Returns the transitive closure of {@code graph}. The transitive closure of a graph is another * graph with an edge connecting node A to node B if node B is {@link #reachableNodes(Graph, * Object) reachable} from node A. * *

This is a "snapshot" based on the current topology of {@code graph}, rather than a live view * of the transitive closure of {@code graph}. In other words, the returned {@link Graph} will not * be updated after modifications to {@code graph}. */ // TODO(b/31438252): Consider potential optimizations for this algorithm. public static Graph transitiveClosure(Graph graph) { MutableGraph transitiveClosure = GraphBuilder.from(graph).allowsSelfLoops(true).build(); // Every node is, at a minimum, reachable from itself. Since the resulting transitive closure // will have no isolated nodes, we can skip adding nodes explicitly and let putEdge() do it. if (graph.isDirected()) { // Note: works for both directed and undirected graphs, but we only use in the directed case. for (N node : graph.nodes()) { for (N reachableNode : reachableNodes(graph, node)) { transitiveClosure.putEdge(node, reachableNode); } } } else { // An optimization for the undirected case: for every node B reachable from node A, // node A and node B have the same reachability set. Set visitedNodes = new HashSet(); for (N node : graph.nodes()) { if (!visitedNodes.contains(node)) { Set reachableNodes = reachableNodes(graph, node); visitedNodes.addAll(reachableNodes); int pairwiseMatch = 1; // start at 1 to include self-loops for (N nodeU : reachableNodes) { for (N nodeV : Iterables.limit(reachableNodes, pairwiseMatch++)) { transitiveClosure.putEdge(nodeU, nodeV); } } } } } return transitiveClosure; } /** * Returns the set of nodes that are reachable from {@code node}. Node B is defined as reachable * from node A if there exists a path (a sequence of adjacent outgoing edges) starting at node A * and ending at node B. Note that a node is always reachable from itself via a zero-length path. * *

This is a "snapshot" based on the current topology of {@code graph}, rather than a live view * of the set of nodes reachable from {@code node}. In other words, the returned {@link Set} will * not be updated after modifications to {@code graph}. * * @throws IllegalArgumentException if {@code node} is not present in {@code graph} */ @SuppressWarnings("unchecked") // Safe because we only cast if node is an element of the graph. public static Set reachableNodes(Graph graph, Object node) { checkArgument(graph.nodes().contains(node), NODE_NOT_IN_GRAPH, node); Set visitedNodes = new LinkedHashSet(); Queue queuedNodes = new ArrayDeque(); visitedNodes.add((N) node); queuedNodes.add((N) node); // Perform a breadth-first traversal rooted at the input node. while (!queuedNodes.isEmpty()) { N currentNode = queuedNodes.remove(); for (N successor : graph.successors(currentNode)) { if (visitedNodes.add(successor)) { queuedNodes.add(successor); } } } return Collections.unmodifiableSet(visitedNodes); } /** * Returns {@code true} if {@code graphA} and {@code graphB} have the same elements and the same * relationships between elements, as exposed via the {@link Graph} interface. * *

Thus, two graphs A and B are equivalent if both are null or all of the following are * true: * *

    *
  • A and B have equal {@link Graph#isDirected() directedness}. *
  • A and B have equal {@link Graph#nodes() node sets}. *
  • A and B have equal {@link Graph#edges() edge sets}. *
* *

Graph properties besides {@link Graph#isDirected() directedness} do not affect * equivalence. For example, two graphs may be considered equivalent even if one allows self-loops * and the other doesn't. Additionally, the order in which nodes or edges are added to the graph, * and the order in which they are iterated over, are irrelevant. */ public static boolean equivalent(@Nullable Graph graphA, @Nullable Graph graphB) { if (graphA == graphB) { return true; } if (graphA == null || graphB == null) { return false; } return graphA.isDirected() == graphB.isDirected() && graphA.nodes().equals(graphB.nodes()) && graphA.edges().equals(graphB.edges()); } /** * Returns {@code true} if {@code graphA} and {@code graphB} have the same elements (including * edge values) and the same relationships between elements, as exposed via the {@link ValueGraph} * interface. * *

Thus, two value graphs A and B are equivalent if both are null or all of the * following are true: * *

    *
  • A and B have equal {@link Graph#isDirected() directedness}. *
  • A and B have equal {@link Graph#nodes() node sets}. *
  • A and B have equal {@link Graph#edges() edge sets}. *
  • Each edge in A has a {@link ValueGraph#edgeValue(Object, Object) value} equal to the {@link * ValueGraph#edgeValue(Object, Object) value} of the corresponding edge in B. *
* *

Graph properties besides {@link Graph#isDirected() directedness} do not affect * equivalence. For example, two graphs may be considered equivalent even if one allows self-loops * and the other doesn't. Additionally, the order in which nodes or edges are added to the graph, * and the order in which they are iterated over, are irrelevant. */ public static boolean equivalent( @Nullable ValueGraph graphA, @Nullable ValueGraph graphB) { if (graphA == graphB) { return true; } if (graphA == null || graphB == null) { return false; } if (graphA.isDirected() != graphB.isDirected() || !graphA.nodes().equals(graphB.nodes()) || !graphA.edges().equals(graphB.edges())) { return false; } for (EndpointPair edge : graphA.edges()) { if (!graphA .edgeValue(edge.nodeU(), edge.nodeV()) .equals(graphB.edgeValue(edge.nodeU(), edge.nodeV()))) { return false; } } return true; } /** * Returns {@code true} if {@code nl.topicus.jdbc.shaded.net.orkA} and {@code nl.topicus.jdbc.shaded.net.orkB} have the same elements and the * same relationships between elements, as exposed via the {@link Network} interface. * *

Thus, two nl.topicus.jdbc.shaded.net.orks A and B are equivalent if both are null or all of the following * are true: * *

    *
  • A and B have equal {@link Network#isDirected() directedness}. *
  • A and B have equal {@link Network#nodes() node sets}. *
  • A and B have equal {@link Network#edges() edge sets}. *
  • Each edge in A connects the same nodes in the same direction (if any) as the corresponding * edge in B. *
* *

Network properties besides {@link Network#isDirected() directedness} do not affect * equivalence. For example, two nl.topicus.jdbc.shaded.net.orks may be considered equal even if one allows parallel * edges and the other doesn't. Additionally, the order in which nodes or edges are added to the * nl.topicus.jdbc.shaded.net.ork, and the order in which they are iterated over, are irrelevant. */ public static boolean equivalent( @Nullable Network nl.topicus.jdbc.shaded.net.orkA, @Nullable Network nl.topicus.jdbc.shaded.net.orkB) { if (nl.topicus.jdbc.shaded.net.orkA == nl.topicus.jdbc.shaded.net.orkB) { return true; } if (nl.topicus.jdbc.shaded.net.orkA == null || nl.topicus.jdbc.shaded.net.orkB == null) { return false; } if (nl.topicus.jdbc.shaded.net.orkA.isDirected() != nl.topicus.jdbc.shaded.net.orkB.isDirected() || !nl.topicus.jdbc.shaded.net.orkA.nodes().equals(nl.topicus.jdbc.shaded.net.orkB.nodes()) || !nl.topicus.jdbc.shaded.net.orkA.edges().equals(nl.topicus.jdbc.shaded.net.orkB.edges())) { return false; } for (Object edge : nl.topicus.jdbc.shaded.net.orkA.edges()) { if (!nl.topicus.jdbc.shaded.net.orkA.incidentNodes(edge).equals(nl.topicus.jdbc.shaded.net.orkB.incidentNodes(edge))) { return false; } } return true; } // Graph mutation methods // Graph view methods /** * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code graph} will be reflected in the view. */ public static Graph transpose(Graph graph) { if (!graph.isDirected()) { return graph; // the transpose of an undirected graph is an identical graph } if (graph instanceof TransposedGraph) { return ((TransposedGraph) graph).graph; } return new TransposedGraph(graph); } private static class TransposedGraph extends AbstractGraph { private final Graph graph; TransposedGraph(Graph graph) { this.graph = graph; } @Override public Set nodes() { return graph.nodes(); } /** * Defer to {@link AbstractGraph#edges()} (based on {@link #successors(Object)}) for full * edges() implementation. */ @Override protected long edgeCount() { return graph.edges().size(); } @Override public boolean isDirected() { return graph.isDirected(); } @Override public boolean allowsSelfLoops() { return graph.allowsSelfLoops(); } @Override public ElementOrder nodeOrder() { return graph.nodeOrder(); } @Override public Set adjacentNodes(Object node) { return graph.adjacentNodes(node); } @Override public Set predecessors(Object node) { return graph.successors(node); // transpose } @Override public Set successors(Object node) { return graph.predecessors(node); // transpose } } /** * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code graph} will be reflected in the view. */ public static ValueGraph transpose(ValueGraph graph) { if (!graph.isDirected()) { return graph; // the transpose of an undirected graph is an identical graph } if (graph instanceof TransposedValueGraph) { return ((TransposedValueGraph) graph).graph; } return new TransposedValueGraph(graph); } private static class TransposedValueGraph extends AbstractValueGraph { private final ValueGraph graph; TransposedValueGraph(ValueGraph graph) { this.graph = graph; } @Override public Set nodes() { return graph.nodes(); } /** * Defer to {@link AbstractGraph#edges()} (based on {@link #successors(Object)}) for full * edges() implementation. */ @Override protected long edgeCount() { return graph.edges().size(); } @Override public boolean isDirected() { return graph.isDirected(); } @Override public boolean allowsSelfLoops() { return graph.allowsSelfLoops(); } @Override public ElementOrder nodeOrder() { return graph.nodeOrder(); } @Override public Set adjacentNodes(Object node) { return graph.adjacentNodes(node); } @Override public Set predecessors(Object node) { return graph.successors(node); // transpose } @Override public Set successors(Object node) { return graph.predecessors(node); // transpose } @Override public V edgeValue(Object nodeU, Object nodeV) { return graph.edgeValue(nodeV, nodeU); // transpose } @Override public V edgeValueOrDefault(Object nodeU, Object nodeV, @Nullable V defaultValue) { return graph.edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose } } /** * Returns a view of {@code nl.topicus.jdbc.shaded.net.ork} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code nl.topicus.jdbc.shaded.net.ork} will be reflected in the view. */ public static Network transpose(Network nl.topicus.jdbc.shaded.net.ork) { if (!nl.topicus.jdbc.shaded.net.ork.isDirected()) { return nl.topicus.jdbc.shaded.net.ork; // the transpose of an undirected nl.topicus.jdbc.shaded.net.ork is an identical nl.topicus.jdbc.shaded.net.ork } if (nl.topicus.jdbc.shaded.net.ork instanceof TransposedNetwork) { return ((TransposedNetwork) nl.topicus.jdbc.shaded.net.ork).nl.topicus.jdbc.shaded.net.ork; } return new TransposedNetwork(nl.topicus.jdbc.shaded.net.ork); } private static class TransposedNetwork extends AbstractNetwork { private final Network nl.topicus.jdbc.shaded.net.ork; TransposedNetwork(Network nl.topicus.jdbc.shaded.net.ork) { this.nl.topicus.jdbc.shaded.net.ork = nl.topicus.jdbc.shaded.net.ork; } @Override public Set nodes() { return nl.topicus.jdbc.shaded.net.ork.nodes(); } @Override public Set edges() { return nl.topicus.jdbc.shaded.net.ork.edges(); } @Override public boolean isDirected() { return nl.topicus.jdbc.shaded.net.ork.isDirected(); } @Override public boolean allowsParallelEdges() { return nl.topicus.jdbc.shaded.net.ork.allowsParallelEdges(); } @Override public boolean allowsSelfLoops() { return nl.topicus.jdbc.shaded.net.ork.allowsSelfLoops(); } @Override public ElementOrder nodeOrder() { return nl.topicus.jdbc.shaded.net.ork.nodeOrder(); } @Override public ElementOrder edgeOrder() { return nl.topicus.jdbc.shaded.net.ork.edgeOrder(); } @Override public Set adjacentNodes(Object node) { return nl.topicus.jdbc.shaded.net.ork.adjacentNodes(node); } @Override public Set predecessors(Object node) { return nl.topicus.jdbc.shaded.net.ork.successors(node); // transpose } @Override public Set successors(Object node) { return nl.topicus.jdbc.shaded.net.ork.predecessors(node); // transpose } @Override public Set incidentEdges(Object node) { return nl.topicus.jdbc.shaded.net.ork.incidentEdges(node); } @Override public Set inEdges(Object node) { return nl.topicus.jdbc.shaded.net.ork.outEdges(node); // transpose } @Override public Set outEdges(Object node) { return nl.topicus.jdbc.shaded.net.ork.inEdges(node); // transpose } @Override public EndpointPair incidentNodes(Object edge) { EndpointPair endpointPair = nl.topicus.jdbc.shaded.net.ork.incidentNodes(edge); return EndpointPair.of(nl.topicus.jdbc.shaded.net.ork, endpointPair.nodeV(), endpointPair.nodeU()); // transpose } @Override public Set adjacentEdges(Object edge) { return nl.topicus.jdbc.shaded.net.ork.adjacentEdges(edge); } @Override public Set edgesConnecting(Object nodeU, Object nodeV) { return nl.topicus.jdbc.shaded.net.ork.edgesConnecting(nodeV, nodeU); // transpose } } // Graph copy methods /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * from {@code graph} for which both nodes are contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static MutableGraph inducedSubgraph(Graph graph, Iterable nodes) { MutableGraph subgraph = GraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { subgraph.putEdge(node, successorNode); } } } return subgraph; } /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * (and associated edge values) from {@code graph} for which both nodes are contained by {@code * nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static MutableValueGraph inducedSubgraph( ValueGraph graph, Iterable nodes) { MutableValueGraph subgraph = ValueGraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { subgraph.putEdgeValue(node, successorNode, graph.edgeValue(node, successorNode)); } } } return subgraph; } /** * Returns the subgraph of {@code nl.topicus.jdbc.shaded.net.ork} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges} * from {@code nl.topicus.jdbc.shaded.net.ork} for which the {@link Network#incidentNodes(Object) incident nodes} are * both contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static MutableNetwork inducedSubgraph( Network nl.topicus.jdbc.shaded.net.ork, Iterable nodes) { MutableNetwork subgraph = NetworkBuilder.from(nl.topicus.jdbc.shaded.net.ork).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (E edge : nl.topicus.jdbc.shaded.net.ork.outEdges(node)) { N successorNode = nl.topicus.jdbc.shaded.net.ork.incidentNodes(edge).adjacentNode(node); if (subgraph.nodes().contains(successorNode)) { subgraph.addEdge(node, successorNode, edge); } } } return subgraph; } /** Creates a mutable copy of {@code graph} with the same nodes and edges. */ public static MutableGraph copyOf(Graph graph) { MutableGraph copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair edge : graph.edges()) { copy.putEdge(edge.nodeU(), edge.nodeV()); } return copy; } /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */ public static MutableValueGraph copyOf(ValueGraph graph) { MutableValueGraph copy = ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair edge : graph.edges()) { copy.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge.nodeU(), edge.nodeV())); } return copy; } /** Creates a mutable copy of {@code nl.topicus.jdbc.shaded.net.ork} with the same nodes and edges. */ public static MutableNetwork copyOf(Network nl.topicus.jdbc.shaded.net.ork) { MutableNetwork copy = NetworkBuilder.from(nl.topicus.jdbc.shaded.net.ork) .expectedNodeCount(nl.topicus.jdbc.shaded.net.ork.nodes().size()) .expectedEdgeCount(nl.topicus.jdbc.shaded.net.ork.edges().size()) .build(); for (N node : nl.topicus.jdbc.shaded.net.ork.nodes()) { copy.addNode(node); } for (E edge : nl.topicus.jdbc.shaded.net.ork.edges()) { EndpointPair endpointPair = nl.topicus.jdbc.shaded.net.ork.incidentNodes(edge); copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge); } return copy; } @CanIgnoreReturnValue static int checkNonNegative(int value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static int checkPositive(int value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } @CanIgnoreReturnValue static long checkNonNegative(long value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static long checkPositive(long value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } /** * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have * been already explored. Any node that has not been explored will not have a state at all. */ private enum NodeVisitState { PENDING, COMPLETE } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy