如何在保留NetworkX网络的同时编写算法来切割节点?

时间:2018-05-04 13:34:54

标签: networkx graph-theory

假设我有一个简单的网络如下,我想删除小写节点,同时保留整体结构。我怎么做?这是一些示例代码:

import networkx as nx
G = nx.DiGraph();
G.add_edge("A","b")
G.add_edge("b","C")
G.add_edge("b","D")
G.add_edge("D","e")
G.add_edge("e","F")


def printHackyDot(x):
    for n in x.nodes():
        for pre in x.predecessors(n):
            print(pre + " -> " + n)

printHackyDot(G)
badNodes = [n for n in G.nodes if str.islower(n)]

运行它将产生:

A -> b
b -> C
b -> D
D -> e
e -> F

This digraph

如何编写f(G),以便得到类似的简化图形,而不是小写节点:

A -> C
A -> D
D -> F

What I want

我尝试了以下操作,但是当你连续两个小写时它会失败:

for badNode in [x for x  in list(G.nodes) if str.islower(x)]:
    R.remove_node(badNode)
    for predNode in G.predecessors(badNode):
        for succNode in G.successors(badNode):
            R.add_edge(predNode,succNode)

2 个答案:

答案 0 :(得分:0)

我假设R作为G的副本开始?

如果您替换

,这将有效
for badNode in [x for x  in list(G.nodes) if str.islower(x)]:
    R.remove_node(badNode)
    for predNode in G.predecessors(badNode):
        for succNode in G.successors(badNode):
            R.add_edge(predNode,succNode)

with(编辑过早删除badNode错误

for badNode in [x for x  in list(R.nodes) if str.islower(x)]:
    for predNode in R.predecessors(badNode):
        for succNode in R.successors(badNode):
            R.add_edge(predNode,succNode)
    R.remove_node(badNode)

问题是,当您处理一行中的两个小写节点中的第一个时,它会删除该节点。但是当你处理另一个时,它会在G中看到该节点具有小写邻居,并且它将边缘放回去。如果您在R中查看它的邻居,您将正确处理它。

答案 1 :(得分:0)

如果图表是DAG,则执行此操作。聪明的人可以解决这个问题。

def isBadNode(x):
    return str.islower(x)

def goodPreds(X,node):
    return [n for n in X.predecessors(node) if not isBadNode(n)]+[gn for n in X.predecessors(node) for gn in goodPreds(X,n) if isBadNode(n)]

def goodSuccs(X,node):
    return [n for n in X.successors(node) if not isBadNode(n)]+[gn for n in X.successors(node) for gn in goodSuccs(X,n) if isBadNode(n)]

R= G.copy()
for badNode in [x for x  in list(R.nodes) if isBadNode(x)]:
    for predNode in goodPreds(G,badNode):
        for succNode in goodSuccs(G,badNode):
            R.add_edge(predNode,succNode)
    R.remove_node(badNode)