Tabnine Logo
ValueGraph
Code IndexAdd Tabnine to your IDE (free)

How to use
ValueGraph
in
com.google.common.graph

Best Java code snippets using com.google.common.graph.ValueGraph (Showing top 20 results out of 315)

origin: google/guava

/** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
 MutableValueGraph<N, V> copy =
   ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
 for (N node : graph.nodes()) {
  copy.addNode(node);
 }
 for (EndpointPair<N> edge : graph.edges()) {
  copy.putEdgeValue(
    edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
 }
 return copy;
}
origin: google/guava

 private static <N, V> GraphConnections<N, V> connectionsOf(
   final ValueGraph<N, V> graph, final N node) {
  Function<N, V> successorNodeToValueFn =
    new Function<N, V>() {
     @Override
     public V apply(N successorNode) {
      return graph.edgeValueOrDefault(node, successorNode, null);
     }
    };
  return graph.isDirected()
    ? DirectedGraphConnections.ofImmutable(
      graph.predecessors(node), Maps.asMap(graph.successors(node), successorNodeToValueFn))
    : UndirectedGraphConnections.ofImmutable(
      Maps.asMap(graph.adjacentNodes(node), successorNodeToValueFn));
 }
}
origin: google/guava

@Override
public Optional<V> edgeValue(EndpointPair<N> endpoints) {
 return delegate().edgeValue(endpoints);
}
origin: google/guava

/**
 * Returns a {@link ValueGraphBuilder} initialized with all properties queryable from {@code
 * graph}.
 *
 * <p>The "queryable" properties are those that are exposed through the {@link ValueGraph}
 * interface, such as {@link ValueGraph#isDirected()}. Other properties, such as {@link
 * #expectedNodeCount(int)}, are not set in the new builder.
 */
public static <N, V> ValueGraphBuilder<N, V> from(ValueGraph<N, V> graph) {
 return new ValueGraphBuilder<N, V>(graph.isDirected())
   .allowsSelfLoops(graph.allowsSelfLoops())
   .nodeOrder(graph.nodeOrder());
}
origin: google/guava

@Override
public final boolean equals(@Nullable Object obj) {
 if (obj == this) {
  return true;
 }
 if (!(obj instanceof ValueGraph)) {
  return false;
 }
 ValueGraph<?, ?> other = (ValueGraph<?, ?>) obj;
 return isDirected() == other.isDirected()
   && nodes().equals(other.nodes())
   && edgeValueMap(this).equals(edgeValueMap(other));
}
origin: google/guava

/**
 * Defer to {@link AbstractValueGraph#edges()} (based on {@link #successors(Object)}) for full
 * edges() implementation.
 */
@Override
protected long edgeCount() {
 return delegate().edges().size();
}
origin: google/guava

@Test
public void transpose_directedValueGraph() {
 MutableValueGraph<Integer, String> directedGraph =
   ValueGraphBuilder.directed().allowsSelfLoops(true).build();
 directedGraph.putEdgeValue(N1, N3, E13);
 directedGraph.putEdgeValue(N3, N1, E31);
 directedGraph.putEdgeValue(N1, N2, E12);
 directedGraph.putEdgeValue(N1, N1, E11);
 directedGraph.putEdgeValue(N3, N4, E34);
 MutableValueGraph<Integer, String> expectedTranspose =
   ValueGraphBuilder.directed().allowsSelfLoops(true).build();
 expectedTranspose.putEdgeValue(N3, N1, E13);
 expectedTranspose.putEdgeValue(N1, N3, E31);
 expectedTranspose.putEdgeValue(N2, N1, E12);
 expectedTranspose.putEdgeValue(N1, N1, E11);
 expectedTranspose.putEdgeValue(N4, N3, E34);
 ValueGraph<Integer, String> transpose = transpose(directedGraph);
 assertThat(transpose).isEqualTo(expectedTranspose);
 assertThat(transpose(transpose)).isSameAs(directedGraph);
 AbstractGraphTest.validateGraph(transpose.asGraph());
 assertThat(transpose.edgeValueOrDefault(N1, N2, null)).isNull();
 for (Integer node : directedGraph.nodes()) {
  assertThat(directedGraph.inDegree(node)).isSameAs(transpose.outDegree(node));
  assertThat(directedGraph.outDegree(node)).isSameAs(transpose.inDegree(node));
 }
 directedGraph.putEdgeValue(N2, N1, E21);
 // View should be updated.
 assertThat(transpose.edgeValueOrDefault(N1, N2, null)).isEqualTo(E21);
 AbstractGraphTest.validateGraph(transpose.asGraph());
}
origin: batfish/batfish

