com.google.common.graph.Network类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(187)

本文整理了Java中com.google.common.graph.Network类的一些代码示例,展示了Network类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Network类的具体详情如下:
包路径:com.google.common.graph.Network
类名称:Network

Network介绍

[英]An interface for graph-structured data, whose edges are unique objects.

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

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

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

Building a Network

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

MutableNetwork graph = NetworkBuilder.directed().build();

NetworkBuilder#build() returns an instance of MutableNetwork, which is a subtype of Network 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 Network interface, or an ImmutableNetwork.

You can create an immutable copy of an existing Network using ImmutableNetwork#copyOf(Network):

ImmutableNetwork immutableGraph = ImmutableNetwork.copyOf(graph);

Instances of ImmutableNetwork do not implement MutableNetwork (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
    [中]用于graph结构化数据的接口,其边是唯一的对象。
    图由一组节点和一组连接成对节点的边组成。
    提供了三个主要接口来表示图形。按照复杂性的增加顺序,它们是:图、值图和网络。通常,您应该更喜欢满足您的用例的最简单接口。有关更多详细信息,请参阅《番石榴用户指南》的{$1$}部分。
    ####能力
    网络支持以下用例(definitions of terms):
    *有向图
    *无向图
    *允许/不允许平行边的图
    *允许/不允许自循环的图
    *节点/边按插入顺序、排序或无序排列的图
    *边是唯一对象的图
    ####建立网络
    这些实现类很常见。根据设计,graph提供的服务不是公开的。要创建网络的一个内置实现的实例,请使用NetworkBuilder类:
MutableNetwork graph = NetworkBuilder.directed().build();

NetworkBuilder#build()返回MutableNetwork的一个实例,它是网络的一个子类型,提供添加和删除节点和边的方法。如果您不需要对图形进行变异(例如,如果您编写的方法在图形上运行只读算法),则应使用非变异网络接口或不可变网络。
您可以使用ImmutableNetwork#copyOf(网络)创建现有网络的不可变副本:

ImmutableNetwork immutableGraph = ImmutableNetwork.copyOf(graph);

ImmutableNetwork的实例没有实现MutableNetwork(显然!)并且根据合同保证不可修改且线程安全。
{}3美元的用户指南{。
####其他文件
请参阅《番石榴用户指南》了解常见的。graph package("Graphs Explained")用于其他文档,包括:

代码示例

代码示例来源:origin: google/guava

/** Creates a mutable copy of {@code network} with the same nodes and edges. */
public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
 MutableNetwork<N, E> copy =
   NetworkBuilder.from(network)
     .expectedNodeCount(network.nodes().size())
     .expectedEdgeCount(network.edges().size())
     .build();
 for (N node : network.nodes()) {
  copy.addNode(node);
 }
 for (E edge : network.edges()) {
  EndpointPair<N> endpointPair = network.incidentNodes(edge);
  copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
 }
 return copy;
}

代码示例来源:origin: google/guava

private static <N, E> NetworkConnections<N, E> connectionsOf(Network<N, E> network, N node) {
 if (network.isDirected()) {
  Map<E, N> inEdgeMap = Maps.asMap(network.inEdges(node), sourceNodeFn(network));
  Map<E, N> outEdgeMap = Maps.asMap(network.outEdges(node), targetNodeFn(network));
  int selfLoopCount = network.edgesConnecting(node, node).size();
  return network.allowsParallelEdges()
    ? DirectedMultiNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount)
    : DirectedNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount);
 } else {
  Map<E, N> incidentEdgeMap =
    Maps.asMap(network.incidentEdges(node), adjacentNodeFn(network, node));
  return network.allowsParallelEdges()
    ? UndirectedMultiNetworkConnections.ofImmutable(incidentEdgeMap)
    : UndirectedNetworkConnections.ofImmutable(incidentEdgeMap);
 }
}

代码示例来源:origin: google/guava

/**
 * Returns true if {@code network} 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.
 *
 * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
 */
