github.com/gopherd/gonum@v0.0.4/spatial/kdtree/kdtree_simple_example_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_test 6 7 import ( 8 "fmt" 9 "math" 10 11 "github.com/gopherd/gonum/spatial/kdtree" 12 ) 13 14 func ExampleTree() { 15 // Example data from https://en.wikipedia.org/wiki/K-d_tree 16 points := kdtree.Points{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}} 17 18 t := kdtree.New(points, false) 19 q := kdtree.Point{8, 7} 20 p, d := t.Nearest(q) 21 fmt.Printf("%v is closest point to %v, d=%f\n", p, q, math.Sqrt(d)) 22 // Output: 23 // [9 6] is closest point to [8 7], d=1.414214 24 } 25 26 func ExampleTree_bounds() { 27 // Example data from https://en.wikipedia.org/wiki/K-d_tree 28 points := kdtree.Points{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}} 29 30 t := kdtree.New(points, true) 31 fmt.Printf("Bounding box of points is %+v\n", t.Root.Bounding) 32 // Output: 33 // Bounding box of points is &{Min:[2 1] Max:[9 7]} 34 } 35 36 func ExampleTree_Do() { 37 // Example data from https://en.wikipedia.org/wiki/K-d_tree 38 points := kdtree.Points{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}} 39 40 // Print all points in the data set within 3 of (3, 5). 41 t := kdtree.New(points, false) 42 q := kdtree.Point{3, 5} 43 t.Do(func(c kdtree.Comparable, _ *kdtree.Bounding, _ int) (done bool) { 44 // Compare each distance and output points 45 // with a Euclidean distance less than 3. 46 // Distance returns the square of the 47 // Euclidean distance between points. 48 if q.Distance(c) <= 3*3 { 49 fmt.Println(c) 50 } 51 return 52 }) 53 // Unordered output: 54 // [2 3] 55 // [4 7] 56 // [5 4] 57 } 58 59 func ExampleTree_DoBounded() { 60 // Example data from https://en.wikipedia.org/wiki/K-d_tree 61 points := kdtree.Points{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}} 62 63 // Find all points within the bounding box ((3, 3), (6, 8)) 64 // and print them with their bounding boxes and tree depth. 65 t := kdtree.New(points, true) // Construct tree with bounding boxes. 66 b := &kdtree.Bounding{ 67 Min: kdtree.Point{3, 3}, 68 Max: kdtree.Point{6, 8}, 69 } 70 t.DoBounded(b, func(c kdtree.Comparable, bound *kdtree.Bounding, depth int) (done bool) { 71 fmt.Printf("p=%v bound=%+v depth=%d\n", c, bound, depth) 72 return 73 }) 74 // Output: 75 // p=[5 4] bound=&{Min:[2 3] Max:[5 7]} depth=1 76 // p=[4 7] bound=&{Min:[4 7] Max:[4 7]} depth=2 77 }