for (BgpPeerConfigId bgpPeerConfigId : bgpTopology.nodes()) {
 BgpPeerConfig bgpPeerConfig = nc.getBgpPeerConfig(bgpPeerConfigId);
 String hostname = bgpPeerConfigId.getHostname();
    continue;
   if (bgpTopology.adjacentNodes(bgpPeerConfigId).isEmpty()) {
    bgpSessionInfo._status = SessionStatus.HALF_OPEN;
   } else if (bgpTopology.degree(bgpPeerConfigId) > 2) {
    bgpSessionInfo._status = SessionStatus.MULTIPLE_REMOTES;
   } else {
    BgpPeerConfigId remoteNeighborId =
      bgpTopology.adjacentNodes(bgpPeerConfigId).iterator().next();
    bgpSessionInfo._remoteNode = remoteNeighborId.getHostname();
    bgpSessionInfo._status = SessionStatus.UNIQUE_MATCH;
origin: google/guava

@Override
public int inDegree(N node) {
 return delegate().outDegree(node); // transpose
}
origin: google/guava

private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections(
  ValueGraph<N, V> graph) {
 // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
 // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
 // input nodes are sorted.
 ImmutableMap.Builder<N, GraphConnections<N, V>> nodeConnections = ImmutableMap.builder();
 for (N node : graph.nodes()) {
  nodeConnections.put(node, connectionsOf(graph, node));
 }
 return nodeConnections.build();
}
origin: google/guava

@Override
public int inDegree(N node) {
 return delegate().inDegree(node);
}
origin: google/guava

 @Override
 public V apply(N successorNode) {
  return graph.edgeValueOrDefault(node, successorNode, null);
 }
};
origin: google/j2objc

/** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
 MutableValueGraph<N, V> copy =
   ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
 for (N node : graph.nodes()) {
  copy.addNode(node);
 }
 for (EndpointPair<N> edge : graph.edges()) {
  copy.putEdgeValue(
    edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
 }
 return copy;
}
origin: google/guava

@Override
public Set<N> adjacentNodes(N node) {
 return delegate().adjacentNodes(node);
}
origin: google/guava

static void assertStronglyEquivalent(ValueGraph<?, ?> graphA, ValueGraph<?, ?> graphB) {
 // Properties not covered by equals()
 assertThat(graphA.allowsSelfLoops()).isEqualTo(graphB.allowsSelfLoops());
 assertThat(graphA.nodeOrder()).isEqualTo(graphB.nodeOrder());
 assertThat(graphA).isEqualTo(graphB);
}
origin: batfish/batfish

/**
 * Initialize incoming BGP message queues.
 *
 * @param bgpTopology source of truth for which sessions get established.
 */
void initBgpQueues(ValueGraph<BgpPeerConfigId, BgpSessionProperties> bgpTopology) {
 if (_vrf.getBgpProcess() == null) {
  _bgpIncomingRoutes = ImmutableSortedMap.of();
 } else {
  _bgpIncomingRoutes =
    Stream.concat(
        _vrf.getBgpProcess().getActiveNeighbors().entrySet().stream()
          .map(
            e ->
              new BgpPeerConfigId(
                getHostname(), _vrf.getName(), e.getKey(), false)),
        _vrf.getBgpProcess().getPassiveNeighbors().entrySet().stream()
          .map(
            e ->
              new BgpPeerConfigId(getHostname(), _vrf.getName(), e.getKey(), true)))
      .filter(bgpTopology.nodes()::contains)
      .flatMap(
        dst ->
          bgpTopology.adjacentNodes(dst).stream().map(src -> new BgpEdgeId(src, dst)))
      .collect(
        toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>()));
 }
}
origin: google/guava

