简体   繁体   English

对networkx中的节点进行分组

[英]grouping nodes in networkx

I don't know the proper terminology, but I have a digraph in networkx and I want to merge related nodes using a mapping function, maintaining a link to the original nodes 我不知道合适的术语,但是我在networkx中有一个图,我想使用映射功能合并相关节点,并维护到原始节点的链接

For example, if I had this graph: 例如,如果我有此图:

a1 -> b1
a2 -> b2
a1 -> c1
a2 -> d2
b1 -> d2
c1 -> f1
c2 -> f2
b1 -> c2

and this function 和这个功能

def mymap(node):
    return node[0]

then I would want to get this graph as a result: 那么我想得到这个图作为结果:

a -> b
a -> c
a -> d
b -> d
c -> f
b -> c

with node data 带有节点数据

a: original_nodes = [a1, a2]
b: original_nodes = [b1, b2]
c: original_nodes = [c1, c2]
d: original_nodes = [d2]
f: original_nodes = [f1, f2]

Is there a way to do this? 有没有办法做到这一点? (without manually iterating over nodes and edges myself; I can do that, but I would think this would be a common task) (无需手动遍历节点和边缘;我可以做到这一点,但我认为这将是一项常见的任务)

hmm, I thought I'd remembered doing this before, just found this in one of my Python scripts: 嗯,我以为我以前记得做过这件事,只是在我的一个Python脚本中发现了这一点:

def supergraph(g1, keyfunc, allow_selfloops=True):
    g2 = nx.DiGraph()
    for (a,b,d) in g1.edges_iter(data=True):
        result = keyfunc(g1,a,b,d)
        if result is not None:
            a2,b2,w = result
            if a2 != b2 or allow_selfloops:
                g2.add_edge(a2,b2)
                try:
                    g2[a2][b2]['weight'] += w
                except:
                    g2[a2][b2]['weight'] = w

            for u2,u in [(a2,a),(b2,b)]:
                if not u2 in g2:
                    g2.add_node(u2, original_nodes=set([u]))
                else:
                    try:
                        g2.node[u2]['original_nodes'].add(u)
                    except:
                        g2.node[u2]['original_nodes'] = set([u])
    return g2

where keyfunc(g,a,b,d) with graph g, nodes a and b, and edge data d, is a mapping function that is supposed to return either None (to ignore that edge) or a tuple (a2, b2, w) with new nodes a2 and b2, and weight w. 其中具有图g,节点a和b以及边缘数据d的keyfunc(g,a,b,d)是一个映射函数,应该返回None (忽略该边缘)或元组(a2, b2, w)具有新的节点a2和b2,权重w。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM