github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/spatial/kdtree/nbpoints_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 kdtree 6 7 var ( 8 _ Interface = nbPoints{} 9 _ Comparable = nbPoint{} 10 ) 11 12 // nbRandoms is the maximum number of random values to sample for calculation of median of 13 // random elements. 14 var nbRandoms = 100 15 16 // nbPoint represents a point in a k-d space that satisfies the Comparable interface. 17 type nbPoint Point 18 19 func (p nbPoint) Compare(c Comparable, d Dim) float64 { q := c.(nbPoint); return p[d] - q[d] } 20 func (p nbPoint) Dims() int { return len(p) } 21 func (p nbPoint) Distance(c Comparable) float64 { 22 q := c.(nbPoint) 23 var sum float64 24 for dim, c := range p { 25 d := c - q[dim] 26 sum += d * d 27 } 28 return sum 29 } 30 31 // nbPoints is a collection of point values that satisfies the Interface. 32 type nbPoints []nbPoint 33 34 func (p nbPoints) Index(i int) Comparable { return p[i] } 35 func (p nbPoints) Len() int { return len(p) } 36 func (p nbPoints) Pivot(d Dim) int { return nbPlane{nbPoints: p, Dim: d}.Pivot() } 37 func (p nbPoints) Slice(start, end int) Interface { return p[start:end] } 38 39 // nbPlane is a wrapping type that allows a Points type be pivoted on a dimension. 40 type nbPlane struct { 41 Dim 42 nbPoints 43 } 44 45 func (p nbPlane) Less(i, j int) bool { return p.nbPoints[i][p.Dim] < p.nbPoints[j][p.Dim] } 46 func (p nbPlane) Pivot() int { return Partition(p, MedianOfRandoms(p, nbRandoms)) } 47 func (p nbPlane) Slice(start, end int) SortSlicer { p.nbPoints = p.nbPoints[start:end]; return p } 48 func (p nbPlane) Swap(i, j int) { 49 p.nbPoints[i], p.nbPoints[j] = p.nbPoints[j], p.nbPoints[i] 50 }