Networkx:使用端口连接节点

时间:2019-07-18 13:35:11

标签: python-3.x networkx

我有这个网络:

r1 = dict( name  = 'R1', ports = dict(p1 = 'p1', p2 = 'p2') )
r2 = dict( name  = 'R2', ports = dict(p1 = 'p1', p2 = 'p2') )
r3 = dict( name  = 'R3', ports = dict(p1 = 'p1', p2 = 'p2') )
routers = [r1,r2,r3]
G = nx.Graph()
[G.add_node(r['name'], name=r['name']) for r in routers]
G.add_edges_from([('R1','R2'),('R2','R3')]

上一个产生下一个拓扑。

enter image description here

如您所见,每个节点都有其端口p1p2。我知道如何在图中创建这些边缘或连接:

In [53]: G.edges()
Out[53]: EdgeView([('R1', 'R2'), ('R2', 'R3')])

但是,我最感兴趣的是使用每个节点的端口作为连接点。含义:

In [53]: G.edges()
Out[53]: EdgeView([('R1'.'p1', 'R2'.'p2'), ('R2'.'p1', 'R3'.'p2')])

我该怎么做?或者,换句话说,从锚点最终是这些端口的节点+端口的意义上,我该如何建模呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

任何端口连接的通用模型

首先,您需要将端口作为属性添加到节点:

import networkx as nx

r1 = dict( name  = 'R1', ports = dict(p1 = 'p1', p2 = 'p2') )
r2 = dict( name  = 'R2', ports = dict(p1 = 'p1', p2 = 'p2') )
r3 = dict( name  = 'R3', ports = dict(p1 = 'p1', p2 = 'p2') )

routers = [r1,r2,r3]

G = nx.Graph()

for r in routers:
  # Add ports as attributes
  G.add_node(r['name'], name=r['name'], ports=r['ports'])

现在,如果我执行以下操作:

G.nodes().get('R3', None)

我得到以下信息:

{'name': 'R3', 'ports': {'p1': 'p1', 'p2': 'p2'}}

然后,您基本上可以添加一个包装器功能来在图形中创建边。我假设您可以使用从一个节点到另一个节点的任何其他端口的任何端口:

def add_edge_port(G, node1, port1, node2, port2):
  node_list = [node1, node2]
  port_list = [port1, port2]

  edge_ports = []

  for idx in range(0, 2):
    node_idx = node_list[idx]
    port_idx = port_list[idx]

    # Sanity check to see if the nodes and ports are present in Graph
    if G.nodes().get(node_idx, None) is None:
      print("Node : {} is not present in Graph".format(node_idx))
      return

    if G.nodes(data=True)[node_idx]['ports'].get(port_idx, None) is None:
      print("Port ID :{} is incorrect for Node ID : {}!".
            format(node_idx, port_idx))
      return

    edge_ports.append(node_idx + '.' + port_idx)

  # Add the anchor points as edge attributes
  G.add_edge(node1, node2, anchors=edge_ports)

现在添加这样的边:

add_edge_port(G, 'R1', 'p1', 'R2', 'p2')

print(G.edges(data=True))
# Output : EdgeDataView([('R1', 'R2', {'anchors': ['R1.p1', 'R2.p2']})])

要获取锚点列表,只需使用:

print(nx.get_edge_attributes(G, 'anchors'))
# Output: {('R1', 'R2'): ['R1.p1', 'R2.p2']}

现在,如果您确定端口p1将始终连接到端口p2

def add_edge_port_modified(G, node1, node2):
  # No need to check the nodes in this case
  edge_ports = [node1 + '.p1', node2 + '.p2'] 
  G.add_edge(node1, node2, anchors=edge_ports)

然后致电:

add_edge_port_modified(G, 'R2', 'R3')

并且边缘将

print(nx.get_edge_attributes(G, 'anchors'))
# Output: {('R2', 'R3'): ['R2.p1', 'R3.p2']}

参考文献: