kdtree
A k-d tree implementation in Go with:
- n-dimensional points
- k-nearest neighbor search
- range search
- remove without rebuilding the whole subtree
- data attached to the points
- using own structs by implementing a simple 2 function interface
Usage
go get github.com/kyroy/kdtree
import "github.com/kyroy/kdtree"
Implement the kdtree.Point
interface
type Point interface {
Dimensions() int
Dimension(i int) float64
}
points.Point2d
type Data struct {
value string
}
func main() {
tree := kdtree.New([]kdtree.Point{
&points.Point2D{X: 3, Y: 1},
&points.Point2D{X: 5, Y: 0},
&points.Point2D{X: 8, Y: 3},
})
tree.Insert(&points.Point2D{X: 1, Y: 8})
tree.Insert(&points.Point2D{X: 7, Y: 5})
fmt.Println(tree.KNN(&points.Point{Coordinates: []float64{1, 1, 1}}, 2))
fmt.Println(tree.RangeSearch(kdrange.New(1, 8, 0, 2)))
fmt.Println(tree.Points())
fmt.Println(tree.Remove(&points.Point2D{X: 5, Y: 0}))
fmt.Println(tree)
tree.Balance()
fmt.Println(tree)
}
n-dimensional Points (points.Point
)
type Data struct {
value string
}
func main() {
tree := kdtree.New([]kdtree.Point{
points.NewPoint([]float64{7, 2, 3}, Data{value: "first"}),
points.NewPoint([]float64{3, 7, 10}, Data{value: "second"}),
points.NewPoint([]float64{4, 6, 1}, Data{value: "third"}),
})
tree.Insert(points.NewPoint([]float64{12, 4, 6}, Data{value: "fourth"}))
tree.Insert(points.NewPoint([]float64{8, 1, 0}, Data{value: "fifth"}))
fmt.Println(tree.KNN(&points.Point{Coordinates: []float64{1, 1, 1}}, 2))
fmt.Println(tree.RangeSearch(kdrange.New(1, 15, 1, 5, 0, 5)))
fmt.Println(tree.Points())
fmt.Println(tree.Remove(points.NewPoint([]float64{3, 7, 10}, nil)))
fmt.Println(tree)
tree.Balance()
fmt.Println(tree)
}