From cb021e3a2528e75567df464348e5efcc8cdf301d Mon Sep 17 00:00:00 2001 From: James Shubin Date: Sun, 7 Jan 2024 17:53:31 -0500 Subject: [PATCH] pgraph: Filter graph should preserve vertices without an edge There was a bug in filter graph that caused it to not preserve any vertices that weren't bound to another with an edge. This fixes the bug and adds a test too. --- pgraph/pgraph.go | 6 +++++- pgraph/pgraph_test.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/pgraph/pgraph.go b/pgraph/pgraph.go index d882ca6e..1851667b 100644 --- a/pgraph/pgraph.go +++ b/pgraph/pgraph.go @@ -506,9 +506,13 @@ func (g *Graph) FilterGraph(name string, vertices []Vertex) (*Graph, error) { return nil, errwrap.Wrapf(err, "could not run FilterGraph() properly") } for k1, x := range g.adjacency { + contains := VertexContains(k1, vertices) + if contains { + newGraph.AddVertex(k1) + } for k2, e := range x { //log.Printf("Filter: %s -> %s # %s", k1.Name, k2.Name, e.Name) - if VertexContains(k1, vertices) || VertexContains(k2, vertices) { + if contains || VertexContains(k2, vertices) { newGraph.AddEdge(k1, k2, e) } } diff --git a/pgraph/pgraph_test.go b/pgraph/pgraph_test.go index a8624525..4004eda9 100644 --- a/pgraph/pgraph_test.go +++ b/pgraph/pgraph_test.go @@ -191,6 +191,28 @@ func TestFilterGraph1(t *testing.T) { } } +func TestFilterGraph2(t *testing.T) { + G, _ := NewGraph("g5") + v1 := NV("v1") + v2 := NV("v2") + v3 := NV("v3") + v4 := NV("v4") + e1 := NE("e1") + G.AddEdge(v1, v2, e1) + G.AddVertex(v3) + G.AddVertex(v4) + + save := []Vertex{v1, v2, v3} + out, err := G.FilterGraph("new g5", save) + if err != nil { + t.Errorf("failed with: %v", err) + } + + if c, i := len(save), out.NumVertices(); c != i { + t.Errorf("should have %d vertices instead of: %d", c, i) + } +} + func TestDisconnectedGraphs1(t *testing.T) { G, _ := NewGraph("g6") v1 := NV("v1")