github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/stat/distmat/permutation_test.go (about) 1 // Copyright ©2020 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 distmat 6 7 import ( 8 "testing" 9 10 "golang.org/x/exp/rand" 11 12 "github.com/jingcheng-WU/gonum/mat" 13 ) 14 15 func TestUniformPermutation(t *testing.T) { 16 up := NewUniformPermutation(rand.NewSource(1)) 17 for _, n := range []int{10, 32, 64, 100} { 18 m := mat.NewDense(n, n, nil) 19 up.PermTo(m) 20 // Test that each row and column satisfies the permutation matrix 21 // invariant that all rows and columns have a single unit element 22 // and the remaining elements are zero. 23 for i := 0; i < n; i++ { 24 checkHasSingleUnitElement(t, "row", i, mat.Row(nil, i, m)) 25 checkHasSingleUnitElement(t, "col", i, mat.Col(nil, i, m)) 26 } 27 } 28 } 29 30 func checkHasSingleUnitElement(t *testing.T, dir string, n int, v []float64) { 31 t.Helper() 32 var sum float64 33 for i, x := range v { 34 switch x { 35 case 0, 1: 36 sum += x 37 default: 38 t.Errorf("unexpected value in %s %d position %d: %v", dir, n, i, v) 39 } 40 } 41 if sum != 1 { 42 t.Errorf("%s %d is not a valid vector: %v", dir, n, v) 43 } 44 }