├── .gitignore ├── go.mod ├── .travis.yml ├── points ├── point2d.go ├── point3d.go ├── point.go ├── point2d_test.go ├── point3d_test.go └── point_test.go ├── kdrange ├── range.go └── range_test.go ├── go.sum ├── README.md ├── kdtree.go ├── LICENSE └── kdtree_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ project files 2 | .idea 3 | *.iml 4 | out 5 | gen 6 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/kyroy/kdtree 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/jupp0r/go-priority-queue v0.0.0-20160601094913-ab1073853bde 7 | github.com/kyroy/priority-queue v0.0.0-20180327160706-6e21825e7e0c 8 | github.com/stretchr/testify v1.4.0 9 | ) 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - "1.14.x" 5 | - "1.13.x" 6 | - master 7 | 8 | env: 9 | - GO111MODULE=on 10 | 11 | script: 12 | - go test -v -coverprofile=coverage.txt -covermode=atomic ./... 13 | 14 | after_success: 15 | - bash <(curl -s https://codecov.io/bash) 16 | -------------------------------------------------------------------------------- /points/point2d.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package points 18 | 19 | import "fmt" 20 | 21 | // Point2D ... 22 | type Point2D struct { 23 | X float64 24 | Y float64 25 | } 26 | 27 | // Dimensions ... 28 | func (p *Point2D) Dimensions() int { 29 | return 2 30 | } 31 | 32 | // Dimension ... 33 | func (p *Point2D) Dimension(i int) float64 { 34 | if i == 0 { 35 | return p.X 36 | } 37 | return p.Y 38 | } 39 | 40 | // String ... 41 | func (p *Point2D) String() string { 42 | return fmt.Sprintf("{%.2f %.2f}", p.X, p.Y) 43 | } 44 | -------------------------------------------------------------------------------- /points/point3d.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package points 18 | 19 | import "fmt" 20 | 21 | // Point3D ... 22 | type Point3D struct { 23 | X float64 24 | Y float64 25 | Z float64 26 | } 27 | 28 | // Dimensions ... 29 | func (p *Point3D) Dimensions() int { 30 | return 3 31 | } 32 | 33 | // Dimension ... 34 | func (p *Point3D) Dimension(i int) float64 { 35 | switch i { 36 | case 0: 37 | return p.X 38 | case 1: 39 | return p.Y 40 | default: 41 | return p.Z 42 | } 43 | } 44 | 45 | // String ... 46 | func (p *Point3D) String() string { 47 | return fmt.Sprintf("{%.2f %.2f %.2f}", p.X, p.Y, p.Z) 48 | } 49 | -------------------------------------------------------------------------------- /kdrange/range.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Package kdrange contains k-dimensional range struct and helpers. 18 | package kdrange 19 | 20 | // Range represents a range in k-dimensional space. 21 | type Range [][2]float64 22 | 23 | // New creates a new Range. 24 | // 25 | // It accepts a sequence of min/max pairs that define the Range. 26 | // For example a 2-dimensional rectangle with the with 2 and height 3, starting at (1,2): 27 | // 28 | // r := NewRange(1, 3, 2, 5) 29 | // 30 | // I.e.: 31 | // x (dim 0): 1 <= x <= 3 32 | // y (dim 1): 2 <= y <= 5 33 | func New(limits ...float64) Range { 34 | if limits == nil || len(limits)%2 != 0 { 35 | return nil 36 | } 37 | r := make([][2]float64, len(limits)/2) 38 | for i := range r { 39 | r[i] = [2]float64{limits[2*i], limits[2*i+1]} 40 | } 41 | return r 42 | } 43 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/jupp0r/go-priority-queue v0.0.0-20160601094913-ab1073853bde h1:+5PMaaQtDUwOcJIUlmX89P0J3iwTvErTmyn5WghzXAQ= 4 | github.com/jupp0r/go-priority-queue v0.0.0-20160601094913-ab1073853bde/go.mod h1:RDgD/dfPmIwFH0qdUOjw71HjtWg56CtyLIoHL+R1wJw= 5 | github.com/kyroy/priority-queue v0.0.0-20180327160706-6e21825e7e0c h1:1c7+XOOGQ19cXjZ1Ss/irljQxgPvb+8z+jNEprCXl20= 6 | github.com/kyroy/priority-queue v0.0.0-20180327160706-6e21825e7e0c/go.mod h1:R477L6j2/dUcE0q0aftk0kR5Xt93W7g1066AodcJhEo= 7 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 8 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 9 | github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= 10 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 11 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 12 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 14 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 15 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 16 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 17 | -------------------------------------------------------------------------------- /points/point.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Package points contains multiple example implementations of the kdtree.Point interface. 18 | package points 19 | 20 | import "fmt" 21 | 22 | // Point represents a n-dimensional point of the k-d tree. 23 | type Point struct { 24 | Coordinates []float64 25 | Data interface{} 26 | } 27 | 28 | // NewPoint creates a new point at the given coordinates and contains the given data. 29 | func NewPoint(coordinates []float64, data interface{}) *Point { 30 | return &Point{ 31 | Coordinates: coordinates, 32 | Data: data, 33 | } 34 | } 35 | 36 | // Dimensions returns the total number of dimensions. 37 | func (p *Point) Dimensions() int { 38 | return len(p.Coordinates) 39 | } 40 | 41 | // Dimension returns the value of the i-th dimension. 42 | func (p *Point) Dimension(i int) float64 { 43 | return p.Coordinates[i] 44 | } 45 | 46 | // String returns the string representation of the point. 47 | func (p *Point) String() string { 48 | return fmt.Sprintf("{%v %v}", p.Coordinates, p.Data) 49 | } 50 | -------------------------------------------------------------------------------- /kdrange/range_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package kdrange_test 18 | 19 | import ( 20 | "github.com/kyroy/kdtree/kdrange" 21 | "github.com/stretchr/testify/assert" 22 | "testing" 23 | ) 24 | 25 | func TestNewRange(t *testing.T) { 26 | tests := []struct { 27 | name string 28 | input []float64 29 | output kdrange.Range 30 | }{ 31 | { 32 | name: "nil", 33 | input: nil, 34 | output: nil, 35 | }, 36 | { 37 | name: "uneven", 38 | input: []float64{0}, 39 | output: nil, 40 | }, 41 | { 42 | name: "empty", 43 | input: []float64{}, 44 | output: [][2]float64{}, 45 | }, 46 | { 47 | name: "2d", 48 | input: []float64{1, 2, 3, 4}, 49 | output: [][2]float64{{1, 2}, {3, 4}}, 50 | }, 51 | { 52 | name: "3d", 53 | input: []float64{4, 1, 6, 19, 3, 1}, 54 | output: [][2]float64{{4, 1}, {6, 19}, {3, 1}}, 55 | }, 56 | } 57 | for _, test := range tests { 58 | t.Run(test.name, func(t *testing.T) { 59 | assert.Equal(t, test.output, kdrange.New(test.input...)) 60 | }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /points/point2d_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package points_test 18 | 19 | import ( 20 | "github.com/kyroy/kdtree/points" 21 | "github.com/stretchr/testify/assert" 22 | "testing" 23 | ) 24 | 25 | func TestPoint2D_Dimensions(t *testing.T) { 26 | assert.Equal(t, (&points.Point2D{}).Dimensions(), 2) 27 | } 28 | 29 | func TestPoint2D_TestDimension(t *testing.T) { 30 | tests := []struct { 31 | name string 32 | point points.Point2D 33 | }{ 34 | {name: "empty", point: points.Point2D{}}, 35 | {name: "X", point: points.Point2D{X: 2}}, 36 | {name: "Y", point: points.Point2D{Y: 3}}, 37 | {name: "XY", point: points.Point2D{X: 2, Y: 3}}, 38 | } 39 | for _, test := range tests { 40 | t.Run(test.name, func(t *testing.T) { 41 | assert.Equal(t, test.point.Dimension(0), test.point.X) 42 | assert.Equal(t, test.point.Dimension(1), test.point.Y) 43 | }) 44 | } 45 | } 46 | 47 | func TestPoint2D_String(t *testing.T) { 48 | tests := []struct { 49 | name string 50 | point points.Point2D 51 | expected string 52 | }{ 53 | {name: "empty", point: points.Point2D{}, expected: "{0.00 0.00}"}, 54 | {name: "X", point: points.Point2D{X: 2}, expected: "{2.00 0.00}"}, 55 | {name: "Y", point: points.Point2D{Y: 3}, expected: "{0.00 3.00}"}, 56 | {name: "XY", point: points.Point2D{X: 2, Y: 3}, expected: "{2.00 3.00}"}, 57 | } 58 | for _, test := range tests { 59 | t.Run(test.name, func(t *testing.T) { 60 | assert.Equal(t, test.point.String(), test.expected) 61 | }) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /points/point3d_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package points_test 18 | 19 | import ( 20 | "github.com/kyroy/kdtree/points" 21 | "github.com/stretchr/testify/assert" 22 | "testing" 23 | ) 24 | 25 | func TestPoint3D_Dimensions(t *testing.T) { 26 | assert.Equal(t, (&points.Point3D{}).Dimensions(), 3) 27 | } 28 | 29 | func TestPoint3D_TestDimension(t *testing.T) { 30 | tests := []struct { 31 | name string 32 | point points.Point3D 33 | }{ 34 | {name: "empty", point: points.Point3D{}}, 35 | {name: "X", point: points.Point3D{X: 2}}, 36 | {name: "Y", point: points.Point3D{Y: 3}}, 37 | {name: "Z", point: points.Point3D{Y: 4}}, 38 | {name: "XYZ", point: points.Point3D{X: 2, Y: 3, Z: 4}}, 39 | } 40 | for _, test := range tests { 41 | t.Run(test.name, func(t *testing.T) { 42 | assert.Equal(t, test.point.Dimension(0), test.point.X) 43 | assert.Equal(t, test.point.Dimension(1), test.point.Y) 44 | assert.Equal(t, test.point.Dimension(2), test.point.Z) 45 | }) 46 | } 47 | } 48 | 49 | func TestPoint3D_String(t *testing.T) { 50 | tests := []struct { 51 | name string 52 | point points.Point3D 53 | expected string 54 | }{ 55 | {name: "empty", point: points.Point3D{}, expected: "{0.00 0.00 0.00}"}, 56 | {name: "X", point: points.Point3D{X: 2}, expected: "{2.00 0.00 0.00}"}, 57 | {name: "Y", point: points.Point3D{Y: 3}, expected: "{0.00 3.00 0.00}"}, 58 | {name: "Z", point: points.Point3D{Z: 4}, expected: "{0.00 0.00 4.00}"}, 59 | {name: "XY", point: points.Point3D{X: 2, Y: 3, Z: 4}, expected: "{2.00 3.00 4.00}"}, 60 | } 61 | for _, test := range tests { 62 | t.Run(test.name, func(t *testing.T) { 63 | assert.Equal(t, test.point.String(), test.expected) 64 | }) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /points/point_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package points_test 18 | 19 | import ( 20 | "github.com/kyroy/kdtree/points" 21 | "github.com/stretchr/testify/assert" 22 | "testing" 23 | ) 24 | 25 | func TestNewPoint(t *testing.T) { 26 | tests := []struct { 27 | name string 28 | coordinates []float64 29 | data interface{} 30 | }{ 31 | {name: "nil nil", coordinates: nil, data: nil}, 32 | } 33 | for _, test := range tests { 34 | t.Run(test.name, func(t *testing.T) { 35 | p := points.NewPoint(test.coordinates, test.data) 36 | assert.Equal(t, test.coordinates, p.Coordinates) 37 | assert.Equal(t, test.data, p.Data) 38 | assert.Equal(t, len(test.coordinates), p.Dimensions()) 39 | for i, v := range test.coordinates { 40 | assert.Equal(t, v, p.Dimension(i)) 41 | } 42 | }) 43 | } 44 | } 45 | 46 | func TestPoint_Dimensions(t *testing.T) { 47 | tests := []struct { 48 | name string 49 | input []float64 50 | }{ 51 | {name: "empty", input: []float64{}}, 52 | {name: "1", input: []float64{1}}, 53 | {name: "2", input: []float64{2.34, 42.}}, 54 | {name: "6", input: []float64{2.34, 42., 2.7, -1.2, 4.3, -0.2}}, 55 | } 56 | for _, test := range tests { 57 | t.Run(test.name, func(t *testing.T) { 58 | p := points.Point{Coordinates: test.input} 59 | assert.Equal(t, p.Dimensions(), len(test.input)) 60 | }) 61 | } 62 | } 63 | 64 | func TestPoint_Dimension(t *testing.T) { 65 | tests := []struct { 66 | name string 67 | input []float64 68 | }{ 69 | {name: "empty", input: []float64{}}, 70 | {name: "1", input: []float64{1}}, 71 | {name: "2", input: []float64{2.34, 42.}}, 72 | {name: "6", input: []float64{2.34, 42., 2.7, -1.2, 4.3, -0.2}}, 73 | } 74 | for _, test := range tests { 75 | t.Run(test.name, func(t *testing.T) { 76 | p := points.Point{Coordinates: test.input} 77 | for i, itm := range test.input { 78 | assert.Equal(t, p.Dimension(i), itm) 79 | } 80 | }) 81 | } 82 | } 83 | 84 | func TestPoint_String(t *testing.T) { 85 | tests := []struct { 86 | name string 87 | point points.Point 88 | expected string 89 | }{ 90 | {name: "empty", point: points.Point{}, expected: "{[] }"}, 91 | {name: "string data", point: points.Point{Coordinates: []float64{1, 2}, Data: "testme"}, expected: "{[1 2] testme}"}, 92 | {name: "float data", point: points.Point{Coordinates: []float64{1, 2}, Data: 4.3}, expected: "{[1 2] 4.3}"}, 93 | {name: "int data", point: points.Point{Coordinates: []float64{1, 2}, Data: 42}, expected: "{[1 2] 42}"}, 94 | { 95 | name: "struct data", 96 | point: points.Point{ 97 | Coordinates: []float64{1, 2}, 98 | Data: struct { 99 | A int 100 | B string 101 | }{ 102 | A: 4, 103 | B: "teststruct", 104 | }, 105 | }, 106 | expected: "{[1 2] {4 teststruct}}"}, 107 | } 108 | for _, test := range tests { 109 | t.Run(test.name, func(t *testing.T) { 110 | assert.Equal(t, test.point.String(), test.expected) 111 | }) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kdtree 2 | 3 | [![GoDoc](https://godoc.org/github.com/kyroy/kdtree?status.svg)](https://godoc.org/github.com/kyroy/kdtree) 4 | [![Build Status](https://travis-ci.org/kyroy/kdtree.svg?branch=master)](https://travis-ci.org/kyroy/kdtree) 5 | [![Codecov](https://img.shields.io/codecov/c/github/kyroy/kdtree.svg)](https://codecov.io/gh/kyroy/kdtree) 6 | [![Go Report Card](https://goreportcard.com/badge/github.com/kyroy/kdtree)](https://goreportcard.com/report/github.com/kyroy/kdtree) 7 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/kyroy/kdtree/blob/master/LICENSE) 8 | 9 | A [k-d tree](https://en.wikipedia.org/wiki/K-d_tree) implementation in Go with: 10 | - n-dimensional points 11 | - k-nearest neighbor search 12 | - range search 13 | - remove without rebuilding the whole subtree 14 | - data attached to the points 15 | - using own structs by implementing a simple 2 function interface 16 | 17 | 18 | ## Usage 19 | 20 | ```bash 21 | go get github.com/kyroy/kdtree 22 | ``` 23 | 24 | ```go 25 | import "github.com/kyroy/kdtree" 26 | ```` 27 | 28 | 29 | ### Implement the `kdtree.Point` interface 30 | 31 | ```go 32 | // Point specifies one element of the k-d tree. 33 | type Point interface { 34 | // Dimensions returns the total number of dimensions 35 | Dimensions() int 36 | // Dimension returns the value of the i-th dimension 37 | Dimension(i int) float64 38 | } 39 | ``` 40 | 41 | 42 | ### `points.Point2d` 43 | 44 | ```go 45 | type Data struct { 46 | value string 47 | } 48 | 49 | func main() { 50 | tree := kdtree.New([]kdtree.Point{ 51 | &points.Point2D{X: 3, Y: 1}, 52 | &points.Point2D{X: 5, Y: 0}, 53 | &points.Point2D{X: 8, Y: 3}, 54 | }) 55 | 56 | // Insert 57 | tree.Insert(&points.Point2D{X: 1, Y: 8}) 58 | tree.Insert(&points.Point2D{X: 7, Y: 5}) 59 | 60 | // KNN (k-nearest neighbor) 61 | fmt.Println(tree.KNN(&points.Point{Coordinates: []float64{1, 1, 1}}, 2)) 62 | // [{3.00 1.00} {5.00 0.00}] 63 | 64 | // RangeSearch 65 | fmt.Println(tree.RangeSearch(kdrange.New(1, 8, 0, 2))) 66 | // [{5.00 0.00} {3.00 1.00}] 67 | 68 | // Points 69 | fmt.Println(tree.Points()) 70 | // [{3.00 1.00} {1.00 8.00} {5.00 0.00} {8.00 3.00} {7.00 5.00}] 71 | 72 | // Remove 73 | fmt.Println(tree.Remove(&points.Point2D{X: 5, Y: 0})) 74 | // {5.00 0.00} 75 | 76 | // String 77 | fmt.Println(tree) 78 | // [[{1.00 8.00} {3.00 1.00} [ {8.00 3.00} {7.00 5.00}]]] 79 | 80 | // Balance 81 | tree.Balance() 82 | fmt.Println(tree) 83 | // [[[{3.00 1.00} {1.00 8.00} ] {7.00 5.00} {8.00 3.00}]] 84 | } 85 | ``` 86 | 87 | ### n-dimensional Points (`points.Point`) 88 | ```go 89 | type Data struct { 90 | value string 91 | } 92 | 93 | func main() { 94 | tree := kdtree.New([]kdtree.Point{ 95 | points.NewPoint([]float64{7, 2, 3}, Data{value: "first"}), 96 | points.NewPoint([]float64{3, 7, 10}, Data{value: "second"}), 97 | points.NewPoint([]float64{4, 6, 1}, Data{value: "third"}), 98 | }) 99 | 100 | // Insert 101 | tree.Insert(points.NewPoint([]float64{12, 4, 6}, Data{value: "fourth"})) 102 | tree.Insert(points.NewPoint([]float64{8, 1, 0}, Data{value: "fifth"})) 103 | 104 | // KNN (k-nearest neighbor) 105 | fmt.Println(tree.KNN(&points.Point{Coordinates: []float64{1, 1, 1}}, 2)) 106 | // [{[4 6 1] {third}} {[7 2 3] {first}}] 107 | 108 | // RangeSearch 109 | fmt.Println(tree.RangeSearch(kdrange.New(1, 15, 1, 5, 0, 5))) 110 | // [{[7 2 3] {first}} {[8 1 0] {fifth}}] 111 | 112 | // Points 113 | fmt.Println(tree.Points()) 114 | // [{[3 7 10] {second}} {[4 6 1] {third}} {[8 1 0] {fifth}} {[7 2 3] {first}} {[12 4 6] {fourth}}] 115 | 116 | // Remove 117 | fmt.Println(tree.Remove(points.NewPoint([]float64{3, 7, 10}, nil))) 118 | // {[3 7 10] {second}} 119 | 120 | // String 121 | fmt.Println(tree) 122 | // [[ {[4 6 1] {third}} [{[8 1 0] {fifth}} {[7 2 3] {first}} {[12 4 6] {fourth}}]]] 123 | 124 | // Balance 125 | tree.Balance() 126 | fmt.Println(tree) 127 | // [[[{[7 2 3] {first}} {[4 6 1] {third}} ] {[8 1 0] {fifth}} {[12 4 6] {fourth}}]] 128 | } 129 | ``` 130 | -------------------------------------------------------------------------------- /kdtree.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Package kdtree implements a k-d tree data structure. 18 | package kdtree 19 | 20 | import ( 21 | "fmt" 22 | "github.com/kyroy/kdtree/kdrange" 23 | "github.com/kyroy/priority-queue" 24 | "math" 25 | "sort" 26 | ) 27 | 28 | // Point specifies one element of the k-d tree. 29 | type Point interface { 30 | // Dimensions returns the total number of dimensions. 31 | Dimensions() int 32 | // Dimension returns the value of the i-th dimension. 33 | Dimension(i int) float64 34 | } 35 | 36 | // KDTree represents the k-d tree. 37 | type KDTree struct { 38 | root *node 39 | } 40 | 41 | // New returns a balanced k-d tree. 42 | func New(points []Point) *KDTree { 43 | return &KDTree{ 44 | root: newKDTree(points, 0), 45 | } 46 | } 47 | 48 | func newKDTree(points []Point, axis int) *node { 49 | if len(points) == 0 { 50 | return nil 51 | } 52 | if len(points) == 1 { 53 | return &node{Point: points[0]} 54 | } 55 | 56 | sort.Sort(&byDimension{dimension: axis, points: points}) 57 | mid := len(points) / 2 58 | root := points[mid] 59 | nextDim := (axis + 1) % root.Dimensions() 60 | return &node{ 61 | Point: root, 62 | Left: newKDTree(points[:mid], nextDim), 63 | Right: newKDTree(points[mid+1:], nextDim), 64 | } 65 | } 66 | 67 | // String returns a string representation of the k-d tree. 68 | func (t *KDTree) String() string { 69 | return fmt.Sprintf("[%s]", printTreeNode(t.root)) 70 | } 71 | 72 | func printTreeNode(n *node) string { 73 | if n != nil && (n.Left != nil || n.Right != nil) { 74 | return fmt.Sprintf("[%s %s %s]", printTreeNode(n.Left), n.String(), printTreeNode(n.Right)) 75 | } 76 | return fmt.Sprintf("%s", n) 77 | } 78 | 79 | // Insert adds a point to the k-d tree. 80 | func (t *KDTree) Insert(p Point) { 81 | if t.root == nil { 82 | t.root = &node{Point: p} 83 | } else { 84 | t.root.Insert(p, 0) 85 | } 86 | } 87 | 88 | // Remove removes and returns the first point from the tree that equals the given point p in all dimensions. 89 | // Returns nil if not found. 90 | func (t *KDTree) Remove(p Point) Point { 91 | if t.root == nil || p == nil { 92 | return nil 93 | } 94 | n, sub := t.root.Remove(p, 0) 95 | if n == t.root { 96 | t.root = sub 97 | } 98 | if n == nil { 99 | return nil 100 | } 101 | return n.Point 102 | } 103 | 104 | // Balance rebalances the k-d tree by recreating it. 105 | func (t *KDTree) Balance() { 106 | t.root = newKDTree(t.Points(), 0) 107 | } 108 | 109 | // Points returns all points in the k-d tree. 110 | // The tree is traversed in-order. 111 | func (t *KDTree) Points() []Point { 112 | if t.root == nil { 113 | return []Point{} 114 | } 115 | return t.root.Points() 116 | } 117 | 118 | // KNN returns the k-nearest neighbours of the given point. 119 | // The points are sorted by the distance to the given points. Starting with the nearest. 120 | func (t *KDTree) KNN(p Point, k int) []Point { 121 | if t.root == nil || p == nil || k == 0 { 122 | return []Point{} 123 | } 124 | 125 | nearestPQ := pq.NewPriorityQueue(pq.WithMinPrioSize(k)) 126 | knn(p, k, t.root, 0, nearestPQ) 127 | 128 | points := make([]Point, 0, k) 129 | for i := 0; i < k && 0 < nearestPQ.Len(); i++ { 130 | o := nearestPQ.PopLowest().(*node).Point 131 | points = append(points, o) 132 | } 133 | 134 | return points 135 | } 136 | 137 | // RangeSearch returns all points in the given range r. 138 | // 139 | // Returns an empty slice when input is nil or len(r) does not equal Point.Dimensions(). 140 | func (t *KDTree) RangeSearch(r kdrange.Range) []Point { 141 | if t.root == nil || r == nil || len(r) != t.root.Dimensions() { 142 | return []Point{} 143 | } 144 | 145 | return t.root.RangeSearch(r, 0) 146 | } 147 | 148 | func knn(p Point, k int, start *node, currentAxis int, nearestPQ *pq.PriorityQueue) { 149 | if p == nil || k == 0 || start == nil { 150 | return 151 | } 152 | 153 | var path []*node 154 | currentNode := start 155 | 156 | // 1. move down 157 | for currentNode != nil { 158 | path = append(path, currentNode) 159 | if p.Dimension(currentAxis) < currentNode.Dimension(currentAxis) { 160 | currentNode = currentNode.Left 161 | } else { 162 | currentNode = currentNode.Right 163 | } 164 | currentAxis = (currentAxis + 1) % p.Dimensions() 165 | } 166 | 167 | // 2. move up 168 | currentAxis = (currentAxis - 1 + p.Dimensions()) % p.Dimensions() 169 | for path, currentNode = popLast(path); currentNode != nil; path, currentNode = popLast(path) { 170 | currentDistance := distance(p, currentNode) 171 | checkedDistance := getKthOrLastDistance(nearestPQ, k-1) 172 | if currentDistance < checkedDistance { 173 | nearestPQ.Insert(currentNode, currentDistance) 174 | checkedDistance = getKthOrLastDistance(nearestPQ, k-1) 175 | } 176 | 177 | // check other side of plane 178 | if planeDistance(p, currentNode.Dimension(currentAxis), currentAxis) < checkedDistance { 179 | var next *node 180 | if p.Dimension(currentAxis) < currentNode.Dimension(currentAxis) { 181 | next = currentNode.Right 182 | } else { 183 | next = currentNode.Left 184 | } 185 | knn(p, k, next, (currentAxis+1)%p.Dimensions(), nearestPQ) 186 | } 187 | currentAxis = (currentAxis - 1 + p.Dimensions()) % p.Dimensions() 188 | } 189 | } 190 | 191 | func distance(p1, p2 Point) float64 { 192 | sum := 0. 193 | for i := 0; i < p1.Dimensions(); i++ { 194 | sum += math.Pow(p1.Dimension(i)-p2.Dimension(i), 2.0) 195 | } 196 | return math.Sqrt(sum) 197 | } 198 | 199 | func planeDistance(p Point, planePosition float64, dim int) float64 { 200 | return math.Abs(planePosition - p.Dimension(dim)) 201 | } 202 | 203 | func popLast(arr []*node) ([]*node, *node) { 204 | l := len(arr) - 1 205 | if l < 0 { 206 | return arr, nil 207 | } 208 | return arr[:l], arr[l] 209 | } 210 | 211 | func getKthOrLastDistance(nearestPQ *pq.PriorityQueue, i int) float64 { 212 | if nearestPQ.Len() <= i { 213 | return math.MaxFloat64 214 | } 215 | _, prio := nearestPQ.Get(i) 216 | return prio 217 | } 218 | 219 | // 220 | // 221 | // byDimension 222 | // 223 | 224 | type byDimension struct { 225 | dimension int 226 | points []Point 227 | } 228 | 229 | // Len is the number of elements in the collection. 230 | func (b *byDimension) Len() int { 231 | return len(b.points) 232 | } 233 | 234 | // Less reports whether the element with 235 | // index i should sort before the element with index j. 236 | func (b *byDimension) Less(i, j int) bool { 237 | return b.points[i].Dimension(b.dimension) < b.points[j].Dimension(b.dimension) 238 | } 239 | 240 | // Swap swaps the elements with indexes i and j. 241 | func (b *byDimension) Swap(i, j int) { 242 | b.points[i], b.points[j] = b.points[j], b.points[i] 243 | } 244 | 245 | // 246 | // 247 | // node 248 | // 249 | 250 | type node struct { 251 | Point 252 | Left *node 253 | Right *node 254 | } 255 | 256 | func (n *node) String() string { 257 | return fmt.Sprintf("%v", n.Point) 258 | } 259 | 260 | func (n *node) Points() []Point { 261 | var points []Point 262 | if n.Left != nil { 263 | points = n.Left.Points() 264 | } 265 | points = append(points, n.Point) 266 | if n.Right != nil { 267 | points = append(points, n.Right.Points()...) 268 | } 269 | return points 270 | } 271 | 272 | func (n *node) Insert(p Point, axis int) { 273 | if p.Dimension(axis) < n.Point.Dimension(axis) { 274 | if n.Left == nil { 275 | n.Left = &node{Point: p} 276 | } else { 277 | n.Left.Insert(p, (axis+1)%n.Point.Dimensions()) 278 | } 279 | } else { 280 | if n.Right == nil { 281 | n.Right = &node{Point: p} 282 | } else { 283 | n.Right.Insert(p, (axis+1)%n.Point.Dimensions()) 284 | } 285 | } 286 | } 287 | 288 | // Remove returns (returned node, substitute node) 289 | func (n *node) Remove(p Point, axis int) (*node, *node) { 290 | for i := 0; i < n.Dimensions(); i++ { 291 | if n.Dimension(i) != p.Dimension(i) { 292 | if n.Left != nil { 293 | returnedNode, substitutedNode := n.Left.Remove(p, (axis+1)%n.Dimensions()) 294 | if returnedNode != nil { 295 | if returnedNode == n.Left { 296 | n.Left = substitutedNode 297 | } 298 | return returnedNode, nil 299 | } 300 | } 301 | if n.Right != nil { 302 | returnedNode, substitutedNode := n.Right.Remove(p, (axis+1)%n.Dimensions()) 303 | if returnedNode != nil { 304 | if returnedNode == n.Right { 305 | n.Right = substitutedNode 306 | } 307 | return returnedNode, nil 308 | } 309 | } 310 | return nil, nil 311 | } 312 | } 313 | 314 | // equals, remove n 315 | 316 | if n.Left != nil { 317 | largest := n.Left.FindLargest(axis, nil) 318 | removed, sub := n.Left.Remove(largest, (axis+1)%n.Dimensions()) 319 | 320 | removed.Left = n.Left 321 | removed.Right = n.Right 322 | if n.Left == removed { 323 | removed.Left = sub 324 | } 325 | return n, removed 326 | } 327 | 328 | if n.Right != nil { 329 | smallest := n.Right.FindSmallest(axis, nil) 330 | removed, sub := n.Right.Remove(smallest, (axis+1)%n.Dimensions()) 331 | 332 | removed.Left = n.Left 333 | removed.Right = n.Right 334 | if n.Right == removed { 335 | removed.Right = sub 336 | } 337 | return n, removed 338 | } 339 | 340 | // n.Left == nil && n.Right == nil 341 | return n, nil 342 | } 343 | 344 | func (n *node) FindSmallest(axis int, smallest *node) *node { 345 | if smallest == nil || n.Dimension(axis) < smallest.Dimension(axis) { 346 | smallest = n 347 | } 348 | if n.Left != nil { 349 | smallest = n.Left.FindSmallest(axis, smallest) 350 | } 351 | if n.Right != nil { 352 | smallest = n.Right.FindSmallest(axis, smallest) 353 | } 354 | return smallest 355 | } 356 | 357 | func (n *node) FindLargest(axis int, largest *node) *node { 358 | if largest == nil || n.Dimension(axis) > largest.Dimension(axis) { 359 | largest = n 360 | } 361 | if n.Left != nil { 362 | largest = n.Left.FindLargest(axis, largest) 363 | } 364 | if n.Right != nil { 365 | largest = n.Right.FindLargest(axis, largest) 366 | } 367 | return largest 368 | } 369 | 370 | func (n *node) RangeSearch(r kdrange.Range, axis int) []Point { 371 | points := []Point{} 372 | 373 | for dim, limit := range r { 374 | if limit[0] > n.Dimension(dim) || limit[1] < n.Dimension(dim) { 375 | goto checkChildren 376 | } 377 | } 378 | points = append(points, n.Point) 379 | 380 | checkChildren: 381 | if n.Left != nil && n.Dimension(axis) >= r[axis][0] { 382 | points = append(points, n.Left.RangeSearch(r, (axis+1)%n.Dimensions())...) 383 | } 384 | if n.Right != nil && n.Dimension(axis) <= r[axis][1] { 385 | points = append(points, n.Right.RangeSearch(r, (axis+1)%n.Dimensions())...) 386 | } 387 | 388 | return points 389 | } 390 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /kdtree_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Dennis Kuhnert 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package kdtree_test 18 | 19 | import ( 20 | "github.com/jupp0r/go-priority-queue" 21 | "github.com/kyroy/kdtree" 22 | "github.com/kyroy/kdtree/kdrange" 23 | . "github.com/kyroy/kdtree/points" 24 | "github.com/stretchr/testify/assert" 25 | "math" 26 | "math/rand" 27 | "testing" 28 | "time" 29 | ) 30 | 31 | func TestNew(t *testing.T) { 32 | tests := []struct { 33 | name string 34 | input []kdtree.Point 35 | output []kdtree.Point 36 | }{ 37 | { 38 | name: "nil", 39 | input: nil, 40 | output: []kdtree.Point{}, 41 | }, 42 | { 43 | name: "empty", 44 | input: []kdtree.Point{}, 45 | output: []kdtree.Point{}, 46 | }, 47 | { 48 | name: "1", 49 | input: []kdtree.Point{&Point2D{X: 1., Y: 2.}}, 50 | output: []kdtree.Point{&Point2D{X: 1., Y: 2.}}, 51 | }, 52 | { 53 | name: "2 equal", 54 | input: []kdtree.Point{&Point2D{X: 1., Y: 2.}, &Point2D{X: 1., Y: 2.}}, 55 | output: []kdtree.Point{&Point2D{X: 1., Y: 2.}, &Point2D{X: 1., Y: 2.}}, 56 | }, 57 | { 58 | name: "sort 1 dim", 59 | input: []kdtree.Point{&Point2D{X: 1.1, Y: 1.2}, &Point2D{X: 1.3, Y: 1.0}, &Point2D{X: 0.9, Y: 1.3}}, 60 | output: []kdtree.Point{&Point2D{X: 0.9, Y: 1.3}, &Point2D{X: 1.1, Y: 1.2}, &Point2D{X: 1.3, Y: 1.0}}, 61 | }, 62 | } 63 | for _, test := range tests { 64 | t.Run(test.name, func(t *testing.T) { 65 | tree := kdtree.New(test.input) 66 | assert.Equal(t, test.output, tree.Points()) 67 | }) 68 | 69 | } 70 | } 71 | 72 | func TestKDTree_String(t *testing.T) { 73 | tests := []struct { 74 | name string 75 | tree *kdtree.KDTree 76 | expected string 77 | }{ 78 | {name: "empty", tree: &kdtree.KDTree{}, expected: "[]"}, 79 | {name: "1 elem", tree: kdtree.New([]kdtree.Point{&Point2D{X: 2, Y: 3}}), expected: "[{2.00 3.00}]"}, 80 | {name: "2 elem", tree: kdtree.New([]kdtree.Point{&Point2D{X: 2, Y: 3}, &Point2D{X: 3.4, Y: 1}}), expected: "[[{2.00 3.00} {3.40 1.00} ]]"}, 81 | {name: "3 elem", tree: kdtree.New([]kdtree.Point{&Point2D{X: 2, Y: 3}, &Point2D{X: 1.4, Y: 7.1}, &Point2D{X: 3.4, Y: 1}}), expected: "[[{1.40 7.10} {2.00 3.00} {3.40 1.00}]]"}, 82 | } 83 | for _, test := range tests { 84 | t.Run(test.name, func(t *testing.T) { 85 | assert.Equal(t, test.expected, test.tree.String()) 86 | }) 87 | } 88 | } 89 | 90 | func TestKDTree_Insert(t *testing.T) { 91 | tests := []struct { 92 | name string 93 | treeInput *kdtree.KDTree 94 | input []kdtree.Point 95 | output []kdtree.Point 96 | }{ 97 | { 98 | name: "empty tree", 99 | input: []kdtree.Point{&Point2D{X: 1., Y: 2.}}, 100 | output: []kdtree.Point{&Point2D{X: 1., Y: 2.}}, 101 | }, 102 | { 103 | name: "1 dim", 104 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1., Y: 2.}}), 105 | input: []kdtree.Point{&Point2D{X: 0.9, Y: 2.1}}, 106 | output: []kdtree.Point{&Point2D{X: 0.9, Y: 2.1}, &Point2D{X: 1., Y: 2.}}, 107 | }, 108 | } 109 | for _, test := range tests { 110 | t.Run(test.name, func(t *testing.T) { 111 | if test.treeInput == nil { 112 | test.treeInput = kdtree.New(nil) 113 | } 114 | for _, elem := range test.input { 115 | test.treeInput.Insert(elem) 116 | } 117 | assert.Equal(t, test.output, test.treeInput.Points()) 118 | }) 119 | } 120 | } 121 | 122 | func TestKDTree_InsertWithGenerator(t *testing.T) { 123 | tests := []struct { 124 | name string 125 | input []kdtree.Point 126 | }{ 127 | {name: "p:10,k:5", input: generateTestCaseData(10)}, 128 | {name: "p:100,k:5", input: generateTestCaseData(100)}, 129 | {name: "p:1000,k:5", input: generateTestCaseData(1000)}, 130 | } 131 | for _, test := range tests { 132 | t.Run(test.name, func(t *testing.T) { 133 | tree := kdtree.New(nil) 134 | for _, elem := range test.input { 135 | tree.Insert(elem) 136 | _ = tree.Points() 137 | // TODO assert 138 | //assert.Equal(t, , treePoints) 139 | } 140 | }) 141 | } 142 | } 143 | 144 | func TestKDTree_Remove(t *testing.T) { 145 | tests := []struct { 146 | name string 147 | treeInput *kdtree.KDTree 148 | preRemove []kdtree.Point 149 | input kdtree.Point 150 | treeOutput string 151 | output kdtree.Point 152 | }{ 153 | { 154 | name: "empty tree", 155 | treeInput: kdtree.New([]kdtree.Point{}), 156 | input: &Point2D{}, 157 | treeOutput: "[]", 158 | output: nil, 159 | }, 160 | { 161 | name: "nil input", 162 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1., Y: 2.}}), 163 | input: nil, 164 | treeOutput: "[{1.00 2.00}]", 165 | output: nil, 166 | }, 167 | { 168 | name: "remove root", 169 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1., Y: 2.}}), 170 | input: &Point2D{X: 1., Y: 2.}, 171 | treeOutput: "[]", 172 | output: &Point2D{X: 1., Y: 2.}, 173 | }, 174 | { 175 | name: "remove root with children", 176 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1., Y: 2.}, &Point2D{X: 1.2, Y: 2.2}, &Point2D{X: 1.3, Y: 2.3}, &Point2D{X: 1.1, Y: 2.1}, &Point2D{X: -1.3, Y: -2.2}}), 177 | input: &Point2D{X: 1.1, Y: 2.1}, 178 | treeOutput: "[[{-1.30 -2.20} {1.00 2.00} [{1.20 2.20} {1.30 2.30} ]]]", 179 | output: &Point2D{X: 1.1, Y: 2.1}, 180 | }, 181 | // x(5,4) 182 | // y(3,6) (7, 7) 183 | // x(2, 2) (2, 10) (8, 2) (9, 9) 184 | // y(1, 3) (4, 1) (1,8) nil (7, 4) (8, 5) (6, 8) nil 185 | // [[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]] 186 | { 187 | name: "not existing", 188 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 189 | input: &Point2D{X: 1., Y: 1.}, 190 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 191 | output: nil, 192 | }, 193 | { 194 | name: "remove leaf", 195 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 196 | input: &Point2D{X: 8., Y: 5.}, 197 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} ] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 198 | output: &Point2D{X: 8., Y: 5.}, 199 | }, 200 | { 201 | name: "remove leaf", 202 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 203 | input: &Point2D{X: 6., Y: 8.}, 204 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} {9.00 9.00}]]]", 205 | output: &Point2D{X: 6., Y: 8.}, 206 | }, 207 | { 208 | name: "remove with 1 replace, right child nil", 209 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 210 | input: &Point2D{X: 9., Y: 9.}, 211 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} {6.00 8.00}]]]", 212 | output: &Point2D{X: 9., Y: 9.}, 213 | }, 214 | { 215 | name: "remove with 1 replace, left child nil", 216 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 217 | preRemove: []kdtree.Point{&Point2D{X: 1, Y: 3}}, 218 | input: &Point2D{X: 2., Y: 2.}, 219 | treeOutput: "[[[{4.00 1.00} {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 220 | output: &Point2D{X: 2., Y: 2.}, 221 | }, 222 | { 223 | name: "remove with 1 replace", 224 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 225 | input: &Point2D{X: 8., Y: 2.}, 226 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[ {7.00 4.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 227 | output: &Point2D{X: 8., Y: 2.}, 228 | }, 229 | { 230 | name: "remove with 1 replace, deep", 231 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 232 | input: &Point2D{X: 3., Y: 6.}, 233 | treeOutput: "[[[[ {2.00 2.00} {4.00 1.00}] {1.00 3.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 234 | output: &Point2D{X: 3., Y: 6.}, 235 | }, 236 | { 237 | name: "remove with 1 replace, deep", 238 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 239 | input: &Point2D{X: 7., Y: 7.}, 240 | treeOutput: "[[[[{1.00 3.00} {2.00 2.00} {4.00 1.00}] {3.00 6.00} [{1.00 8.00} {2.00 10.00} ]] {5.00 4.00} [[{7.00 4.00} {8.00 2.00} ] {8.00 5.00} [{6.00 8.00} {9.00 9.00} ]]]]", 241 | output: &Point2D{X: 7., Y: 7.}, 242 | }, 243 | { 244 | name: "remove with left nil", 245 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 246 | preRemove: []kdtree.Point{&Point2D{X: 4, Y: 1}, &Point2D{X: 1, Y: 3}, &Point2D{X: 2, Y: 2}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}}, 247 | input: &Point2D{X: 5., Y: 4.}, 248 | treeOutput: "[[ {6.00 8.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} {9.00 9.00}]]]", 249 | output: &Point2D{X: 5., Y: 4.}, 250 | }, 251 | { 252 | name: "remove with sub left nil", 253 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}), 254 | preRemove: []kdtree.Point{&Point2D{X: 4, Y: 1}, &Point2D{X: 1, Y: 3}, &Point2D{X: 2, Y: 2}}, 255 | input: &Point2D{X: 5., Y: 4.}, 256 | treeOutput: "[[[ {1.00 8.00} {2.00 10.00}] {3.00 6.00} [[{7.00 4.00} {8.00 2.00} {8.00 5.00}] {7.00 7.00} [{6.00 8.00} {9.00 9.00} ]]]]", 257 | output: &Point2D{X: 5., Y: 4.}, 258 | }, 259 | // x (4,1) 260 | // y (1,3) (5,4) 261 | // x (3,1) (3,6) (7,3) (8,5) 262 | // y (2,2) (4,2) (2,8) (3,8) (5,3) (9,2) (7,7) (9,8) 263 | // x (2,1) (1,3) (3,1) (3,3) (1,8) (2,10) (4,4) (3,9) (6,2) (6,4) (8,2) (7,4) (6,5) (6,8) (9,6) (9,9) 264 | // [[[[[{2.00 1.00} {2.00 2.00} {1.00 3.00}] {3.00 1.00} [{3.00 1.00} {4.00 2.00} {3.00 3.00}]] {1.00 3.00} [[{1.00 8.00} {2.00 8.00} {2.00 10.00}] {3.00 6.00} [{4.00 4.00} {3.00 8.00} {3.00 9.00}]]] {4.00 1.00} [[[{6.00 2.00} {5.00 3.00} {6.00 4.00}] {7.00 3.00} [{8.00 2.00} {9.00 2.00} {7.00 4.00}]] {5.00 4.00} [[{6.00 5.00} {7.00 7.00} {6.00 8.00}] {8.00 5.00} [{9.00 6.00} {9.00 8.00} {9.00 9.00}]]]]] 265 | { 266 | name: "remove (3,1) with 2 replace", 267 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 268 | input: &Point2D{X: 3., Y: 1.}, 269 | treeOutput: "[[[[[ {2.00 1.00} {1.00 3.00}] {2.00 2.00} [{3.00 1.00} {4.00 2.00} {3.00 3.00}]] {1.00 3.00} [[{1.00 8.00} {2.00 8.00} {2.00 10.00}] {3.00 6.00} [{4.00 4.00} {3.00 8.00} {3.00 9.00}]]] {4.00 1.00} [[[{6.00 2.00} {5.00 3.00} {6.00 4.00}] {7.00 3.00} [{8.00 2.00} {9.00 2.00} {7.00 4.00}]] {5.00 4.00} [[{6.00 5.00} {7.00 7.00} {6.00 8.00}] {8.00 5.00} [{9.00 6.00} {9.00 8.00} {9.00 9.00}]]]]]", 270 | output: &Point2D{X: 3., Y: 1.}, 271 | }, 272 | { 273 | name: "remove (5,4) with 1 replace, deep 3", 274 | treeInput: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 275 | input: &Point2D{X: 5., Y: 4.}, 276 | treeOutput: "[[[[[{2.00 1.00} {2.00 2.00} {1.00 3.00}] {3.00 1.00} [{3.00 1.00} {4.00 2.00} {3.00 3.00}]] {1.00 3.00} [[{1.00 8.00} {2.00 8.00} {2.00 10.00}] {3.00 6.00} [{4.00 4.00} {3.00 8.00} {3.00 9.00}]]] {4.00 1.00} [[[{6.00 2.00} {5.00 3.00} ] {7.00 3.00} [{8.00 2.00} {9.00 2.00} {7.00 4.00}]] {6.00 4.00} [[{6.00 5.00} {7.00 7.00} {6.00 8.00}] {8.00 5.00} [{9.00 6.00} {9.00 8.00} {9.00 9.00}]]]]]", 277 | output: &Point2D{X: 5., Y: 4.}, 278 | }, 279 | } 280 | for _, test := range tests { 281 | t.Run(test.name, func(t *testing.T) { 282 | if test.preRemove != nil { 283 | for _, r := range test.preRemove { 284 | test.treeInput.Remove(r) 285 | } 286 | } 287 | o := test.treeInput.Remove(test.input) 288 | if c, ok := o.(kdtree.Point); ok { 289 | assertPointsEqual(t, test.output, c) 290 | } else { 291 | assert.Equal(t, test.output, o) 292 | } 293 | assert.Equal(t, test.treeOutput, test.treeInput.String()) 294 | }) 295 | } 296 | } 297 | 298 | func TestKDTree_Balance(t *testing.T) { 299 | tests := []struct { 300 | name string 301 | treeInput *kdtree.KDTree 302 | preRemove []kdtree.Point 303 | treeOutput string 304 | }{ 305 | { 306 | name: "empty tree", 307 | treeInput: kdtree.New([]kdtree.Point{}), 308 | treeOutput: "[]", 309 | }, 310 | } 311 | for _, test := range tests { 312 | t.Run(test.name, func(t *testing.T) { 313 | if test.preRemove != nil { 314 | for _, r := range test.preRemove { 315 | test.treeInput.Remove(r) 316 | } 317 | } 318 | test.treeInput.Balance() 319 | assert.Equal(t, test.treeOutput, test.treeInput.String()) 320 | }) 321 | } 322 | } 323 | 324 | func TestKDTree_BalanceNoNilNode(t *testing.T) { 325 | tests := []struct { 326 | name string 327 | input []kdtree.Point 328 | add int 329 | remove int 330 | }{ 331 | // add 332 | {name: "0->1", input: generateTestCaseData(0), add: 1}, 333 | {name: "0->3", input: generateTestCaseData(0), add: 3}, 334 | {name: "0->7", input: generateTestCaseData(0), add: 7}, 335 | {name: "0->15", input: generateTestCaseData(0), add: 15}, 336 | // remove 337 | {name: "5->1", input: generateTestCaseData(5), remove: 4}, 338 | {name: "32->3", input: generateTestCaseData(32), remove: 29}, 339 | {name: "17->7", input: generateTestCaseData(17), remove: 10}, 340 | {name: "17->15", input: generateTestCaseData(17), remove: 2}, 341 | // remove & add 342 | {name: "50->8->15", input: generateTestCaseData(50), remove: 42, add: 7}, 343 | } 344 | for _, test := range tests { 345 | t.Run(test.name, func(t *testing.T) { 346 | tree := kdtree.New(test.input) 347 | for i := 0; i < test.remove; i++ { 348 | tree.Remove(test.input[i]) 349 | } 350 | for _, p := range generateTestCaseData(test.add) { 351 | tree.Insert(p) 352 | } 353 | tree.Balance() 354 | assert.NotContains(t, tree.String(), "") 355 | }) 356 | } 357 | } 358 | 359 | // TestKNN ... 360 | func TestKDTree_KNN(t *testing.T) { 361 | tests := []struct { 362 | name string 363 | target kdtree.Point 364 | k int 365 | input []kdtree.Point 366 | output []kdtree.Point 367 | }{ 368 | { 369 | name: "nil", 370 | target: nil, 371 | k: 3, 372 | input: []kdtree.Point{&Point2D{X: 1., Y: 2.}}, 373 | output: []kdtree.Point{}, 374 | }, 375 | { 376 | name: "empty", 377 | target: &Point2D{X: 1., Y: 2.}, 378 | k: 3, 379 | input: []kdtree.Point{}, 380 | output: []kdtree.Point{}, 381 | }, 382 | { 383 | name: "k >> points", 384 | target: &Point2D{X: 1., Y: 2.}, 385 | k: 10, 386 | input: []kdtree.Point{&Point2D{X: 1., Y: 2.}, &Point2D{X: 0.9, Y: 2.1}, &Point2D{X: 1.1, Y: 1.9}}, 387 | output: []kdtree.Point{&Point2D{X: 1., Y: 2.}, &Point2D{X: 0.9, Y: 2.1}, &Point2D{X: 1.1, Y: 1.9}}, 388 | }, 389 | { 390 | name: "small 2D example", 391 | target: &Point2D{X: 9, Y: 4}, 392 | k: 3, 393 | input: []kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}}, 394 | output: []kdtree.Point{&Point2D{X: 8, Y: 5}, &Point2D{X: 7, Y: 4}, &Point2D{X: 8, Y: 2}}, 395 | }, 396 | } 397 | for _, test := range tests { 398 | t.Run(test.name, func(t *testing.T) { 399 | tree := kdtree.New(test.input) 400 | assert.Equal(t, test.output, tree.KNN(test.target, test.k)) 401 | }) 402 | } 403 | } 404 | 405 | func TestKDTree_KNNWithGenerator(t *testing.T) { 406 | tests := []struct { 407 | name string 408 | target kdtree.Point 409 | k int 410 | input []kdtree.Point 411 | }{ 412 | {name: "p:100,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(100)}, 413 | {name: "p:1000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(1000)}, 414 | {name: "p:10000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(10000)}, 415 | {name: "p:100000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(100000)}, 416 | {name: "p:1000000,k:10", target: &Point2D{}, k: 10, input: generateTestCaseData(1000000)}, 417 | {name: "p:1000000,k:20", target: &Point2D{}, k: 20, input: generateTestCaseData(1000000)}, 418 | {name: "p:1000000,k:30", target: &Point2D{}, k: 30, input: generateTestCaseData(1000000)}, 419 | } 420 | for _, test := range tests { 421 | t.Run(test.name, func(t *testing.T) { 422 | tree := kdtree.New(test.input) 423 | assert.Equal(t, prioQueueKNN(test.input, test.target, test.k), tree.KNN(test.target, test.k)) 424 | }) 425 | } 426 | } 427 | 428 | func TestKDTree_RangeSearch(t *testing.T) { 429 | tests := []struct { 430 | name string 431 | tree *kdtree.KDTree 432 | input kdrange.Range 433 | expected []kdtree.Point 434 | }{ 435 | { 436 | name: "nil", 437 | tree: kdtree.New(generateTestCaseData(5)), 438 | input: nil, 439 | expected: []kdtree.Point{}, 440 | }, 441 | { 442 | name: "wrong dim", 443 | tree: kdtree.New(generateTestCaseData(5)), 444 | input: kdrange.New(), 445 | expected: []kdtree.Point{}, 446 | }, 447 | { 448 | name: "out of range x (lower)", 449 | tree: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 450 | input: kdrange.New(-2, -1, 2, 10), 451 | expected: []kdtree.Point{}, 452 | }, 453 | { 454 | name: "out of range y (lower)", 455 | tree: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 456 | input: kdrange.New(2, 10, -2, -1), 457 | expected: []kdtree.Point{}, 458 | }, 459 | { 460 | name: "out of range x (higher)", 461 | tree: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 462 | input: kdrange.New(20, 30, 2, 10), 463 | expected: []kdtree.Point{}, 464 | }, 465 | { 466 | name: "out of range y (higher)", 467 | tree: kdtree.New([]kdtree.Point{&Point2D{X: 1, Y: 3}, &Point2D{X: 1, Y: 8}, &Point2D{X: 2, Y: 2}, &Point2D{X: 2, Y: 10}, &Point2D{X: 3, Y: 6}, &Point2D{X: 4, Y: 1}, &Point2D{X: 5, Y: 4}, &Point2D{X: 6, Y: 8}, &Point2D{X: 7, Y: 4}, &Point2D{X: 7, Y: 7}, &Point2D{X: 8, Y: 2}, &Point2D{X: 8, Y: 5}, &Point2D{X: 9, Y: 9}, &Point2D{X: 3, Y: 1}, &Point2D{X: 4, Y: 2}, &Point2D{X: 9, Y: 2}, &Point2D{X: 6, Y: 5}, &Point2D{X: 3, Y: 8}, &Point2D{X: 6, Y: 2}, &Point2D{X: 1, Y: 3}, &Point2D{X: 3, Y: 3}, &Point2D{X: 6, Y: 4}, &Point2D{X: 9, Y: 8}, &Point2D{X: 2, Y: 1}, &Point2D{X: 2, Y: 8}, &Point2D{X: 3, Y: 1}, &Point2D{X: 7, Y: 3}, &Point2D{X: 3, Y: 9}, &Point2D{X: 4, Y: 4}, &Point2D{X: 5, Y: 3}, &Point2D{X: 9, Y: 6}}), 468 | input: kdrange.New(2, 10, 20, 30), 469 | expected: []kdtree.Point{}, 470 | }, 471 | } 472 | for _, test := range tests { 473 | t.Run(test.name, func(t *testing.T) { 474 | assert.Equal(t, test.expected, test.tree.RangeSearch(test.input)) 475 | }) 476 | } 477 | } 478 | 479 | func TestKDTree_RangeSearchWithGenerator(t *testing.T) { 480 | tests := []struct { 481 | name string 482 | input []kdtree.Point 483 | r kdrange.Range 484 | }{ 485 | {name: "nodes: 100 range: -100 50 -50 100", input: generateTestCaseData(100), r: kdrange.New(-100, 50, -50, 100)}, 486 | {name: "nodes: 1000 range: -100 50 -50 100", input: generateTestCaseData(1000), r: kdrange.New(-100, 50, -50, 100)}, 487 | {name: "nodes: 10000 range: -100 50 -50 100", input: generateTestCaseData(10000), r: kdrange.New(-100, 50, -50, 100)}, 488 | {name: "nodes: 100000 range: -500 250 -250 500", input: generateTestCaseData(100000), r: kdrange.New(-500, 250, -250, 500)}, 489 | {name: "nodes: 1000000 range: -500 250 -250 500", input: generateTestCaseData(1000000), r: kdrange.New(-500, 250, -250, 500)}, 490 | } 491 | for _, test := range tests { 492 | t.Run(test.name, func(t *testing.T) { 493 | tree := kdtree.New(test.input) 494 | assert.ElementsMatch(t, filterRangeSearch(test.input, test.r), tree.RangeSearch(test.r)) 495 | }) 496 | } 497 | } 498 | 499 | // TestKDTree_RemoveAxisInversion is a targeted test for issue #6. 500 | // 501 | // https://github.com/kyroy/kdtree/issues/6 502 | // 503 | // Remove wasn't correctly taking into account the axis when searching for 504 | // replacements/substitutes. This caused an incorrect result when removing the 505 | // root node from this tree. 506 | // 507 | // This is because the {171, 176} node starts on the 'left' branch of the 508 | // {238, 155} node, which is correct if indexed by the X axis. When the root 509 | // node is removed, {238, 155} instead becomes indexed on the Y axis, but 510 | // {171, 176} was being left on the 'left' branch. 511 | // 512 | // This test verifies the fix and should help prevent regressions 513 | func TestKDTree_RemoveAxisInversion(t *testing.T) { 514 | tree := kdtree.New([]kdtree.Point{ 515 | &Point2D{X: 171, Y: 176}, 516 | &Point2D{X: 238, Y: 155}, 517 | &Point2D{X: 257, Y: 246}, 518 | &Point2D{X: 181, Y: 265}, 519 | &Point2D{X: 206, Y: 282}, 520 | &Point2D{X: 265, Y: 176}, 521 | &Point2D{X: 284, Y: 209}, 522 | &Point2D{X: 296, Y: 168}, 523 | &Point2D{X: 280, Y: 225}, 524 | &Point2D{X: 288, Y: 283}, 525 | &Point2D{X: 289, Y: 292}, 526 | }) 527 | search := &Point2D{X: 150, Y: 218} 528 | remove := &Point2D{X: 265, Y: 176} 529 | 530 | tree.Remove(remove) 531 | 532 | fewNN := tree.KNN(search, 1) 533 | manyNN := tree.KNN(search, 10) 534 | 535 | assertPointsEqual(t, fewNN[0], manyNN[0]) 536 | } 537 | 538 | func TestKDTree_RemoveAxisInversionGenerator(t *testing.T) { 539 | for dims := 2; dims <= 4; dims++ { 540 | maxSize := int(math.Pow(float64(dims), 4)) 541 | 542 | tree := kdtree.New(nil) 543 | arr := make([]kdtree.Point, 0, maxSize+1) 544 | for i := 0; i < 1000; i++ { 545 | p := generateTestPoint(dims) 546 | 547 | // Two KNN queries 548 | fewNN := tree.KNN(p, 1) 549 | manyNN := tree.KNN(p, maxSize) 550 | 551 | if len(arr) > 0 { 552 | assertPointsEqual(t, fewNN[0], manyNN[0]) 553 | } 554 | 555 | // Add in the new point 556 | arr = append(arr, p) 557 | tree.Insert(p) 558 | 559 | // Limit the max number of elements - which will also 560 | // introduce some churn in the tree 561 | if len(arr) > maxSize { 562 | idx := rand.Intn(len(arr)) 563 | tree.Remove(arr[idx]) 564 | arr[idx] = arr[len(arr)-1] 565 | arr = arr[:len(arr)-1] 566 | } 567 | } 568 | } 569 | } 570 | 571 | // benchmarks 572 | 573 | var resultTree *kdtree.KDTree 574 | var resultPoints []kdtree.Point 575 | 576 | func BenchmarkNew(b *testing.B) { 577 | benchmarks := []struct { 578 | name string 579 | input []kdtree.Point 580 | }{ 581 | {name: "100", input: generateTestCaseData(100)}, 582 | {name: "1000", input: generateTestCaseData(1000)}, 583 | {name: "10000", input: generateTestCaseData(10000)}, 584 | {name: "100000", input: generateTestCaseData(100000)}, 585 | } 586 | for _, bm := range benchmarks { 587 | b.Run(bm.name, func(b *testing.B) { 588 | var t *kdtree.KDTree 589 | for i := 0; i < b.N; i++ { 590 | t = kdtree.New(bm.input) 591 | } 592 | resultTree = t 593 | }) 594 | } 595 | } 596 | 597 | func BenchmarkKNN(b *testing.B) { 598 | benchmarks := []struct { 599 | name string 600 | target kdtree.Point 601 | k int 602 | input []kdtree.Point 603 | }{ 604 | {name: "p:100,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(100)}, 605 | {name: "p:1000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(1000)}, 606 | {name: "p:10000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(10000)}, 607 | {name: "p:100000,k:5", target: &Point2D{}, k: 5, input: generateTestCaseData(100000)}, 608 | } 609 | for _, bm := range benchmarks { 610 | var res []kdtree.Point 611 | tree := kdtree.New(bm.input) 612 | b.Run(bm.name, func(b *testing.B) { 613 | for i := 0; i < b.N; i++ { 614 | res = tree.KNN(bm.target, bm.k) 615 | } 616 | resultPoints = res 617 | }) 618 | } 619 | } 620 | 621 | // helpers 622 | 623 | func generateTestCaseData(size int) []kdtree.Point { 624 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 625 | var points []kdtree.Point 626 | for i := 0; i < size; i++ { 627 | points = append(points, &Point2D{X: r.Float64()*3000 - 1500, Y: r.Float64()*3000 - 1500}) 628 | } 629 | 630 | return points 631 | } 632 | 633 | func generateTestPoint(dimensions int) kdtree.Point { 634 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 635 | values := make([]float64, dimensions) 636 | for j := range values { 637 | values[j] = r.Float64()*3000 - 1500 638 | } 639 | return NewPoint(values, nil) 640 | } 641 | 642 | func prioQueueKNN(points []kdtree.Point, p kdtree.Point, k int) []kdtree.Point { 643 | knn := make([]kdtree.Point, 0, k) 644 | if p == nil { 645 | return knn 646 | } 647 | 648 | nnPQ := pq.New() 649 | for _, point := range points { 650 | nnPQ.Insert(point, distance(p, point)) 651 | } 652 | 653 | for i := 0; i < k; i++ { 654 | point, err := nnPQ.Pop() 655 | if err != nil { 656 | break 657 | } 658 | knn = append(knn, point.(kdtree.Point)) 659 | } 660 | return knn 661 | } 662 | 663 | func filterRangeSearch(points []kdtree.Point, r kdrange.Range) []kdtree.Point { 664 | result := make([]kdtree.Point, 0) 665 | 666 | pointLoop: 667 | for _, point := range points { 668 | for i, d := range r { 669 | if d[0] > point.Dimension(i) || d[1] < point.Dimension(i) { 670 | continue pointLoop 671 | } 672 | } 673 | result = append(result, point) 674 | } 675 | 676 | return result 677 | } 678 | 679 | func distance(p1, p2 kdtree.Point) float64 { 680 | sum := 0. 681 | for i := 0; i < p1.Dimensions(); i++ { 682 | sum += math.Pow(p1.Dimension(i)-p2.Dimension(i), 2.0) 683 | } 684 | return math.Sqrt(sum) 685 | } 686 | 687 | func assertPointsEqual(t *testing.T, p1 kdtree.Point, p2 kdtree.Point) { 688 | assert.Equal(t, p1.Dimensions(), p2.Dimensions()) 689 | for i := 0; i < p1.Dimensions(); i++ { 690 | assert.Equal(t, p1.Dimension(i), p2.Dimension(i), "assert equal dimension %d", i) 691 | } 692 | } 693 | --------------------------------------------------------------------------------