如何在LightGraphs(Julia)中为图形添加自由边?

时间:2018-02-25 18:42:19

标签: graph julia edge lightgraphs

我在 Julia 中添加了一个简单的加权有向图(来自 SimpleWeightedDiGraph(),它是 LightGraphs 包的一部分)。一些弧线是“自由的”(零重量)。但是,当指定权重0时,它不会作为新边添加,并且最短路径问题不会在可能的解决方案中包含它。有没有一种简单的方法可以在Julia中为图形添加“自由”边/弧?

2 个答案:

答案 0 :(得分:3)

关键问题是如何在稀疏矩阵(它是SELECT ST.type, COALESCE(SUM(TR.total_amount), 0) AS amount FROM sms_admin_status ST LEFT JOIN transaction_transaction TR ON TR.status = ST.type WHERE TR.store_id = 21 AND TR.transaction_type = 'Layaway' AND TR.status != 'Void' AND TR.date_made >= '2018-02-01' AND TR.date_made <= '2018-02-26' GROUP BY ST.type 的基础数据存储中表示零值。虽然确实在显式设置后保留了基础零值:

SimpleWeightedGraph

如果您必须对边缘做任何事情,这将失败:

julia> g = SimpleWeightedGraph(6)
{6, 0} undirected simple Int64 graph with Float64 weights

julia> add_edge!(g, 1, 2, 1.0)
true

julia> add_edge!(g, 1, 3, 1.0)
true

julia> add_edge!(g, 1, 3, 0.0)
true

julia> weights(g)
6×6 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
  [2, 1]  =  1.0
  [3, 1]  =  0.0
  [1, 2]  =  1.0
  [1, 3]  =  0.0

对此没有很好的解决方案。我的建议是使用如上所述的足够小的重量来近似零值。

(PS:初始julia> collect(edges(g)) 1-element Array{SimpleWeightedGraphs.SimpleWeightedEdge{Int64,Float64},1}: Edge 1 => 2 with weight 1.0 不起作用的原因是因为在Julia中,将新的sparsematrix元素的值设置为零是无操作。)

答案 1 :(得分:0)

SimpleWeightedGraphs README example的这种修改对我有用:

using LightGraphs, SimpleWeightedGraphs

# set the size of the graph
g = SimpleWeightedDiGraph(3) 

add_edge!(g, 1, 2, 0.5)
add_edge!(g, 2, 3, 0.8)
add_edge!(g, 1, 3, 2.0)

# find the shortest path from vertex 1 to vertex 3 taking weights into account.
enumerate_paths(dijkstra_shortest_paths(g, 1), 3) # gives [1,2,3]

# reweight the edge from 1 to 3 to be "free"
add_edge!(g, 1, 3, 0.0)

enumerate_paths(dijkstra_shortest_paths(g, 1), 3) # gives [1,3]

请注意,顶点必须位于图表中(根据其大小)才能设置其权重,如文档中所述:?add_edge!