如何解决如何去除 Lightgraphs 中的自循环
我是 Julia 和 LightGraphs 的新手,我一直在努力寻找检测和消除自循环的最有效方法。到目前为止,我发现的唯一方法是遍历 simplegraph 中的所有节点,检查它是否有自循环,然后将其删除。有没有比在 Python NetworkX 中使用这个组合更好的方法:G.remove_edges_from(G.selfloop_edges())
?
我现在的做法:
path = adrs\to\my\edgeList
G = simplegraph(loadgraph(path,GraphIO.EdgeList.EdgeListFormat()))
for node in vertices(G)
if has_edge(G,node,node)
rem_edge!(G,node)
end
end
解决方法
这可能是有条件地执行此操作的最佳方法,但您可以只调用 rem_edge!(G,node,node)
而无需检查 has_edge()
- 它返回一个布尔值,指示是否删除了边缘,因此如果没有,则可以安全使用那里有一个实际的边缘。
您可以使用以下命令找到具有自循环的顶点:
vxs = Iterators.flatten(simplecycles_limited_length(g,1))
要删除它们,只需执行以下操作:
rem_edge!.(Ref(g),vxs,vxs)
,
我在我的解决方案(没有 has_edge()
,感谢@sbromberger!)和@Przemyslaw 提出的解决方案(看起来很整洁!)之间进行了快速基准测试。似乎我的简单方法仍然是最有效的方法,无论是在内存还是时间方面。我很惊讶地看到 simplecycles_limited_length()
比循环更糟糕,考虑到该函数似乎是为了这个特定目的。如果你知道这是为什么,请告诉我。
这是我的基准测试结果(my_graph 有 22,470 个节点和 170,823 条边以及 179 个自循环):
using BenchmarkTools
function sl1(G)
for node in vertices(G)
rem_edge!(G,node)
end
end
function sl2(G)
vxs = Iterators.flatten(simplecycles_limited_length(G,1))
rem_edge!.(Ref(G),vxs)
end
@benchmark sl1(my_graph)
>>> BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 554.401 μs (0.00% GC)
median time: 582.899 μs (0.00% GC)
mean time: 592.032 μs (0.00% GC)
maximum time: 1.292 ms (0.00% GC)
--------------
samples: 8440
evals/sample: 1
@benchmark sl1($my_graph)
>>> BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 555.500 μs (0.00% GC)
median time: 603.501 μs (0.00% GC)
mean time: 616.309 μs (0.00% GC)
maximum time: 1.281 ms (0.00% GC)
--------------
samples: 8108
evals/sample: 1
@benchmark sl2(my_graph)
>>> BenchmarkTools.Trial:
memory estimate: 448 bytes
allocs estimate: 6
--------------
minimum time: 792.400 μs (0.00% GC)
median time: 836.000 μs (0.00% GC)
mean time: 855.634 μs (0.00% GC)
maximum time: 1.836 ms (0.00% GC)
--------------
samples: 5839
evals/sample: 1
@benchmark sl2($my_graph)
>>> BenchmarkTools.Trial:
memory estimate: 448 bytes
allocs estimate: 6
--------------
minimum time: 795.600 μs (0.00% GC)
median time: 853.250 μs (0.00% GC)
mean time: 889.450 μs (0.00% GC)
maximum time: 2.022 ms (0.00% GC)
--------------
samples: 5618
evals/sample: 1
@btime sl1(my_graph)
>>> 555.999 μs (0 allocations: 0 bytes)
@btime sl1($my_graph)
>>> 564.000 μs (0 allocations: 0 bytes)
@btime sl2(my_graph)
>>> 781.800 μs (6 allocations: 448 bytes)
@btime sl2($my_graph)
>>> 802.200 μs (6 allocations: 448 bytes)
编辑:根据要求添加了内插基准。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。