forked from MadAppGang/kdbush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kdbush.go
320 lines (263 loc) · 7.24 KB
/
kdbush.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package kdbush
import (
"math"
)
// Interface, that should be implemented by indexing structure
// It's just simply returns points coordinates
// Called once, only when index created, so you could calc values on the fly for this interface
type Point interface {
Coordinates() (X, Y float64)
}
// Minimal struct, that implements Point interface
type SimplePoint struct {
X, Y float64
}
// SimplePoint's implementation of Point interface
func (sp *SimplePoint) Coordinates() (float64, float64) {
return sp.X, sp.Y
}
// A very fast static spatial index for 2D points based on a flat KD-tree.
// Points only, no rectangles
// static (no add, remove items)
// 2 dimensional
// indexing 16-40 times faster then rtreego(https://github.com/dhconnelly/rtreego) (TODO: benchmark)
type KDBush struct {
NodeSize int
Points []Point
idxs []int //array of indexes
coords []float64 //array of coordinates
}
// Create new index from points
// Structure don't copy points itself, copy only coordinates
// Returns pointer to new KDBush index object, all data in it already indexed
// Input:
// points - slice of objects, that implements Point interface
// nodeSize - size of the KD-tree node, 64 by default. Higher means faster indexing but slower search, and vise versa.
func NewBush(points []Point, nodeSize int) *KDBush {
b := KDBush{}
b.buildIndex(points, nodeSize)
return &b
}
// Finds all items within the given bounding box and returns an array of indices that refer to the items in the original points input slice.
func (bush *KDBush) Range(minX, minY, maxX, maxY float64) []int {
stack := []int{0, len(bush.idxs) - 1, 0}
result := []int{}
var x, y float64
for len(stack) > 0 {
axis := stack[len(stack)-1]
stack = stack[:len(stack)-1]
right := stack[len(stack)-1]
stack = stack[:len(stack)-1]
left := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if right-left <= bush.NodeSize {
for i := left; i <= right; i++ {
x = bush.coords[2*i]
y = bush.coords[2*i+1]
if x >= minX && x <= maxX && y >= minY && y <= maxY {
result = append(result, bush.idxs[i])
}
}
continue
}
m := floor(float64(left+right) / 2.0)
x = bush.coords[2*m]
y = bush.coords[2*m+1]
if x >= minX && x <= maxX && y >= minY && y <= maxY {
result = append(result, bush.idxs[m])
}
nextAxis := (axis + 1) % 2
if (axis == 0 && minX <= x) || (axis != 0 && minY <= y) {
stack = append(stack, left)
stack = append(stack, m-1)
stack = append(stack, nextAxis)
}
if (axis == 0 && maxX >= x) || (axis != 0 && maxY >= y) {
stack = append(stack, m+1)
stack = append(stack, right)
stack = append(stack, nextAxis)
}
}
return result
}
// Finds all items within a given radius from the query point and returns an array of indices.
// Set true haverstine for calculate correctly distance between two geographical points on a sphere.
func (bush *KDBush) Within(point Point, radius float64, haversine bool) []int {
stack := []int{0, len(bush.idxs) - 1, 0}
result := []int{}
var r2 float64
if haversine {
r2 = radius
} else {
r2 = radius * radius
}
qx, qy := point.Coordinates()
for len(stack) > 0 {
axis := stack[len(stack)-1]
stack = stack[:len(stack)-1]
right := stack[len(stack)-1]
stack = stack[:len(stack)-1]
left := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if right-left <= bush.NodeSize {
for i := left; i <= right; i++ {
dst := distance(bush.coords[2*i], bush.coords[2*i+1], qx, qy, haversine)
if dst <= r2 {
result = append(result, bush.idxs[i])
}
}
continue
}
m := floor(float64(left+right) / 2.0)
x := bush.coords[2*m]
y := bush.coords[2*m+1]
if distance(x, y, qx, qy, haversine) <= r2 {
result = append(result, bush.idxs[m])
}
nextAxis := (axis + 1) % 2
if (axis == 0 && (qx-radius <= x)) || (axis != 0 && (qy-radius <= y)) {
stack = append(stack, left)
stack = append(stack, m-1)
stack = append(stack, nextAxis)
}
if (axis == 0 && (qx+radius >= x)) || (axis != 0 && (qy+radius >= y)) {
stack = append(stack, m+1)
stack = append(stack, right)
stack = append(stack, nextAxis)
}
}
return result
}
///// private method to sort the data
////////////////////////////////////////////////////////////////
/// Sorting stuff
////////////////////////////////////////////////////////////////
func (bush *KDBush) buildIndex(points []Point, nodeSize int) {
bush.NodeSize = nodeSize
bush.Points = points
bush.idxs = make([]int, len(points))
bush.coords = make([]float64, 2*len(points))
for i, v := range points {
bush.idxs[i] = i
x, y := v.Coordinates()
bush.coords[i*2] = x
bush.coords[i*2+1] = y
}
sort(bush.idxs, bush.coords, bush.NodeSize, 0, len(bush.idxs)-1, 0)
}
func sort(idxs []int, coords []float64, nodeSize int, left, right, depth int) {
if (right - left) <= nodeSize {
return
}
m := floor(float64(left+right) / 2.0)
sselect(idxs, coords, m, left, right, depth%2)
sort(idxs, coords, nodeSize, left, m-1, depth+1)
sort(idxs, coords, nodeSize, m+1, right, depth+1)
}
func sselect(idxs []int, coords []float64, k, left, right, inc int) {
//whatever you want
for right > left {
if (right - left) > 600 {
n := right - left + 1
m := k - left + 1
z := math.Log(float64(n))
s := 0.5 * math.Exp(2.0*z/3.0)
sds := 1.0
if float64(m)-float64(n)/2.0 < 0 {
sds = -1.0
}
n_s := float64(n) - s
sd := 0.5 * math.Sqrt(z*s*n_s/float64(n)) * sds
newLeft := iMax(left, floor(float64(k)-float64(m)*s/float64(n)+sd))
newRight := iMin(right, floor(float64(k)+float64(n-m)*s/float64(n)+sd))
sselect(idxs, coords, k, newLeft, newRight, inc)
}
t := coords[2*k+inc]
i := left
j := right
swapItem(idxs, coords, left, k)
if coords[2*right+inc] > t {
swapItem(idxs, coords, left, right)
}
for i < j {
swapItem(idxs, coords, i, j)
i += 1
j -= 1
for coords[2*i+inc] < t {
i += 1
}
for coords[2*j+inc] > t {
j -= 1
}
}
if coords[2*left+inc] == t {
swapItem(idxs, coords, left, j)
} else {
j += 1
swapItem(idxs, coords, j, right)
}
if j <= k {
left = j + 1
}
if k <= j {
right = j - 1
}
}
}
func swapItem(idxs []int, coords []float64, i, j int) {
swapi(idxs, i, j)
swapf(coords, 2*i, 2*j)
swapf(coords, 2*i+1, 2*j+1)
}
func swapf(a []float64, i, j int) {
t := a[i]
a[i] = a[j]
a[j] = t
}
func swapi(a []int, i, j int) {
t := a[i]
a[i] = a[j]
a[j] = t
}
func iMax(a, b int) int {
if a > b {
return a
} else {
return b
}
}
func iMin(a, b int) int {
if a < b {
return a
} else {
return b
}
}
func floor(in float64) int {
out := math.Floor(in)
return int(out)
}
func sqrtDist(ax, ay, bx, by float64) float64 {
dx := ax - bx
dy := ay - by
return dx*dx + dy*dy
}
func orthoDist(ax, ay, bx, by float64) float64 {
var la1, lo1, la2, lo2, r float64
r = 6378100 // Earth radius in METERS (equator)
lo1 = ax * math.Pi / 180 // longitude
la1 = ay * math.Pi / 180 // latitude
lo2 = bx * math.Pi / 180
la2 = by * math.Pi / 180
h := hsin(lo2-lo1) + math.Cos(lo1)*math.Cos(lo2)*hsin(la2-la1)
return 2 * r * math.Asin(math.Sqrt(h))
}
func distance(ax, ay, bx, by float64, haversine bool) float64 {
if haversine {
return orthoDist(ax, ay, bx, by)
}
return sqrtDist(ax, ay, bx, by)
}
func hsin(theta float64) float64 {
return math.Pow(math.Sin(theta/2), 2)
}