如何将一个不相连的networkx图分成多个相互不相交但相连的图?

2024-04-27

我有一个networkx.Graph代表一个对象graph https://en.wikipedia.org/wiki/Graph_(discrete_mathematics) whose nodes https://en.wikipedia.org/wiki/Vertex_(graph_theory)代表英语单词,其edges https://mathworld.wolfram.com/GraphEdge.html两个 wnode 之间意味着这些节点代表的两个单词至少有一个共享的认知同义词 https://en.wikipedia.org/wiki/Cognitive_synonymy他们之间synsets https://en.wiktionary.org/wiki/synset(即非空路口 https://en.wikipedia.org/wiki/Intersection_(set_theory))。我希望这对某人来说是有趣或有用的背景,但我的问题是与图表相关的更广泛适用的问题,networkx和Python。

Many 诱导子图 https://en.wikipedia.org/wiki/Induced_subgraph该图的(边诱导或顶点诱导)都是边不相交和顶点不相交 https://en.wikipedia.org/wiki/Glossary_of_graph_theory_terms,我想将这些子图分成自己的networkx.Graph对象之间相互联系又相互脱节。有可能我只是使用了错误的搜索词networkx文档,但是。以下是来自图表一小部分的一些示例。

我浏览了 for [networkx] disjoint在 Stack Overflow 上,没有看到我要找的东西。例如,一个结果谈到了当已经有一个边缘集可以从中导出时获取导出的子图 https://stackoverflow.com/questions/35092574/what-is-the-algorithm-to-get-disjoint-set-from-edgelist-with-weights/35094136#35094136. Or 另一篇文章谈到尝试绘制两个不相交的图 https://stackoverflow.com/questions/26691948/drawing-a-graph-partition-with-the-networkx-package-in-python/27158933#27158933,但前提是您已经拥有它们。与我的问题的图论方面相关,但与networkx方面,显然有像洪水填充算法这样的东西可能会解决我的问题的一部分 https://stackoverflow.com/questions/42011513/topologically-sort-directed-graph-into-buckets-for-disjoint-sub-graphs.

现在,作为一个最小的工作示例,让我们创建一个小的随机图,但确保它已断开连接。

import networkx as nx

g = nx.fast_gnp_random_graph(10, 0.3)

while nx.is_connected(g):
    g = nx.fast_gnp_random_graph(10, 0.3)

此时,我们有一个图表g。我想到的是如下所示的内容,其中我占据了相互不相交的图形列表。我不仅需要在循环节点时添加更多图表,还需要随时更新图表。我想也许归纳图的并集可能会起作用,但是nx.disjoint_union_all and nx.union要么通过重新标记来强制图形不相交(我不想要这个),要么期望图形已经不相交。

graphs = []

for node in g.nodes(): # same 'g' we made above
    if graphs:
        pass
    else:
        graphs.append(g.subgraph([i for i in g.neighbors(node)] +\
                                 [node]).copy())

如何将未连接的networkx图分成多个相互不相交的连接图?


您似乎正在寻找连接的组件。
考虑下图。

components = [g.subgraph(c).copy() for c in nx.connected_components(g)]
for idx,g in enumerate(components,start=1):
    print(f"Component {idx}: Nodes: {g.nodes()} Edges: {g.edges()}")

Output:

Component 1: Nodes: [0, 1, 2, 5, 6, 7, 8, 9] Edges: [(0, 2), (0, 6), (1, 2), (1, 5), (1, 7), (1, 8), (2, 5), (5, 7), (6, 8), (7, 9), (8, 9)]
Component 2: Nodes: [3, 4] Edges: [(3, 4)]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将一个不相连的networkx图分成多个相互不相交但相连的图? 的相关文章

随机推荐