public static boolean hasCycle(Network<?, ?> network) {
 // 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 (!network.isDirected()
   && network.allowsParallelEdges()
   && network.edges().size() > network.asGraph().edges().size()) {
  return true;
 }
 return hasCycle(network.asGraph());
}

代码示例来源:origin: google/guava

private static <N, E> Map<E, N> getEdgeToReferenceNode(Network<N, E> network) {
 // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
 // whatever ordering the network's edges do, so ImmutableSortedMap is unnecessary even if the
 // input edges are sorted.
 ImmutableMap.Builder<E, N> edgeToReferenceNode = ImmutableMap.builder();
 for (E edge : network.edges()) {
  edgeToReferenceNode.put(edge, network.incidentNodes(edge).nodeU());
 }
 return edgeToReferenceNode.build();
}

代码示例来源:origin: google/guava

/**
 * Returns a {@link NetworkBuilder} initialized with all properties queryable from {@code
 * network}.
 *
 * <p>The "queryable" properties are those that are exposed through the {@link Network} interface,
 * such as {@link Network#isDirected()}. Other properties, such as {@link
 * #expectedNodeCount(int)}, are not set in the new builder.
 */
public static <N, E> NetworkBuilder<N, E> from(Network<N, E> network) {
 return new NetworkBuilder<N, E>(network.isDirected())
   .allowsParallelEdges(network.allowsParallelEdges())
   .allowsSelfLoops(network.allowsSelfLoops())
   .nodeOrder(network.nodeOrder())
   .edgeOrder(network.edgeOrder());
}

代码示例来源:origin: google/guava

assertThat(networkString).contains("isDirected: " + network.isDirected());
assertThat(networkString).contains("allowsParallelEdges: " + network.allowsParallelEdges());
assertThat(networkString).contains("allowsSelfLoops: " + network.allowsSelfLoops());
Graph<N> asGraph = network.asGraph();
AbstractGraphTest.validateGraph(asGraph);
assertThat(network.nodes()).isEqualTo(asGraph.nodes());
assertThat(network.edges().size()).isAtLeast(asGraph.edges().size());
assertThat(network.nodeOrder()).isEqualTo(asGraph.nodeOrder());
assertThat(network.isDirected()).isEqualTo(asGraph.isDirected());
assertThat(network.allowsSelfLoops()).isEqualTo(asGraph.allowsSelfLoops());
for (E edge : sanityCheckSet(network.edges())) {
 EndpointPair<N> endpointPair = network.incidentNodes(edge);
 N nodeU = endpointPair.nodeU();
 N nodeV = endpointPair.nodeV();
 assertThat(asGraph.edges()).contains(EndpointPair.of(network, nodeU, nodeV));
 assertThat(network.edgesConnecting(nodeU, nodeV)).contains(edge);
 assertThat(network.successors(nodeU)).contains(nodeV);
 assertThat(network.adjacentNodes(nodeU)).contains(nodeV);
 assertThat(network.outEdges(nodeU)).contains(edge);
 assertThat(network.incidentEdges(nodeU)).contains(edge);
 assertThat(network.predecessors(nodeV)).contains(nodeU);
 assertThat(network.adjacentNodes(nodeV)).contains(nodeU);
 assertThat(network.inEdges(nodeV)).contains(edge);
 assertThat(network.incidentEdges(nodeV)).contains(edge);
 for (N incidentNode : network.incidentNodes(edge)) {

代码示例来源:origin: google/guava

@Override
public final boolean equals(@Nullable Object obj) {
 if (obj == this) {
  return true;
 }
 if (!(obj instanceof Network)) {
  return false;
 }
 Network<?, ?> other = (Network<?, ?>) obj;
 return isDirected() == other.isDirected()
   && nodes().equals(other.nodes())
   && edgeIncidentNodesMap(this).equals(edgeIncidentNodesMap(other));
}

代码示例来源:origin: google/guava

AbstractNetworkTest.validateNetwork(transpose);
assertThat(transpose.edgesConnecting(N1, N2)).isEmpty();
assertThat(transpose.edgeConnecting(N1, N2).isPresent()).isFalse();
assertThat(transpose.edgeConnectingOrNull(N1, N2)).isNull();
 assertThat(directedGraph.inDegree(node)).isSameAs(transpose.outDegree(node));
 assertThat(directedGraph.outDegree(node)).isSameAs(transpose.inDegree(node));
assertThat(transpose.edgesConnecting(N1, N2)).containsExactly(E21);
assertThat(transpose.edgeConnecting(N1, N2).get()).isEqualTo(E21);
assertThat(transpose.edgeConnectingOrNull(N1, N2)).isEqualTo(E21);
AbstractNetworkTest.validateNetwork(transpose);

代码示例来源:origin: jrtom/jung

public Double apply(VEPair<N, E> ve_pair) {
  E e = ve_pair.getE();
  N v = ve_pair.getV();
  return graph.isDirected()
    ? 1.0 / graph.outDegree(graph.incidentNodes(e).source())
    : 1.0 / graph.degree(v);
 }
}

代码示例来源:origin: google/guava

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

代码示例来源:origin: google/guava

@Override
 public EndpointPair<N> apply(E edge) {
  return network.incidentNodes(edge);
 }
};

