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

find nodes with multiple parents using networkx

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

启用的关系
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"})
])

运行 这个,我得到:

所以我在这里考虑的是 MN12 有 parents P1P2。所以我想考虑 P2 与 P1 相关,以 MN12 作为映射 table.

换句话说,如果我hard-code关系图我想要:

G = nx.DiGraph()

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

G.add_nodes_from([

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

])

请注意 C21 仍然是 C2 的 child。只修改了MN12,因为它有2个parents.

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

回到我的输入图:

(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_edges and successors

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

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