From bcdc7ea61babe43af5b2c357f8599bd033c70f42 Mon Sep 17 00:00:00 2001 From: Dexter Date: Tue, 16 Mar 2021 23:33:39 +0100 Subject: [PATCH] Kj/induced subgraphs (#4) * Create LabelledGraph package * Add LightGraphs dependency * Implement induced subgraph construction --- src/LabelledGraphs.jl | 7 +++++++ test/runtests.jl | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/LabelledGraphs.jl b/src/LabelledGraphs.jl index b655281..baa9438 100644 --- a/src/LabelledGraphs.jl +++ b/src/LabelledGraphs.jl @@ -217,6 +217,13 @@ module LabelledGraphs has_prop(lg.inner_graph, prop) end + function LightGraphs.induced_subgraph( + lg::LabelledGraph{S, T}, vertices::Vector{T} + ) where {S, T} + sub_ig, _vmap = induced_subgraph(lg.inner_graph, [lg.reverse_label_map[v] for v in vertices]) + LabelledGraph(vertices, sub_ig), vertices + end + # --- Default-type aliases --- LabelledGraph(labels::Vector{T}) where T = LabelledGraph{SimpleGraph}(labels) LabelledDiGraph(labels::Vector{T}) where T = LabelledGraph{SimpleDiGraph}(labels) diff --git a/test/runtests.jl b/test/runtests.jl index f8f39af..3a41079 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -278,3 +278,38 @@ for graph_type ∈ (MetaGraph, MetaDiGraph) @test !has_prop(lg, :title) end end + +for graph_type ∈ (SimpleGraph, SimpleDiGraph, MetaGraph, MetaDiGraph) +@testset "Vertices labels are preserved when constructing induced subgraph of LabelledGraph{$graph_type}" begin + lg = LabelledGraph{graph_type}([10, 20, 40, 50]) + add_edge!(lg, 40, 10) + add_edge!(lg, 50, 10) + add_edge!(lg, 20, 40) + + sub_lg, vmap = induced_subgraph(lg, [10, 20, 40]) + + @test nv(sub_lg) == 3 + @test vertices(sub_lg) == [10, 20, 40] + + @test ne(sub_lg) == 2 + @test has_edge(sub_lg, 20, 40) + @test has_edge(sub_lg, 40, 10) + @test vmap == [10, 20, 40] +end +end + +for graph_type ∈ (MetaGraph, MetaDiGraph) +@testset "Metainformation are correctly preserved when constructing induced subgraph of LabelledGraph{$graph_type}" begin + lg = LabelledGraph{graph_type}([5, 10, 15]) + add_edge!(lg, 5, 10) + + set_prop!(lg, :name, "The Ising model") + set_prop!(lg, 5, :x, 20) + set_prop!(lg, 5, 10, :y, 30) + + sub_ig, vmap = induced_subgraph(lg, [10, 5]) + @test get_prop(sub_ig, :name) == "The Ising model" + @test get_prop(sub_ig, 5, :x) == 20 + @test get_prop(sub_ig, 5, 10, :y) == 30 +end +end