代码示例来源:origin: jrtom/jung

public void setNetwork(Network<N, E> network, boolean forceUpdate) {
 log.trace("setNetwork to n:{} e:{}", network.nodes(), network.edges());
 this.network = network;
 this.layoutModel.setGraph(network.asGraph());
 if (forceUpdate && this.layoutAlgorithm != null) {
  log.trace("will accept {}", layoutAlgorithm);
  layoutModel.accept(this.layoutAlgorithm);
  log.trace("will fire stateChanged");
  changeSupport.fireStateChanged();
  log.trace("fired stateChanged");
 }
}

代码示例来源:origin: jrtom/jung

@Override
public void layoutChanged(LayoutEvent<N> evt) {
 // need to take care of edge changes
 N node = evt.getNode();
 Point p = evt.getLocation();
 if (visualizationModel.getNetwork().nodes().contains(node)) {
  Set<E> edges = visualizationModel.getNetwork().incidentEdges(node);
  for (E edge : edges) {
   update(edge, p);
  }
 }
}

代码示例来源:origin: google/guava

@Override
public Set<E> edgesConnecting(N nodeU, N nodeV) {
 return delegate().edgesConnecting(nodeU, nodeV);
}

代码示例来源:origin: google/guava

@Override
public boolean isDirected() {
 return delegate().isDirected();
}

代码示例来源:origin: google/guava

@Override
public int degree(N node) {
 return delegate().degree(node);
}

代码示例来源:origin: google/guava

@Override
public int inDegree(N node) {
 return delegate().inDegree(node);
}

代码示例来源:origin: google/guava

private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
  Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
    new Function<E, EndpointPair<N>>() {
     @Override
     public EndpointPair<N> apply(E edge) {
      return network.incidentNodes(edge);
     }
    };
  return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
 }
}

代码示例来源:origin: jrtom/jung

public Map<N, Integer> nodeScores() {
  return Maps.asMap(graph.nodes(), node -> graph.degree(node));
 }
}

代码示例来源:origin: batfish/batfish

/**
 * Initialize incoming EIGRP message queues for each adjacency
 *
 * @param eigrpTopology The topology representing EIGRP adjacencies
 */
void initQueues(Network<EigrpInterface, EigrpEdge> eigrpTopology) {
 _incomingRoutes =
   _interfaces.stream()
     .filter(eigrpTopology.nodes()::contains)
     .flatMap(n -> eigrpTopology.inEdges(n).stream())
     .collect(toImmutableSortedMap(Function.identity(), e -> new ConcurrentLinkedQueue<>()));
}

相关文章