diff --git a/docs/src/tutorial.md b/docs/src/tutorial.md index a16d8c0..43b60f4 100644 --- a/docs/src/tutorial.md +++ b/docs/src/tutorial.md @@ -28,6 +28,13 @@ julia> get_weight(g, 1, 2) 0.5 ``` +Or by passing in any `e::AbstractEdge`: + +```jldoctest tuto +julia> get_weight(g, Edge(1, 2)) +0.5 +``` + Find the shortest path from vertex 1 to vertex 3, taking weights into account: ```jldoctest tuto diff --git a/src/abstractsimpleweightedgraph.jl b/src/abstractsimpleweightedgraph.jl index 05b6d32..e645788 100644 --- a/src/abstractsimpleweightedgraph.jl +++ b/src/abstractsimpleweightedgraph.jl @@ -28,10 +28,14 @@ weighttype(::AbstractSimpleWeightedGraph{T,U}) where {T} where {U} = U """ get_weight(g, u, v) + get_weight(g, e) -Retrieve the weight of edge `(u, v)`. +Retrieve the weight of edge `(u, v)` or `e`. """ get_weight(g::AbstractSimpleWeightedGraph, u::Integer, v::Integer) = weights(g)[u, v] +function get_weight(g::AbstractSimpleWeightedGraph, e::AbstractEdge{<:Integer}) + return weights(g)[src(e), dst(e)] +end ## Vertices diff --git a/src/overrides.jl b/src/overrides.jl index 389491e..30b8723 100644 --- a/src/overrides.jl +++ b/src/overrides.jl @@ -194,7 +194,7 @@ function Graphs.induced_subgraph( for e in elist if has_edge(g, e) i, j = index_map[src(e)], index_map[dst(e)] - w = get_weight(g, dst(e), src(e)) + w = get_weight(g, e) push!(I, j) # storage is transposed! push!(J, i) push!(W, w) diff --git a/test/simpleweightedgraph.jl b/test/simpleweightedgraph.jl index adb7ce7..0a02856 100644 --- a/test/simpleweightedgraph.jl +++ b/test/simpleweightedgraph.jl @@ -204,6 +204,9 @@ using SparseArrays @test sum(weights(g)) == 2 * ne(g) * 3 @test @inferred(get_weight(g, 1, 2)) == 3 + @test @inferred(get_weight(g, Edge(1, 2))) == 3 + @test @inferred(get_weight(g, SimpleWeightedEdge(1, 2, 0.5))) == 3 + g = SimpleWeightedDiGraph(path_graph(5), 4.0) @test sum(weights(g)) == ne(g) * 4.0 @@ -294,12 +297,18 @@ using SparseArrays @test g[1, 2, Val{:weight}()] ≈ 5 @test get_weight(g, 1, 2) ≈ 5 + @test get_weight(g, Edge(1, 2)) ≈ 5 + @test get_weight(g, SimpleWeightedEdge(1, 2)) ≈ 5 if is_directed(G) @test g[2, 1, Val{:weight}()] ≈ 0 @test get_weight(g, 2, 1) ≈ 0 + @test get_weight(g, Edge(2, 1)) ≈ 0 + @test get_weight(g, SimpleWeightedEdge(2, 1)) ≈ 0 else @test g[2, 1, Val{:weight}()] ≈ 5 @test get_weight(g, 2, 1) ≈ 5 + @test get_weight(g, Edge(2, 1)) ≈ 5 + @test get_weight(g, SimpleWeightedEdge(2, 1)) ≈ 5 end m = adjacency_matrix(g) @test g[2, 1, Val{:weight}()] ≈ g.weights[1, 2]