Networkx:使用端口连接节点

3

我有这个网络:

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个回答

1

通用端口连接模型

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

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']})])

To get the anchors list, simply use:

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']}

参考文献:


1
你好@Mohanned!是的,我看到了你的回答,我很喜欢。实际上,我一直在考虑类似的事情。到目前为止,我正在使用nx.set_edge_attributes(G, {(ip_A,ip_B):data}),其中data与你的anchors相同。这种方法唯一的问题是你将锚点端口记录为边属性。我看到它的有用性,但它并没有解决我的问题。我希望端口本身成为锚点,就像一个节点一样。无论如何,谢谢你! - Lucas Aimaretto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接