Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/overrides.jl
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,28 @@ function induced_subgraph(g::T, vlist::AbstractVector{U}) where T <: AbstractSim
newg.weights = new_weights
return newg, Vector{E}(vlist)
end

function induced_subgraph(g::T, elist::AbstractVector{U}) where T <: AbstractSimpleWeightedGraph where U <: AbstractEdge
allunique(elist) || throw(ArgumentError("Edges in subgraph list must be unique"))
E = eltype(g)
W = edgetype(g)
vertexSet = Set{E}()
for e in elist
if has_edge(g, e)
push!(vertexSet, src(e), dst(e))
else
@warn "Skipping the edge $(e), since it does not exist in the graph!"
end
end
vertexList = collect(vertexSet)
new_weights = g.weights[vertexList, vertexList]

newg = zero(g)
newg.weights = new_weights
for e in edges(newg)
if e ∉ elist
newg.weights[dst(e), src(e)] = 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is not gonna work because the matrix new_weights has new indexing due to the removal of many vertices

Copy link
Contributor Author

@pgrepds pgrepds Mar 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review. I have reimplemented the function and added new tests!

end
end
return newg, Vector{W}(collect(edges(newg)))
end
15 changes: 15 additions & 0 deletions test/simpleweightedgraph.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SimpleWeightedGraphs
using SparseArrays

@testset verbose = true "SimpleWeightedGraphs" begin
@info("Ignore warnings relating to adding and removing vertices and edges")
Expand Down Expand Up @@ -329,4 +330,18 @@ using SimpleWeightedGraphs
@test g[1, 3, Val{:weight}()] ≈ 0
@test g[2, 3, Val{:weight}()] ≈ 0.5
end

# this testset was implemented for https://github.com/JuliaGraphs/SimpleWeightedGraphs.jl/issues/32
@testset "induced_subgraph should preserve weights for edge lists" begin
g = SimpleWeightedGraph([0 2; 2 0])
graphWeights = weights(g)
expectedGraphWeights = sparse([0 2; 2 0])
@test graphWeights == expectedGraphWeights
# vertex induced subgraph
vertexInducedSubgraphWeights = weights(first(induced_subgraph(g, [1, 2])))
@test vertexInducedSubgraphWeights == expectedGraphWeights
# edge induced subgraph
edgeInducedSubgraphWeights = weights(first(induced_subgraph(g, [Edge(1, 2)])))
@test edgeInducedSubgraphWeights == expectedGraphWeights
end
end