使用 networkx 查找具有多个父节点的节点

问题描述

假设我有一个有向图(这是关于关系表的)。我想找到 M:N 表来跟踪通过 M:N 表启用的关系。

from pathlib import Path
import subprocess
import networkx as nx

def write_svg(g,name):
    temp = "temp.dot"
    suffix = "jpg"
    nx.nx_agraph.write_dot(g,temp)
    pa_img = Path(f"{name}.{suffix}")
    li_cmd = f"/opt/local/bin/dot {temp} -T {suffix} -o {pa_img}".split()
    subprocess.check_output(li_cmd)

G = nx.DiGraph()

G.add_edge("C1","P1")
G.add_edge("C2","P1")
G.add_edge("C21","C2")
G.add_edge("MN12","P1")
G.add_edge("MN12","P2")
G.add_nodes_from([
    ("MN12",{"color" : "red"})
])

运行这个,我得到:

enter image description here

所以我在这里考虑的是 MN12 作为父级 P1P2。所以我想考虑P2与P1相关,以MN12为映射表。

换句话说,如果我对我想要的关系图进行硬编码:

G = nx.DiGraph()

G.add_edge("C1","C2")
G.add_edge("P2(using MN12)","P1")

G.add_nodes_from([

    ("P2(using MN12)",{"color" : "green"})

])

enter image description here

请注意,C21 仍然是 C2 的子代。只有 MN12修改,因为它有 2 个父级。

现在,我知道我可以看到给定节点的度数了。

回到我的输入图:

(Pdb++) G.degree('MN12')
2
(Pdb++) G.degree('C1')
1
(Pdb++) G.degree('C2')
2
(Pdb++) G.degree('P1')
3

但是我如何看到来自 MN12 的箭头指向 P1 和 P2?这甚至是 networkx 的问题吗?

解决方法

您可以同时使用 out_edgessuccessors

>>> G.out_edges("MN12")
OutEdgeDataView([('MN12','P1'),('MN12','P2')])

>>> list(G.successors("MN12"))
['P1','P2']