gonum.org/v1/gonum@v0.14.0/graph/complement_test.go (about) 1 // Copyright ©2019 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package graph_test 6 7 import ( 8 "fmt" 9 "testing" 10 11 "golang.org/x/exp/rand" 12 13 "gonum.org/v1/gonum/graph" 14 "gonum.org/v1/gonum/graph/graphs/gen" 15 "gonum.org/v1/gonum/graph/iterator" 16 "gonum.org/v1/gonum/graph/simple" 17 ) 18 19 var complementTests = []struct { 20 g graph.Graph 21 }{ 22 {g: gnp(100, 0, rand.NewSource(1))}, 23 {g: gnp(100, 0.05, rand.NewSource(1))}, 24 {g: gnp(100, 0.5, rand.NewSource(1))}, 25 {g: gnp(100, 0.95, rand.NewSource(1))}, 26 {g: gnp(100, 1, rand.NewSource(1))}, 27 } 28 29 func TestComplement(t *testing.T) { 30 for _, test := range complementTests { 31 n := len(graph.NodesOf(test.g.Nodes())) 32 wantM := n * (n - 1) // Double counting edges, but no self-loops. 33 34 var gotM int 35 iter := test.g.Nodes() 36 for iter.Next() { 37 id := iter.Node().ID() 38 to := test.g.From(id) 39 for to.Next() { 40 gotM++ 41 } 42 toC := graph.Complement{test.g}.From(id) 43 for toC.Next() { 44 gotM++ 45 } 46 } 47 if gotM != wantM { 48 t.Errorf("unexpected number of edges in sum of input and complement: got:%d want:%d", gotM, wantM) 49 } 50 } 51 } 52 53 func gnp(n int, p float64, src rand.Source) *simple.UndirectedGraph { 54 g := simple.NewUndirectedGraph() 55 err := gen.Gnp(g, n, p, src) 56 if err != nil { 57 panic(fmt.Sprintf("gnp: bad test: %v", err)) 58 } 59 return g 60 } 61 62 var nodeFilterIteratorTests = []struct { 63 src, filter graph.Nodes 64 root int64 65 len int 66 }{ 67 {src: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), filter: graph.Empty, root: 0, len: 0}, 68 {src: iterator.NewOrderedNodes([]graph.Node{simple.Node(0), simple.Node(1)}), filter: graph.Empty, root: 0, len: 1}, 69 {src: iterator.NewOrderedNodes([]graph.Node{simple.Node(0), simple.Node(1), simple.Node(2)}), filter: iterator.NewOrderedNodes([]graph.Node{simple.Node(1)}), root: 0, len: 1}, 70 } 71 72 func TestNodeFilterIterator(t *testing.T) { 73 for _, test := range nodeFilterIteratorTests { 74 it := graph.NewNodeFilterIterator(test.src, test.filter, test.root) 75 if it.Len() < 0 { 76 t.Logf("don't test indeterminate iterators: %T", it) 77 continue 78 } 79 for i := 0; i < 2; i++ { 80 n := it.Len() 81 if n != test.len { 82 t.Errorf("unexpected length of iterator construction/reset: got:%d want:%d", n, test.len) 83 } 84 for it.Next() { 85 n-- 86 } 87 if n != 0 { 88 t.Errorf("unexpected remaining nodes after iterator completion: got:%d want:0", n) 89 } 90 it.Reset() 91 } 92 } 93 }