Skip to content

Commit

Permalink
get_weight with AbstractEdge (#46)
Browse files Browse the repository at this point in the history
Quick PR to allow `get_weight` to be called with any `AbstractEdge`
using the Interface defined in `Graphs`. This fixes my issue #45.
(assuming it is an issue and not a conscious design decision.)
  • Loading branch information
henrik-wolf authored Jul 2, 2023
1 parent a8da15d commit 8128430
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
7 changes: 7 additions & 0 deletions docs/src/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion src/abstractsimpleweightedgraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/overrides.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions test/simpleweightedgraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 8128430

Please sign in to comment.