forked from jakevdp/pyDistances
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball_tree.pyx
1612 lines (1342 loc) · 64.3 KB
/
ball_tree.pyx
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Author: Jake Vanderplas <vanderplas@astro.washington.edu>
# License: BSD
# TODO:
# - documentation update with metrics
#
# - currently all metrics are used without precomputed values.
# Allowing precomputed values could speed computation with some metrics.
#
# - KDBound: doesn't work for chebyshev
#
# - correlation function query
#
# Other Thoughts:
# what about using fibonacci heaps to keep track of visited nodes? This is
# fairly easy to try out with the HeapBase abstraction.
"""
=========
Ball Tree
=========
A ball tree is a data object which speeds up nearest neighbor
searches in high dimensions (see scikit-learn neighbors module
documentation for an overview of neighbor trees). There are many
types of ball trees. This package provides a basic implementation
in cython.
Implementation Notes
--------------------
A ball tree can be thought of as a collection of nodes. Each node
stores a centroid, a radius, and the pointers to two child nodes.
* centroid : the centroid of a node is the mean of all the locations
of points within the node
* radius : the radius of a node is the distance from the centroid
to the furthest point in the node.
* subnodes : each node has a maximum of 2 child nodes. The data within
the parent node is divided between the two child nodes.
In a typical tree implementation, nodes may be classes or structures which
are dynamically allocated as needed. This offers flexibility in the number
of nodes, and leads to very straightforward and readable code. It also means
that the tree can be dynamically augmented or pruned with new data, in an
in-line fashion. This approach generally leads to recursive code: upon
construction, the head node constructs its child nodes, the child nodes
construct their child nodes, and so-on.
For an illustration of this sort of approach, refer to slow_ball_tree.py, which
is a python-only implementation designed for readibility rather than speed.
The current package uses a different approach: all node data is stored in
a set of numpy arrays which are pre-allocated. The main advantage of this
approach is that the whole object can be quickly and easily saved to disk
and reconstructed from disk. This also allows for an iterative interface
which gives more control over the heap, and leads to speed. There are a
few disadvantages, however: once the tree is built, augmenting or pruning it
is not as straightforward. Also, the size of the tree must be known from the
start, so there is not as much flexibility in building it.
BallTree Storage
~~~~~~~~~~~~~~~~
The BallTree information is stored using a combination of
"Array of Structures" and "Structure of Arrays" to maximize speed.
Given input data of size ``(n_samples, n_features)``, BallTree computes the
expected number of nodes ``n_nodes`` (see below), and allocates the
following arrays:
* ``data`` : a float array of shape ``(n_samples, n_features)``
This is simply the input data. If the input matrix is well-formed
(contiguous, c-ordered, correct data type) then no copy is needed
* ``idx_array`` : an integer array of size ``n_samples``
This can be thought of as an array of pointers to the data in ``data``.
Rather than shuffling around the data itself, we shuffle around pointers
to the rows in data.
* ``node_centroid_arr`` : a float array of shape ``(n_nodes, n_features)``
This stores the centroid of the data in each node.
* ``node_info_arr`` : a size-``n_nodes`` array of ``NodeInfo`` structures.
This stores information associated with each node. Each ``NodeInfo``
instance has the following attributes:
- ``idx_start``
- ``idx_end`` : ``idx_start`` and ``idx_end`` reference the part of
``idx_array`` which point to the data associated with the node.
The data in node with index ``i_node`` is given by
``data[idx_array[idx_start:idx_end]]``
- ``is_leaf`` : a boolean value which tells whether this node is a leaf:
that is, whether or not it has children.
- ``radius`` : a floating-point value which gives the distance from
the node centroid to the furthest point in the node.
One feature here is that there are no stored pointers from parent nodes to
child nodes and vice-versa. These pointers are implemented implicitly:
For a node with index ``i``, the two children are found at indices
``2 * i + 1`` and ``2 * i + 2``, while the parent is found at index
``floor((i - 1) / 2)``. The root node has no parent.
With this data structure in place, the functionality of the above BallTree
pseudo-code can be implemented in a much more efficient manner.
Most of the data passing done in this code uses raw data pointers.
Using numpy arrays would be preferable for indexing safety, but the
overhead of array slicing and sub-array construction leads to execution
time which is several orders of magnitude slower than the current
implementation.
Priority Queue vs Max-heap
~~~~~~~~~~~~~~~~~~~~~~~~~~
When querying for more than one neighbor, the code must maintain a list of
the current k nearest points. The BallTree code implements this in two ways.
- A priority queue: this is simply a sorted list. When an item is added,
it is inserted in the appropriate location. The cost of the search plus
insert averages O[k].
- A max-heap: this is a binary tree structure arranged such that each node is
greater than its children. The cost of adding an item is O[log(k)].
At the end of the iterations, the results must be sorted: a quicksort is
used, which averages O[k log(k)]. Quicksort has worst-case O[k^2]
performance, but because the input is already structured in a max-heap,
the worst case will not be realized. Thus the sort is a one-time operation
with cost O[k log(k)].
Each insert is performed an average of log(N) times per query, where N is
the number of training points. Because of this, for a single query, the
priority-queue approach costs O[k log(N)], and the max-heap approach costs
O[log(k)log(N)] + O[k log(k)]. Empirical tests show that for sufficiently
large k, the max-heap approach out-performs the priority queue approach by
a factor of a few. In light of these tests, the code uses a priority queue
for k < 5, and a max-heap otherwise.
Memory Allocation
~~~~~~~~~~~~~~~~~
It is desirable to construct a tree in as balanced a way as possible.
Given a training set with n_samples and a user-supplied leaf_size, if
the points in each node are divided as evenly as possible between the
two children, the maximum depth needed so that leaf nodes satisfy
``leaf_size <= n_points <= 2 * leaf_size`` is given by
``n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size)))``
(with the exception of the special case where ``n_samples <= leaf_size``)
For a given number of levels, the number of points in a tree is given by
``n_nodes = 2 ** n_levels - 1``. Both of these results can be shown
by induction. Using them, the correct amount of memory can be pre-allocated
for a given ``n_samples`` and ``leaf_size``.
"""
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport fmax, fmin, fabs
from distmetrics cimport DistanceMetric, DTYPE_t
from distmetrics import DTYPE
# validation function ported from scikit-learn (sklearn.utils.array2d)
def array2d(X, dtype=None, order=None):
"""Returns at least 2-d array with data from X"""
return np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
######################################################################
# global definitions
# type used for indices & counts
# warning: there will be problems if ITYPE is switched to an unsigned type!
ITYPE = np.int32
ctypedef np.int32_t ITYPE_t
# explicitly define infinity
cdef DTYPE_t INF = np.inf
######################################################################
# NodeInfo struct
# used to keep track of node information.
# there is also a centroid for each node: this is kept in a separate
# array for efficiency. This is a hybrid of the "Array of Structures"
# and "Structure of Arrays" styles.
cdef struct NodeInfo:
ITYPE_t idx_start
ITYPE_t idx_end
ITYPE_t is_leaf
DTYPE_t radius # radius is used for BallTree
######################################################################
# newObj function
# this is a helper function for pickling
def newObj(obj):
return obj.__new__(obj)
######################################################################
# Invalid metrics
#
# These are not true metrics (they don't satisfy the triangle inequality)
# so BallTree will not work with them
INVALID_METRICS = ['sqeuclidean', 'correlation', 'pminkowski',
'pwminkowski', 'sqseuclidean', 'sqmahalanobis']
######################################################################
# BinaryTree class.
# This is a base class for tree-based N-point queries
cdef class _BinaryTree(object):
"""Base class for KDTree and BallTree"""
cdef readonly np.ndarray data
cdef np.ndarray idx_array
cdef np.ndarray node_info_arr
cdef np.ndarray node_data_arr1
cdef np.ndarray node_data_arr2
cdef ITYPE_t leaf_size
cdef ITYPE_t n_levels
cdef ITYPE_t n_nodes
cdef DistanceMetric dm
cdef BoundBase bound
cdef HeapBase heap
cdef int n_trims
cdef int n_leaves
cdef int n_splits
def get_stats(self):
return (self.n_trims, self.n_leaves, self.n_splits)
def get_arrays(self):
return (self.data, self.idx_array,
self.node_data_arr1, self.node_data_arr2)
def __cinit__(self):
"""
initialize all arrays to empty. This will prevent memory errors
in rare cases where __init__ is not called
"""
self.data = np.zeros((0,0), dtype=DTYPE)
self.idx_array = np.zeros(0, dtype=ITYPE)
self.node_data_arr1 = np.zeros((0,0), dtype=DTYPE)
self.node_data_arr2 = np.zeros((0,0), dtype=DTYPE)
self.node_info_arr = np.zeros(0, dtype='c')
self.dm = DistanceMetric()
self.bound = BoundBase()
self.heap = HeapBase()
def __init__(self, X, leaf_size=20, metric="minkowski", p=2, **kwargs):
raise ValueError("_BinaryTree cannot be instantiated on its own")
def __init_metric(self, metric, **kwargs):
if isinstance(metric, DistanceMetric):
self.dm = metric
metric = self.dm.metric
else:
self.dm = DistanceMetric(metric, **kwargs)
def __init_common(self, X, leaf_size=20, data1=True, data2=False):
"""Common initialization steps"""
self.data = np.asarray(X, dtype=DTYPE, order='C')
if self.data.size == 0:
raise ValueError("X is an empty array")
if self.data.ndim != 2:
raise ValueError("X should have two dimensions")
if leaf_size < 1:
raise ValueError("leaf_size must be greater than or equal to 1")
self.leaf_size = leaf_size
cdef ITYPE_t n_samples = self.data.shape[0]
cdef ITYPE_t n_features = self.data.shape[1]
# set up dist_metric
if self.dm.learn_params_from_data:
self.dm.set_params_from_data(self.data)
# determine number of levels in the tree, and from this
# the number of nodes in the tree. This results in leaf nodes
# with numbers of points betweeen leaf_size and 2 * leaf_size
# (see module-level doc string for details)
self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1
self.n_nodes = (2 ** self.n_levels) - 1
# allocate arrays for storage
self.idx_array = np.arange(n_samples, dtype=ITYPE)
self.node_info_arr = np.zeros(self.n_nodes * sizeof(NodeInfo),
dtype='c', order='C')
if data1:
self.node_data_arr1 = np.zeros((self.n_nodes, n_features),
dtype=DTYPE, order='C')
if data2:
self.node_data_arr2 = np.zeros((self.n_nodes, n_features),
dtype=DTYPE, order='C')
self._recursive_build(0, 0, n_samples)
def __reduce__(self):
"""reduce method used for pickling"""
return (newObj, (self.__class__,), self.__getstate__())
def __getstate__(self):
"""get state for pickling"""
return (self.data,
self.idx_array,
self.node_data_arr1,
self.node_data_arr2,
self.node_info_arr,
self.leaf_size,
self.n_levels,
self.n_nodes,
self.dm,
self.bound)
def __setstate__(self, state):
"""set state for pickling"""
(self.data,
self.idx_array,
self.node_data_arr1,
self.node_data_arr2,
self.node_info_arr,
self.leaf_size,
self.n_levels,
self.n_nodes,
self.dm,
self.bound) = state
def query(self, X, k=1, return_distance=True, dualtree=False):
"""
query(X, k=1, return_distance=True)
query the Ball Tree for the k nearest neighbors
Parameters
----------
X : array-like, last dimension self.n_features
An array of points to query
k : integer (default = 1)
The number of nearest neighbors to return
return_distance : boolean (default = True)
if True, return a tuple (d,i)
if False, return array i
Returns
-------
i : if return_distance == False
(d, i) : if return_distance == True
d : array of doubles - shape: x.shape[:-1] + (k,)
each entry gives the sorted list of distances to the
neighbors of the corresponding point
i : array of integers - shape: x.shape[:-1] + (k,)
each entry gives the sorted list of indices of
neighbors of the corresponding point
Examples
--------
Query for k-nearest neighbors
# >>> import numpy as np
# >>> np.random.seed(0)
# >>> X = np.random.random((10,3)) # 10 points in 3 dimensions
# >>> ball_tree = BallTree(X, leaf_size=2)
# >>> dist, ind = ball_tree.query(X[0], k=3)
# >>> print ind # indices of 3 closest neighbors
# [0 3 1]
# >>> print dist # distances to 3 closest neighbors
# [ 0. 0.19662693 0.29473397]
"""
cdef ITYPE_t n_neighbors = k
cdef ITYPE_t n_features = self.data.shape[1]
X = array2d(X, dtype=DTYPE, order='C')
if X.shape[-1] != n_features:
raise ValueError("query data dimension must match BallTree "
"data dimension")
if self.data.shape[0] < n_neighbors:
raise ValueError("k must be less than or equal "
"to the number of training points")
# flatten X, and save original shape information
orig_shape = X.shape
X = X.reshape((-1, n_features))
cdef ITYPE_t n_queries = X.shape[0]
# allocate distances and indices for return
cdef np.ndarray distances = np.zeros((X.shape[0], n_neighbors),
dtype=DTYPE)
distances.fill(INF)
cdef np.ndarray idx_array = np.zeros((X.shape[0], n_neighbors),
dtype=ITYPE)
cdef np.ndarray Xarr = X
# define some variables needed for the computation
cdef np.ndarray bounds
cdef ITYPE_t i
cdef DTYPE_t* pt
#cdef DTYPE_t* dist_ptr = <DTYPE_t*> distances.data
cdef DTYPE_t* dist_ptr = <DTYPE_t*> np.PyArray_DATA(distances)
#cdef ITYPE_t* idx_ptr = <ITYPE_t*> idx_array.data
cdef ITYPE_t* idx_ptr = <ITYPE_t*> np.PyArray_DATA(idx_array)
cdef DTYPE_t reduced_dist_LB
# create heap/queue object for holding results
if n_neighbors == 1:
self.heap = OneItemHeap()
elif n_neighbors >= 5:
self.heap = MaxHeap()
else:
self.heap = PriorityQueue()
self.heap.init(dist_ptr, idx_ptr, n_neighbors)
self.n_trims = 0
self.n_leaves = 0
self.n_splits = 0
if dualtree:
# build a tree on query data with the same metric as self
other = self.__class__(X, leaf_size=self.leaf_size,
metric=self.dm,
**self.dm.init_kwargs)
reduced_dist_LB = self.bound.min_rdist_dual(self, 0, other, 0)
# bounds store the current furthest neighbor which is stored
# in each node of the "other" tree. This makes it so that we
# don't need to repeatedly search every point in the node.
bounds = np.empty(other.data.shape[0])
bounds.fill(INF)
self.query_dual_(0, other, 0, n_neighbors,
dist_ptr, idx_ptr, reduced_dist_LB,
#<DTYPE_t*> bounds.data)
<DTYPE_t*> np.PyArray_DATA(bounds))
else:
pt = <DTYPE_t*> np.PyArray_DATA(Xarr)
#pt = <DTYPE_t*> Xarr.data
for i in range(Xarr.shape[0]):
reduced_dist_LB = self.bound.min_rdist(self, 0, pt)
self.query_one_(0, pt, n_neighbors,
dist_ptr, idx_ptr, reduced_dist_LB)
dist_ptr += n_neighbors
idx_ptr += n_neighbors
pt += n_features
dist_ptr = <DTYPE_t*> np.PyArray_DATA(distances)
idx_ptr = <ITYPE_t*> np.PyArray_DATA(idx_array)
#dist_ptr = <DTYPE_t*> distances.data
#idx_ptr = <ITYPE_t*> idx_array.data
for i in range(n_neighbors * n_queries):
dist_ptr[i] = self.dm.reduced_to_dist(dist_ptr[i],
&self.dm.params)
if self.heap.needs_final_sort():
for i in range(n_queries):
sort_dist_idx(dist_ptr, idx_ptr, n_neighbors)
dist_ptr += n_neighbors
idx_ptr += n_neighbors
# deflatten results
if return_distance:
return (distances.reshape((orig_shape[:-1]) + (k,)),
idx_array.reshape((orig_shape[:-1]) + (k,)))
else:
return idx_array.reshape((orig_shape[:-1]) + (k,))
def query_radius(self, X, r, return_distance=False,
int count_only=False, int sort_results=False):
"""
query_radius(self, X, r, return_distance=False,
count_only = False, sort_results=False):
query the Ball Tree for neighbors within a ball of size r
Parameters
----------
X : array-like, last dimension self.dim
An array of points to query
r : distance within which neighbors are returned
r can be a single value, or an array of values of shape
x.shape[:-1] if different radii are desired for each point.
return_distance : boolean (default = False)
if True, return distances to neighbors of each point
if False, return only neighbors
Note that unlike BallTree.query(), setting return_distance=True
adds to the computation time. Not all distances need to be
calculated explicitly for return_distance=False. Results are
not sorted by default: see ``sort_results`` keyword.
count_only : boolean (default = False)
if True, return only the count of points within distance r
if False, return the indices of all points within distance r
If return_distance==True, setting count_only=True will
result in an error.
sort_results : boolean (default = False)
if True, the distances and indices will be sorted before being
returned. If False, the results will not be sorted. If
return_distance == False, setting sort_results = True will
result in an error.
Returns
-------
count : if count_only == True
ind : if count_only == False and return_distance == False
(ind, dist) : if count_only == False and return_distance == True
count : array of integers, shape = X.shape[:-1]
each entry gives the number of neighbors within
a distance r of the corresponding point.
ind : array of objects, shape = X.shape[:-1]
each element is a numpy integer array listing the indices of
neighbors of the corresponding point. Note that unlike
the results of BallTree.query(), the returned neighbors
are not sorted by distance
dist : array of objects, shape = X.shape[:-1]
each element is a numpy double array
listing the distances corresponding to indices in i.
Examples
--------
Query for neighbors in a given radius
# >>> import numpy as np
# >>> np.random.seed(0)
# >>> X = np.random.random((10,3)) # 10 points in 3 dimensions
# >>> ball_tree = BallTree(X, leaf_size=2)
# >>> print ball_tree.query_radius(X[0], r=0.3, count_only=True)
# 3
# >>> ind = ball_tree.query_radius(X[0], r=0.3)
# >>> print ind # indices of neighbors within distance 0.3
# [3 0 1]
"""
if count_only and return_distance:
raise ValueError("count_only and return_distance "
"cannot both be true")
if sort_results and not return_distance:
raise ValueError("return_distance must be True "
"if sort_results is True")
cdef np.ndarray idx_array, idx_array_i, distances, distances_i
cdef np.ndarray pt, count
cdef ITYPE_t count_i = 0
cdef ITYPE_t n_features = self.data.shape[1]
# prepare X for query
X = array2d(X, dtype=DTYPE, order='C')
if X.shape[-1] != self.data.shape[1]:
raise ValueError("query data dimension must match BallTree "
"data dimension")
# prepare r for query
r = np.asarray(r, dtype=DTYPE, order='C')
r = np.atleast_1d(r)
if r.shape == (1,):
r = r[0] * np.ones(X.shape[:-1], dtype=DTYPE)
else:
if r.shape != X.shape[:-1]:
raise ValueError("r must be broadcastable to X.shape")
# flatten X and r for iteration
orig_shape = X.shape
X = X.reshape((-1, X.shape[-1]))
r = r.reshape(-1)
cdef np.ndarray Xarr = X
cdef np.ndarray rarr = r
cdef DTYPE_t* Xdata = <DTYPE_t*> np.PyArray_DATA(Xarr)
cdef DTYPE_t* rdata = <DTYPE_t*> np.PyArray_DATA(rarr)
#cdef DTYPE_t* Xdata = <DTYPE_t*> Xarr.data
#cdef DTYPE_t* rdata = <DTYPE_t*> rarr.data
cdef ITYPE_t i
# prepare variables for iteration
if not count_only:
idx_array = np.zeros(X.shape[0], dtype='object')
if return_distance:
distances = np.zeros(X.shape[0], dtype='object')
idx_array_i = np.zeros(self.data.shape[0], dtype=ITYPE)
distances_i = np.zeros(self.data.shape[0], dtype=DTYPE)
count = np.zeros(X.shape[0], ITYPE)
cdef ITYPE_t* count_data = <ITYPE_t*> np.PyArray_DATA(count)
#cdef ITYPE_t* count_data = <ITYPE_t*> count.data
#TODO: avoid enumerate and repeated allocation of pt slice
for i in range(Xarr.shape[0]):
count_data[i] = self.query_radius_one_(
0,
Xdata + i * n_features,
rdata[i],
<ITYPE_t*> np.PyArray_DATA(idx_array_i),
<DTYPE_t*> np.PyArray_DATA(distances_i),
#<ITYPE_t*> idx_array_i.data,
#<DTYPE_t*> distances_i.data,
0, count_only, return_distance)
if count_only:
pass
else:
if sort_results:
sort_dist_idx(#<DTYPE_t*> distances_i.data,
#<ITYPE_t*> idx_array_i.data,
<DTYPE_t*> np.PyArray_DATA(distances_i),
<ITYPE_t*> np.PyArray_DATA(idx_array_i),
count_data[i])
idx_array[i] = idx_array_i[:count_data[i]].copy()
if return_distance:
distances[i] = distances_i[:count_data[i]].copy()
# deflatten results
if count_only:
return count.reshape(orig_shape[:-1])
elif return_distance:
return (idx_array.reshape(orig_shape[:-1]),
distances.reshape(orig_shape[:-1]))
else:
return idx_array.reshape(orig_shape[:-1])
@cython.cdivision(True)
cdef void _recursive_build(self, ITYPE_t i_node,
ITYPE_t idx_start, ITYPE_t idx_end):
cdef ITYPE_t imax
cdef ITYPE_t n_features = self.data.shape[1]
cdef ITYPE_t n_points = idx_end - idx_start
cdef ITYPE_t n_mid = n_points / 2
cdef ITYPE_t* idx_array = (<ITYPE_t*> np.PyArray_DATA(self.idx_array)
+ idx_start)
cdef DTYPE_t* data = <DTYPE_t*> np.PyArray_DATA(self.data)
#cdef ITYPE_t* idx_array = (<ITYPE_t*> self.idx_array.data + idx_start)
#cdef DTYPE_t* data = <DTYPE_t*> self.data.data
# initialize node data
cdef NodeInfo* node_info = self.bound.init_node(self, i_node,
idx_start, idx_end)
# set up node info
node_info.idx_start = idx_start
node_info.idx_end = idx_end
if 2 * i_node + 1 >= self.n_nodes:
node_info.is_leaf = 1
if idx_end - idx_start > 2 * self.leaf_size:
# this shouldn't happen if our memory allocation is correct
# we'll proactively prevent memory errors, but raise a warning
# saying we're doing so.
import warnings
warnings.warn("Internal: memory layout is flawed: "
"not enough nodes allocated")
elif idx_end - idx_start < 2:
# this shouldn't happen if our memory allocation is correct
# we'll proactively prevent memory errors, but raise a warning
# saying we're doing so.
import warnings
warnings.warn("Internal: memory layout is flawed: "
"too many nodes allocated")
node_info.is_leaf = 1
else: # split node and recursively construct child nodes.
# determine dimension on which to split
node_info.is_leaf = 0
i_max = find_split_dim(data, idx_array, n_features, n_points)
# partition indices along this dimension
partition_indices(data, idx_array, i_max, n_mid,
n_features, n_points)
self._recursive_build(2 * i_node + 1,
idx_start, idx_start + n_mid)
self._recursive_build(2 * i_node + 2,
idx_start + n_mid, idx_end)
cdef void query_one_(self,
ITYPE_t i_node,
DTYPE_t* pt,
ITYPE_t n_neighbors,
DTYPE_t* near_set_dist,
ITYPE_t* near_set_indx,
DTYPE_t reduced_dist_LB):
cdef DTYPE_t* data = <DTYPE_t*> np.PyArray_DATA(self.data)
cdef ITYPE_t* idx_array = <ITYPE_t*> np.PyArray_DATA(self.idx_array)
#cdef DTYPE_t* data = <DTYPE_t*> self.data.data
#cdef ITYPE_t* idx_array = <ITYPE_t*> self.idx_array.data
cdef ITYPE_t n_features = self.data.shape[1]
cdef NodeInfo* node_info = self.node_info(i_node)
cdef DTYPE_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2
cdef ITYPE_t i, i1, i2
# set the values in the heap
self.heap.init(near_set_dist, near_set_indx, n_neighbors)
#------------------------------------------------------------
# Case 1: query point is outside node radius:
# trim it from the query
if reduced_dist_LB > self.heap.largest():
self.n_trims += 1
#------------------------------------------------------------
# Case 2: this is a leaf node. Update set of nearby points
elif node_info.is_leaf:
self.n_leaves += 1
for i in range(node_info.idx_start, node_info.idx_end):
dist_pt = self.rdist(pt, data + n_features * idx_array[i])
if dist_pt < self.heap.largest():
self.heap.insert(dist_pt, idx_array[i])
#------------------------------------------------------------
# Case 3: Node is not a leaf. Recursively query subnodes
# starting with the closest
else:
self.n_splits += 1
i1 = 2 * i_node + 1
i2 = i1 + 1
reduced_dist_LB_1 = self.bound.min_rdist(self, i1, pt)
reduced_dist_LB_2 = self.bound.min_rdist(self, i2, pt)
# recursively query subnodes
if reduced_dist_LB_1 <= reduced_dist_LB_2:
self.query_one_(i1, pt, n_neighbors, near_set_dist,
near_set_indx, reduced_dist_LB_1)
self.query_one_(i2, pt, n_neighbors, near_set_dist,
near_set_indx, reduced_dist_LB_2)
else:
self.query_one_(i2, pt, n_neighbors, near_set_dist,
near_set_indx, reduced_dist_LB_2)
self.query_one_(i1, pt, n_neighbors, near_set_dist,
near_set_indx, reduced_dist_LB_1)
cdef void query_dual_(self,
ITYPE_t i_node1,
_BinaryTree other,
ITYPE_t i_node2,
ITYPE_t n_neighbors,
DTYPE_t* near_set_dist,
ITYPE_t* near_set_indx,
DTYPE_t reduced_dist_LB,
DTYPE_t* bounds):
cdef ITYPE_t n_features = self.data.shape[1]
cdef NodeInfo* node_info1 = self.node_info(i_node1)
cdef NodeInfo* node_info2 = other.node_info(i_node2)
#cdef DTYPE_t* data1 = <DTYPE_t*> self.data.data
#cdef DTYPE_t* data2 = <DTYPE_t*> other.data.data
cdef DTYPE_t* data1 = <DTYPE_t*> np.PyArray_DATA(self.data)
cdef DTYPE_t* data2 = <DTYPE_t*> np.PyArray_DATA(other.data)
#cdef ITYPE_t* idx_array1 = <ITYPE_t*> self.idx_array.data
#cdef ITYPE_t* idx_array2 = <ITYPE_t*> other.idx_array.data
cdef ITYPE_t* idx_array1 = <ITYPE_t*> np.PyArray_DATA(self.idx_array)
cdef ITYPE_t* idx_array2 = <ITYPE_t*> np.PyArray_DATA(other.idx_array)
cdef DTYPE_t dist_pt, reduced_dist_LB1, reduced_dist_LB2
cdef ITYPE_t i1, i2
#------------------------------------------------------------
# Case 1: nodes are further apart than the current bound:
# trim both from the query
if reduced_dist_LB > bounds[i_node2]:
pass
#------------------------------------------------------------
# Case 2: both nodes are leaves:
# do a brute-force search comparing all pairs
elif node_info1.is_leaf and node_info2.is_leaf:
bounds[i_node2] = -1
for i2 in range(node_info2.idx_start, node_info2.idx_end):
self.heap.init(near_set_dist + idx_array2[i2] * n_neighbors,
near_set_indx + idx_array2[i2] * n_neighbors,
n_neighbors)
if self.heap.largest() <= reduced_dist_LB:
continue
for i1 in range(node_info1.idx_start, node_info1.idx_end):
dist_pt = self.rdist(data1 + n_features * idx_array1[i1],
data2 + n_features * idx_array2[i2])
if dist_pt < self.heap.largest():
self.heap.insert(dist_pt, idx_array1[i1])
# keep track of node bound
bounds[i_node2] = fmax(bounds[i_node2], self.heap.largest())
#------------------------------------------------------------
# Case 3a: node 1 is a leaf: split node 2 and recursively
# query, starting with the nearest node
elif node_info1.is_leaf:
reduced_dist_LB1 = self.bound.min_rdist_dual(self, i_node1,
other, 2 * i_node2 + 1)
reduced_dist_LB2 = self.bound.min_rdist_dual(self, i_node1,
other, 2 * i_node2 + 2)
if reduced_dist_LB1 < reduced_dist_LB2:
self.query_dual_(i_node1, other, 2 * i_node2 + 1, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
self.query_dual_(i_node1, other, 2 * i_node2 + 2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
else:
self.query_dual_(i_node1, other, 2 * i_node2 + 2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
self.query_dual_(i_node1, other, 2 * i_node2 + 1, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
# update node bound information
bounds[i_node2] = fmax(bounds[2 * i_node2 + 1],
bounds[2 * i_node2 + 2])
#------------------------------------------------------------
# Case 3b: node 2 is a leaf: split node 1 and recursively
# query, starting with the nearest node
elif node_info2.is_leaf:
reduced_dist_LB1 = self.bound.min_rdist_dual(self, 2 * i_node1 + 1,
other, i_node2)
reduced_dist_LB2 = self.bound.min_rdist_dual(self, 2 * i_node1 + 2,
other, i_node2)
if reduced_dist_LB1 < reduced_dist_LB2:
self.query_dual_(2 * i_node1 + 1, other, i_node2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
self.query_dual_(2 * i_node1 + 2, other, i_node2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
else:
self.query_dual_(2 * i_node1 + 2, other, i_node2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
self.query_dual_(2 * i_node1 + 1, other, i_node2, n_neighbors,
near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
#------------------------------------------------------------
# Case 4: neither node is a leaf:
# split both and recursively query all four pairs
else:
reduced_dist_LB1 = self.bound.min_rdist_dual(self, 2 * i_node1 + 1,
other, 2 * i_node2 + 1)
reduced_dist_LB2 = self.bound.min_rdist_dual(self, 2 * i_node1 + 2,
other, 2 * i_node2 + 1)
if reduced_dist_LB1 < reduced_dist_LB2:
self.query_dual_(2 * i_node1 + 1, other, 2 * i_node2 + 1,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
self.query_dual_(2 * i_node1 + 2, other, 2 * i_node2 + 1,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
else:
self.query_dual_(2 * i_node1 + 2, other, 2 * i_node2 + 1,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
self.query_dual_(2 * i_node1 + 1, other, 2 * i_node2 + 1,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
reduced_dist_LB1 = self.bound.min_rdist_dual(self, 2 * i_node1 + 1,
other, 2 * i_node2 + 2)
reduced_dist_LB2 = self.bound.min_rdist_dual(self, 2 * i_node1 + 2,
other, 2 * i_node2 + 2)
if reduced_dist_LB1 < reduced_dist_LB2:
self.query_dual_(2 * i_node1 + 1, other, 2 * i_node2 + 2,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
self.query_dual_(2 * i_node1 + 2, other, 2 * i_node2 + 2,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
else:
self.query_dual_(2 * i_node1 + 2, other, 2 * i_node2 + 2,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB2, bounds)
self.query_dual_(2 * i_node1 + 1, other, 2 * i_node2 + 2,
n_neighbors, near_set_dist, near_set_indx,
reduced_dist_LB1, bounds)
# update node bound information
bounds[i_node2] = fmax(bounds[2 * i_node2 + 1],
bounds[2 * i_node2 + 2])
cdef ITYPE_t query_radius_one_(self,
ITYPE_t i_node,
DTYPE_t* pt, DTYPE_t r,
ITYPE_t* indices,
DTYPE_t* distances,
ITYPE_t count,
int count_only,
int return_distance):
#cdef DTYPE_t* data = <DTYPE_t*> self.data.data
#cdef ITYPE_t* idx_array = <ITYPE_t*> self.idx_array.data
cdef DTYPE_t* data = <DTYPE_t*> np.PyArray_DATA(self.data)
cdef ITYPE_t* idx_array = <ITYPE_t*> np.PyArray_DATA(self.idx_array)
cdef ITYPE_t n_features = self.data.shape[1]
cdef NodeInfo* node_info = self.node_info(i_node)
cdef ITYPE_t i
cdef DTYPE_t reduced_r
cdef DTYPE_t dist_pt, dist_LB, dist_UB
self.bound.minmax_dist(self, i_node, pt, &dist_LB, &dist_UB)
#------------------------------------------------------------
# Case 1: all node points are outside distance r.
# prune this branch.
if dist_LB > r:
pass
#------------------------------------------------------------
# Case 2: all node points are within distance r
# add all points to neighbors
elif dist_UB <= r:
if count_only:
count += (node_info.idx_end - node_info.idx_start)
else:
for i in range(node_info.idx_start, node_info.idx_end):
if (count < 0) or (count >= self.data.shape[0]):
raise ValueError("count too big")
indices[count] = idx_array[i]
if return_distance:
distances[count] = self.dist(pt, (data + n_features
* idx_array[i]))
count += 1
#------------------------------------------------------------
# Case 3: this is a leaf node. Go through all points to
# determine if they fall within radius
elif node_info.is_leaf:
reduced_r = self.dm.dist_to_reduced(r, &self.dm.params)
for i in range(node_info.idx_start, node_info.idx_end):
dist_pt = self.rdist(pt, (data + n_features
* idx_array[i]))
if dist_pt <= reduced_r:
if (count < 0) or (count >= self.data.shape[0]):
raise ValueError("Fatal: count out of range")
if count_only:
pass
else:
indices[count] = idx_array[i]
if return_distance:
distances[count] = self.dm.reduced_to_dist(
dist_pt, &self.dm.params)
count += 1
#------------------------------------------------------------
# Case 4: Node is not a leaf. Recursively query subnodes
else:
count = self.query_radius_one_(2 * i_node + 1, pt, r,
indices, distances, count,
count_only, return_distance)
count = self.query_radius_one_(2 * i_node + 2, pt, r,
indices, distances, count,
count_only, return_distance)
return count
cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2):
return self.dm.dfunc(x1, x2, self.data.shape[1],
&self.dm.params, -1, -1)
cdef DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2):
return self.dm.reduced_dfunc(x1, x2, self.data.shape[1],
&self.dm.params, -1, -1)
cdef NodeInfo* node_info(self, ITYPE_t i_node):
return <NodeInfo*> np.PyArray_DATA(self.node_info_arr) + i_node
#return <NodeInfo*> self.node_info_arr.data + i_node
cdef DTYPE_t* node_data1(self, ITYPE_t i_node):
return (<DTYPE_t*> np.PyArray_DATA(self.node_data_arr1)
+ i_node * self.node_data_arr1.shape[1])
#return (<DTYPE_t*> self.node_data_arr1.data
# + i_node * self.node_data_arr1.shape[1])
cdef DTYPE_t* node_data2(self, ITYPE_t i_node):
return (<DTYPE_t*> np.PyArray_DATA(self.node_data_arr2)
+ i_node * self.node_data_arr2.shape[1])
#return (<DTYPE_t*> self.node_data_arr2.data
# + i_node * self.node_data_arr2.shape[1])
cdef class BallTree(_BinaryTree):
"""
Ball Tree for fast nearest-neighbor searches :
BallTree(X, leaf_size=20, p=2.0)
Parameters
----------
X : array-like, shape = [n_samples, n_features]
n_samples is the number of points in the data set, and
n_features is the dimension of the parameter space.