Skip to content

Commit 86feac3

Browse files
committed
add induced_subgraph function for creating induced subgraph from edge list
1 parent 8fc9557 commit 86feac3

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/overrides.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,28 @@ function induced_subgraph(g::T, vlist::AbstractVector{U}) where T <: AbstractSim
144144
newg.weights = new_weights
145145
return newg, Vector{E}(vlist)
146146
end
147+
148+
function induced_subgraph(g::T, elist::AbstractVector{U}) where T <: AbstractSimpleWeightedGraph where U <: AbstractEdge
149+
allunique(elist) || throw(ArgumentError("Edges in subgraph list must be unique"))
150+
E = eltype(g)
151+
W = edgetype(g)
152+
vertexSet = Set{E}()
153+
for e in elist
154+
if has_edge(g, e)
155+
push!(vertexSet, src(e), dst(e))
156+
else
157+
@warn "Skipping the edge $(e), since it does not exist in the graph!"
158+
end
159+
end
160+
vertexList = collect(vertexSet)
161+
new_weights = g.weights[vertexList, vertexList]
162+
163+
newg = zero(g)
164+
newg.weights = new_weights
165+
for e in edges(newg)
166+
if e elist
167+
newg.weights[dst(e), src(e)] = 0
168+
end
169+
end
170+
return newg, Vector{W}(collect(edges(newg)))
171+
end

test/simpleweightedgraph.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using SimpleWeightedGraphs
2+
using SparseArrays
23

34
@testset verbose = true "SimpleWeightedGraphs" begin
45
@info("Ignore warnings relating to adding and removing vertices and edges")
@@ -329,4 +330,18 @@ using SimpleWeightedGraphs
329330
@test g[1, 3, Val{:weight}()] 0
330331
@test g[2, 3, Val{:weight}()] 0.5
331332
end
333+
334+
# this testset was implemented for https://github.com/JuliaGraphs/SimpleWeightedGraphs.jl/issues/32
335+
@testset "induced_subgraph should preserve weights for edge lists" begin
336+
g = SimpleWeightedGraph([0 2; 2 0])
337+
graphWeights = weights(g)
338+
expectedGraphWeights = sparse([0 2; 2 0])
339+
@test graphWeights == expectedGraphWeights
340+
# vertex induced subgraph
341+
vertexInducedSubgraphWeights = weights(first(induced_subgraph(g, [1, 2])))
342+
@test vertexInducedSubgraphWeights == expectedGraphWeights
343+
# edge induced subgraph
344+
edgeInducedSubgraphWeights = weights(first(induced_subgraph(g, [Edge(1, 2)])))
345+
@test edgeInducedSubgraphWeights == expectedGraphWeights
346+
end
332347
end

0 commit comments

Comments
 (0)