Python 如何从现有的组件图中获得具有给定边数的随机组件子图?
我想从networkx中现有的组件图中创建一个具有边的组件子图。两个图都是无向的 例如,我希望我的新图形与现有图形相比有100条边,并且是组件。现有的一个有大约200万条边,是一个组件 我目前的做法如下:Python 如何从现有的组件图中获得具有给定边数的随机组件子图?,python,networkx,graph-theory,Python,Networkx,Graph Theory,我想从networkx中现有的组件图中创建一个具有边的组件子图。两个图都是无向的 例如,我希望我的新图形与现有图形相比有100条边,并且是组件。现有的一个有大约200万条边,是一个组件 我目前的做法如下: def get_random_component(number_of_edges): G_def = nx.Graph() G_copy = nx.Graph() G_iter = nx.Graph() G_copy.add_edges_from(G.edges
def get_random_component(number_of_edges):
G_def = nx.Graph()
G_copy = nx.Graph()
G_iter = nx.Graph()
G_copy.add_edges_from(G.edges)
for i in range(number_of_edges):
G_iter.clear()
G_iter.add_edges_from(G_copy.edges)
currently_found_edge = random.choices(list(G_iter.edges), k=1)[0]
while (G_def.has_edge(*currently_found_edge) or (not G_def.has_node(currently_found_edge[0])
and not G_def.has_node(currently_found_edge[1]))):
G_iter.remove_edge(*currently_found_edge)
currently_found_edge = random.choices(list(G_iter.edges), k=1)[0]
G_def.add_edge(*currently_found_edge)
G_copy.remove_edge(*currently_found_edge)
return G_def
但这非常耗时。有没有更好的方法找到具有给定边数的随机分量子图?是的。首先,当您请求算法帮助时,请以易于阅读的形式发布您的算法。代码很好,但只有当您使用有意义的变量名时:
def
、copy
、和iter
才有意义
在while
循环中,您发布的算法经历了很多失败的痛苦,尤其是在给定的情况下,从2e6边的图构建100边组件。除非图形连接紧密,否则每个新边都会旋转很多次
构造一个连通子图,而不是在图中连动。我们称之为SG。另外,假设下面的G
是原始图形的副本,我们可以根据需要进行变异
new_node = a random node of G.
legal_move = new_node.edges() # A set of edges you can traverse from nodes in SG
for _ in range(100):
if legal_move is empty:
# You have found a connected component
# with fewer than 100 edges.
# SG is the closure of that component.
# Break out of this loop, Subtract SG from G, and start over.
new_edge = # a random edge from legal_move (see note below)
subtract SG from legal_move (don't consider any edges already used).
add new_edge to SG
One node of new_edge is already in SG; if the other is not ...
Add other node to SG
Add other.edges to legal_move (except for new_edge)
关于随机选择的说明:
您必须为“随机”定义流程。一个简单的方法是
从legal\u moves
中选择一条随机边。另一种方法是选择
从legal\u移动中选择随机节点,然后选择随机边
从那个节点。你的成长模式会因环境的不同而不同
每个节点的阶数
对于大多数图形,上面的过程会快得多。
由于每个边都引用其两个节点,并且每个节点都维护其边的列表,因此探索和更新阶段将显著加快
编码留给学生作为练习。:-)