/**
 * 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 <N, V> MutableValueGraph<N, V> inducedSubgraph(
  ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
 MutableValueGraph<N, V> subgraph =
   (nodes instanceof Collection)
     ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
     : 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.edgeValueOrDefault(node, successorNode, null));
   }
  }
 }
 return subgraph;
}
origin: google/guava

@Override
public int degree(N node) {
 return delegate().degree(node);
}
origin: batfish/batfish

static @Nonnull ConfiguredSessionStatus getConfiguredStatus(
  BgpPeerConfigId bgpPeerConfigId,
  BgpActivePeerConfig activePeerConfig,
  SessionType sessionType,
  Set<Ip> allInterfaceIps,
  ValueGraph<BgpPeerConfigId, BgpSessionProperties> configuredBgpTopology) {
 ConfiguredSessionStatus brokenStatus = getLocallyBrokenStatus(activePeerConfig, sessionType);
 if (brokenStatus != null) {
  return brokenStatus;
 }
 // Nothing blatantly broken so far on the local side, keep checking.
 Ip localIp = activePeerConfig.getLocalIp();
 Ip remoteIp = activePeerConfig.getPeerAddress();
 if (!allInterfaceIps.contains(localIp)) {
  return ConfiguredSessionStatus.INVALID_LOCAL_IP;
 } else if (!allInterfaceIps.contains(remoteIp)) {
  return ConfiguredSessionStatus.UNKNOWN_REMOTE;
 } else if (configuredBgpTopology.adjacentNodes(bgpPeerConfigId).isEmpty()) {
  return ConfiguredSessionStatus.HALF_OPEN;
 } else if (configuredBgpTopology.outDegree(bgpPeerConfigId) > 1) {
  return ConfiguredSessionStatus.MULTIPLE_REMOTES;
 }
 return ConfiguredSessionStatus.UNIQUE_MATCH;
}
origin: google/guava

@Override
public boolean allowsSelfLoops() {
 return delegate().allowsSelfLoops();
}
com.google.common.graphValueGraph

Javadoc

An interface for graph-structured data, whose edges have associated non-unique values.

A graph is composed of a set of nodes and a set of edges connecting pairs of nodes.

There are three primary interfaces provided to represent graphs. In order of increasing complexity they are: Graph, ValueGraph, and Network. You should generally prefer the simplest interface that satisfies your use case. See the "Choosing the right graph type" section of the Guava User Guide for more details.

Capabilities

ValueGraph supports the following use cases (definitions of terms):

  • directed graphs
  • undirected graphs
  • graphs that do/don't allow self-loops
  • graphs whose nodes/edges are insertion-ordered, sorted, or unordered
  • graphs whose edges have associated values

ValueGraph, as a subtype of Graph, explicitly does not support parallel edges, and forbids implementations or extensions with parallel edges. If you need parallel edges, use Network. (You can use a positive Integer edge value as a loose representation of edge multiplicity, but the *degree() and mutation methods will not reflect your interpretation of the edge value as its multiplicity.)

Building a ValueGraph

The implementation classes that common.graph provides are not public, by design. To create an instance of one of the built-in implementations of ValueGraph, use the ValueGraphBuilder class:

 
MutableValueGraph graph = ValueGraphBuilder.directed().build();

ValueGraphBuilder#build() returns an instance of MutableValueGraph, which is a subtype of ValueGraph that provides methods for adding and removing nodes and edges. If you do not need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on the graph), you should use the non-mutating ValueGraph interface, or an ImmutableValueGraph.

You can create an immutable copy of an existing ValueGraph using ImmutableValueGraph#copyOf(ValueGraph):

 
ImmutableValueGraph immutableGraph = ImmutableValueGraph.copyOf(graph);

Instances of ImmutableValueGraph do not implement MutableValueGraph(obviously!) and are contractually guaranteed to be unmodifiable and thread-safe.

The Guava User Guide has more information on (and examples of) building graphs.

Additional documentation

See the Guava User Guide for the common.graph package ("Graphs Explained") for additional documentation, including:

  • equals(), hashCode(), and graph equivalence
  • Synchronization policy
  • Notes for implementors

Most used methods

  • nodes
    Returns all nodes in this graph, in the order specified by #nodeOrder().
  • adjacentNodes
    Returns the nodes which have an incident edge in common with node in this graph.
  • edgeValue
    Returns the value of the edge connecting nodeU to nodeV, if one is present; otherwise, returns Optio
  • edges
    Returns all edges in this graph.
  • allowsSelfLoops
    Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting to ad
  • outDegree
    Returns the count of node's outgoing edges (equal to successors(node).size()) in a directed graph. I
  • degree
    Returns the count of node's incident edges, counting self-loops twice (equivalently, the number of t
  • edgeValueOrDefault
    Returns the value of the edge connecting nodeU to nodeV, if one is present; otherwise, returns defau
  • inDegree
    Returns the count of node's incoming edges (equal to predecessors(node).size()) in a directed graph.
  • isDirected
    Returns true if the edges in this graph are directed. Directed edges connect a EndpointPair#source()
  • hasEdgeConnecting
    Returns true if there is an edge directly connecting nodeU to nodeV. This is equivalent to nodes().c
  • nodeOrder
    Returns the order of iteration for the elements of #nodes().
  • hasEdgeConnecting,
  • nodeOrder,
  • predecessors,
  • successors,
  • asGraph,
  • equals,
  • incidentEdges

Popular in Java

  • Parsing JSON documents to java classes using gson
  • setRequestProperty (URLConnection)
  • getApplicationContext (Context)
  • compareTo (BigDecimal)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • IOException (java.io)
    Signals a general, I/O-related error. Error details may be specified when calling the constructor, a
  • MessageFormat (java.text)
    Produces concatenated messages in language-neutral way. New code should probably use java.util.Forma
  • Collections (java.util)
    This class consists exclusively of static methods that operate on or return collections. It contains
  • ResourceBundle (java.util)
    ResourceBundle is an abstract class which is the superclass of classes which provide Locale-specifi
  • Options (org.apache.commons.cli)
    Main entry-point into the library. Options represents a collection of Option objects, which describ
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now