forked from scipy/scipy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ckdtree.pyx
1542 lines (1259 loc) · 53.3 KB
/
ckdtree.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
# Copyright Anne M. Archibald 2008
# Additional contributions by Patrick Varilly and Sturla Molden 2012
# Revision by Sturla Molden 2015
# Balanced kd-tree construction written by Jake Vanderplas for scikit-learn
# Released under the scipy license
# distutils: language = c++
from __future__ import absolute_import
import numpy as np
import scipy.sparse
cimport numpy as np
from numpy.math cimport INFINITY
from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
from libc.string cimport memset, memcpy
from libcpp.vector cimport vector
from libcpp.algorithm cimport sort
cimport cython
from multiprocessing import cpu_count
import threading
cdef extern from "<limits.h>":
long LONG_MAX
cdef int number_of_processors = cpu_count()
__all__ = ['cKDTree']
cdef extern from *:
int NPY_LIKELY(int)
int NPY_UNLIKELY(int)
# C++ implementations
# ===================
cdef extern from "ckdtree_decl.h":
int ckdtree_isinf(np.float64_t x) nogil
struct ckdtreenode:
np.intp_t split_dim
np.intp_t children
np.float64_t split
np.intp_t start_idx
np.intp_t end_idx
ckdtreenode *less
ckdtreenode *greater
np.intp_t _less
np.intp_t _greater
struct ckdtree:
vector[ckdtreenode] *tree_buffer
ckdtreenode *ctree
np.float64_t *raw_data
np.intp_t n
np.intp_t m
np.intp_t leafsize
np.float64_t *raw_maxes
np.float64_t *raw_mins
np.intp_t *raw_indices
np.float64_t *raw_boxsize_data
np.intp_t size
# External build and query methods in C++.
int build_ckdtree(ckdtree *self,
np.intp_t start_idx,
np.intp_t end_idx,
np.float64_t *maxes,
np.float64_t *mins,
int _median,
int _compact) nogil except +
int build_weights(ckdtree *self,
np.float64_t *node_weights,
np.float64_t *weights) nogil except +
int query_knn(const ckdtree *self,
np.float64_t *dd,
np.intp_t *ii,
const np.float64_t *xx,
const np.intp_t n,
const np.intp_t *k,
const np.intp_t nk,
const np.intp_t kmax,
const np.float64_t eps,
const np.float64_t p,
const np.float64_t distance_upper_bound) nogil except +
int query_pairs(const ckdtree *self,
const np.float64_t r,
const np.float64_t p,
const np.float64_t eps,
vector[ordered_pair] *results) nogil except +
int count_neighbors_unweighted(const ckdtree *self,
const ckdtree *other,
np.intp_t n_queries,
np.float64_t *real_r,
np.intp_t *results,
const np.float64_t p,
int cumulative) nogil except +
int count_neighbors_weighted(const ckdtree *self,
const ckdtree *other,
np.float64_t *self_weights,
np.float64_t *other_weights,
np.float64_t *self_node_weights,
np.float64_t *other_node_weights,
np.intp_t n_queries,
np.float64_t *real_r,
np.float64_t *results,
const np.float64_t p,
int cumulative) nogil except +
int query_ball_point(const ckdtree *self,
const np.float64_t *x,
const np.float64_t *r,
const np.float64_t p,
const np.float64_t eps,
const np.intp_t n_queries,
vector[np.intp_t] **results,
const int return_length) nogil except +
int query_ball_tree(const ckdtree *self,
const ckdtree *other,
const np.float64_t r,
const np.float64_t p,
const np.float64_t eps,
vector[np.intp_t] **results) nogil except +
int sparse_distance_matrix(const ckdtree *self,
const ckdtree *other,
const np.float64_t p,
const np.float64_t max_distance,
vector[coo_entry] *results) nogil except +
# C++ helper functions
# ====================
cdef extern from "coo_entries.h":
struct coo_entry:
np.intp_t i
np.intp_t j
np.float64_t v
cdef extern from "ordered_pair.h":
struct ordered_pair:
np.intp_t i
np.intp_t j
# coo_entry wrapper
# =================
cdef class coo_entries:
cdef:
readonly object __array_interface__
vector[coo_entry] *buf
def __cinit__(coo_entries self):
self.buf = NULL
def __init__(coo_entries self):
self.buf = new vector[coo_entry]()
def __dealloc__(coo_entries self):
if self.buf != NULL:
del self.buf
# The methods ndarray, dict, coo_matrix, and dok_matrix must only
# be called after the buffer is filled with coo_entry data. This
# is because std::vector can reallocate its internal buffer when
# push_back is called.
def ndarray(coo_entries self):
cdef:
coo_entry *pr
np.uintp_t uintptr
np.intp_t n
_dtype = [('i',np.intp),('j',np.intp),('v',np.float64)]
res_dtype = np.dtype(_dtype, align = True)
n = <np.intp_t> self.buf.size()
if NPY_LIKELY(n > 0):
pr = self.buf.data()
uintptr = <np.uintp_t> (<void*> pr)
dtype = np.dtype(np.uint8)
self.__array_interface__ = dict(
data = (uintptr, False),
descr = dtype.descr,
shape = (n*sizeof(coo_entry),),
strides = (dtype.itemsize,),
typestr = dtype.str,
version = 3,
)
return np.asarray(self).view(dtype=res_dtype)
else:
return np.empty(shape=(0,), dtype=res_dtype)
def dict(coo_entries self):
cdef:
np.intp_t i, j, k, n
np.float64_t v
coo_entry *pr
dict res_dict
n = <np.intp_t> self.buf.size()
if NPY_LIKELY(n > 0):
pr = self.buf.data()
res_dict = dict()
for k in range(n):
i = pr[k].i
j = pr[k].j
v = pr[k].v
res_dict[(i,j)] = v
return res_dict
else:
return {}
def coo_matrix(coo_entries self, m, n):
res_arr = self.ndarray()
return scipy.sparse.coo_matrix(
(res_arr['v'], (res_arr['i'], res_arr['j'])),
shape=(m, n))
def dok_matrix(coo_entries self, m, n):
return self.coo_matrix(m,n).todok()
# ordered_pair wrapper
# ====================
cdef class ordered_pairs:
cdef:
readonly object __array_interface__
vector[ordered_pair] *buf
def __cinit__(ordered_pairs self):
self.buf = NULL
def __init__(ordered_pairs self):
self.buf = new vector[ordered_pair]()
def __dealloc__(ordered_pairs self):
if self.buf != NULL:
del self.buf
# The methods ndarray and set must only be called after the buffer
# is filled with ordered_pair data.
def ndarray(ordered_pairs self):
cdef:
ordered_pair *pr
np.uintp_t uintptr
np.intp_t n
n = <np.intp_t> self.buf.size()
if NPY_LIKELY(n > 0):
pr = self.buf.data()
uintptr = <np.uintp_t> (<void*> pr)
dtype = np.dtype(np.intp)
self.__array_interface__ = dict(
data = (uintptr, False),
descr = dtype.descr,
shape = (n,2),
strides = (2*dtype.itemsize,dtype.itemsize),
typestr = dtype.str,
version = 3,
)
return np.asarray(self)
else:
return np.empty(shape=(0,2), dtype=np.intp)
def set(ordered_pairs self):
cdef:
ordered_pair *pair
np.intp_t i, n
set results
results = set()
pair = self.buf.data()
n = <np.intp_t> self.buf.size()
if sizeof(long) < sizeof(np.intp_t):
# Needed for Python 2.x on Win64
for i in range(n):
results.add((int(pair.i), int(pair.j)))
pair += 1
else:
# other platforms
for i in range(n):
results.add((pair.i, pair.j))
pair += 1
return results
# Tree structure exposed to Python
# ================================
cdef class cKDTreeNode:
"""
class cKDTreeNode
This class exposes a Python view of a node in the cKDTree object.
All attributes are read-only.
Attributes
----------
level : int
The depth of the node. 0 is the level of the root node.
split_dim : int
The dimension along which this node is split. If this value is -1
the node is a leafnode in the kd-tree. Leafnodes are not split further
and scanned by brute force.
split : float
The value used to separate split this node. Points with value >= split
in the split_dim dimension are sorted to the 'greater' subnode
whereas those with value < split are sorted to the 'lesser' subnode.
children : int
The number of data points sorted to this node.
data_points : ndarray of float64
An array with the data points sorted to this node.
indices : ndarray of intp
An array with the indices of the data points sorted to this node. The
indices refer to the position in the data set used to construct the
kd-tree.
lesser : cKDTreeNode or None
Subnode with the 'lesser' data points. This attribute is None for
leafnodes.
greater : cKDTreeNode or None
Subnode with the 'greater' data points. This attribute is None for
leafnodes.
"""
cdef:
readonly np.intp_t level
readonly np.intp_t split_dim
readonly np.intp_t children
readonly np.float64_t split
ckdtreenode *_node
np.ndarray _data
np.ndarray _indices
cdef void _setup(cKDTreeNode self):
self.split_dim = self._node.split_dim
self.children = self._node.children
self.split = self._node.split
property data_points:
def __get__(cKDTreeNode self):
return self._data[self.indices,:]
property indices:
def __get__(cKDTreeNode self):
cdef np.intp_t i, start, stop
if self.split_dim == -1:
start = self._node.start_idx
stop = self._node.end_idx
return self._indices[start:stop]
else:
return np.hstack([self.lesser.indices,
self.greater.indices])
property lesser:
def __get__(cKDTreeNode self):
if self.split_dim == -1:
return None
else:
n = cKDTreeNode()
n._node = self._node.less
n._data = self._data
n._indices = self._indices
n.level = self.level + 1
n._setup()
return n
property greater:
def __get__(cKDTreeNode self):
if self.split_dim == -1:
return None
else:
n = cKDTreeNode()
n._node = self._node.greater
n._data = self._data
n._indices = self._indices
n.level = self.level + 1
n._setup()
return n
# Main cKDTree class
# ==================
cdef class cKDTree:
"""
cKDTree(data, leafsize=16, compact_nodes=True, copy_data=False,
balanced_tree=True, boxsize=None)
kd-tree for quick nearest-neighbor lookup
This class provides an index into a set of k-dimensional points
which can be used to rapidly look up the nearest neighbors of any
point.
The algorithm used is described in Maneewongvatana and Mount 1999.
The general idea is that the kd-tree is a binary trie, each of whose
nodes represents an axis-aligned hyperrectangle. Each node specifies
an axis and splits the set of points based on whether their coordinate
along that axis is greater than or less than a particular value.
During construction, the axis and splitting point are chosen by the
"sliding midpoint" rule, which ensures that the cells do not all
become long and thin.
The tree can be queried for the r closest neighbors of any given point
(optionally returning only those within some maximum distance of the
point). It can also be queried, with a substantial gain in efficiency,
for the r approximate closest neighbors.
For large dimensions (20 is already large) do not expect this to run
significantly faster than brute force. High-dimensional nearest-neighbor
queries are a substantial open problem in computer science.
Parameters
----------
data : array_like, shape (n,m)
The n data points of dimension m to be indexed. This array is
not copied unless this is necessary to produce a contiguous
array of doubles, and so modifying this data will result in
bogus results. The data are also copied if the kd-tree is built
with copy_data=True.
leafsize : positive int, optional
The number of points at which the algorithm switches over to
brute-force. Default: 16.
compact_nodes : bool, optional
If True, the kd-tree is built to shrink the hyperrectangles to
the actual data range. This usually gives a more compact tree that
is robust against degenerated input data and gives faster queries
at the expense of longer build time. Default: True.
copy_data : bool, optional
If True the data is always copied to protect the kd-tree against
data corruption. Default: False.
balanced_tree : bool, optional
If True, the median is used to split the hyperrectangles instead of
the midpoint. This usually gives a more compact tree and
faster queries at the expense of longer build time. Default: True.
boxsize : array_like or scalar, optional
Apply a m-d toroidal topology to the KDTree.. The topology is generated
by :math:`x_i + n_i L_i` where :math:`n_i` are integers and :math:`L_i`
is the boxsize along i-th dimension. The input data shall be wrapped
into :math:`[0, L_i)`. A ValueError is raised if any of the data is
outside of this bound.
Attributes
----------
data : ndarray, shape (n,m)
The n data points of dimension m to be indexed. This array is
not copied unless this is necessary to produce a contiguous
array of doubles. The data are also copied if the kd-tree is built
with `copy_data=True`.
leafsize : positive int
The number of points at which the algorithm switches over to
brute-force.
m : int
The dimension of a single data-point.
n : int
The number of data points.
maxes : ndarray, shape (m,)
The maximum value in each dimension of the n data points.
mins : ndarray, shape (m,)
The minimum value in each dimension of the n data points.
tree : object, class cKDTreeNode
This class exposes a Python view of the root node in the cKDTree object.
size : int
The number of nodes in the tree.
See Also
--------
KDTree : Implementation of `cKDTree` in pure Python
"""
cdef:
ckdtree * cself
readonly cKDTreeNode tree
readonly np.ndarray data
readonly np.ndarray maxes
readonly np.ndarray mins
readonly np.ndarray indices
readonly object boxsize
np.ndarray boxsize_data
property n:
def __get__(self): return self.cself.n
property m:
def __get__(self): return self.cself.m
property leafsize:
def __get__(self): return self.cself.leafsize
property size:
def __get__(self): return self.cself.size
def __cinit__(cKDTree self):
self.cself = <ckdtree * > PyMem_Malloc(sizeof(ckdtree))
self.cself.tree_buffer = NULL
def __init__(cKDTree self, data, np.intp_t leafsize=16, compact_nodes=True,
copy_data=False, balanced_tree=True, boxsize=None):
cdef:
np.float64_t [::1] tmpmaxes, tmpmins
np.float64_t *ptmpmaxes
np.float64_t *ptmpmins
ckdtree *cself = self.cself
int compact, median
data = np.array(data, order='C', copy=copy_data, dtype=np.float64)
if data.ndim != 2:
raise ValueError("data must be 2 dimensions")
self.data = data
cself.n = data.shape[0]
cself.m = data.shape[1]
cself.leafsize = leafsize
if leafsize<1:
raise ValueError("leafsize must be at least 1")
if boxsize is None:
self.boxsize = None
self.boxsize_data = None
else:
self.boxsize_data = np.empty(2 * self.m, dtype=np.float64)
boxsize = np.float64(np.broadcast_to(boxsize, self.m))
self.boxsize_data[:self.m] = boxsize
self.boxsize_data[self.m:] = 0.5 * boxsize
self.boxsize = boxsize
periodic_mask = self.boxsize > 0
if ((self.data >= self.boxsize[None, :])[:, periodic_mask]).any():
raise ValueError("Some input data are greater than the size of the periodic box.")
if ((self.data < 0)[:, periodic_mask]).any():
raise ValueError("Negative input data are outside of the periodic box.")
self.maxes = np.ascontiguousarray(
np.amax(self.data, axis=0) if self.n > 0 else np.zeros(self.m),
dtype=np.float64)
self.mins = np.ascontiguousarray(
np.amin(self.data,axis=0) if self.n > 0 else np.zeros(self.m),
dtype=np.float64)
self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.intp))
self._pre_init()
compact = 1 if compact_nodes else 0
median = 1 if balanced_tree else 0
cself.tree_buffer = new vector[ckdtreenode]()
tmpmaxes = np.copy(self.maxes)
tmpmins = np.copy(self.mins)
ptmpmaxes = &tmpmaxes[0]
ptmpmins = &tmpmins[0]
with nogil:
build_ckdtree(cself, 0, cself.n, ptmpmaxes, ptmpmins, median, compact)
# set up the tree structure pointers
self._post_init()
cdef _pre_init(cKDTree self):
cself = self.cself
# finalize the pointers from array attributes
cself.raw_data = <np.float64_t*> np.PyArray_DATA(self.data)
cself.raw_maxes = <np.float64_t*> np.PyArray_DATA(self.maxes)
cself.raw_mins = <np.float64_t*> np.PyArray_DATA(self.mins)
cself.raw_indices = <np.intp_t*> np.PyArray_DATA(self.indices)
if self.boxsize_data is not None:
cself.raw_boxsize_data = <np.float64_t*>np.PyArray_DATA(self.boxsize_data)
else:
cself.raw_boxsize_data = NULL
cdef _post_init(cKDTree self):
cself = self.cself
# finalize the tree points, this calls _post_init_traverse
cself.ctree = cself.tree_buffer.data()
# set the size attribute after tree_buffer is built
cself.size = cself.tree_buffer.size()
self._post_init_traverse(cself.ctree)
# make the tree viewable from Python
self.tree = cKDTreeNode()
self.tree._node = cself.ctree
self.tree._data = self.data
self.tree._indices = self.indices
self.tree.level = 0
self.tree._setup()
cdef _post_init_traverse(cKDTree self, ckdtreenode *node):
cself = self.cself
# recurse the tree and re-initialize
# "less" and "greater" fields
if node.split_dim == -1:
# leafnode
node.less = NULL
node.greater = NULL
else:
node.less = cself.ctree + node._less
node.greater = cself.ctree + node._greater
self._post_init_traverse(node.less)
self._post_init_traverse(node.greater)
def __dealloc__(cKDTree self):
cself = self.cself
if cself.tree_buffer != NULL:
del cself.tree_buffer
PyMem_Free(cself)
# -----
# query
# -----
@cython.boundscheck(False)
def query(cKDTree self, object x, object k=1, np.float64_t eps=0,
np.float64_t p=2, np.float64_t distance_upper_bound=INFINITY,
np.intp_t n_jobs=1):
"""
query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf, n_jobs=1)
Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : list of integer or integer
The list of k-th nearest neighbors to return. If k is an
integer it is treated as a list of [1, ... k] (range(1, k+1)).
Note that the counting starts from 1.
eps : non-negative float
Return approximate nearest neighbors; the k-th returned value
is guaranteed to be no further than (1+eps) times the
distance to the real k-th nearest neighbor.
p : float, 1<=p<=infinity
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
A finite large p may cause a ValueError if overflow can occur.
distance_upper_bound : nonnegative float
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
n_jobs : int, optional
Number of jobs to schedule for parallel processing. If -1 is given
all processors are used. Default: 1.
Returns
-------
d : array of floats
The distances to the nearest neighbors.
If ``x`` has shape ``tuple+(self.m,)``, then ``d`` has shape ``tuple+(k,)``.
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with infinite distances.
i : ndarray of ints
The locations of the neighbors in ``self.data``.
If ``x`` has shape ``tuple+(self.m,)``, then ``i`` has shape ``tuple+(k,)``.
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with ``self.n``.
Notes
-----
If the KD-Tree is periodic, the position ``x`` is wrapped into the
box.
When the input k is a list, a query for arange(max(k)) is performed, but
only columns that store the requested values of k are preserved. This is
implemented in a manner that reduces memory usage.
Examples
--------
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> x, y = np.mgrid[0:5, 2:8]
>>> tree = cKDTree(np.c_[x.ravel(), y.ravel()])
To query the nearest neighbours and return squeezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=1)
>>> print(dd, ii)
[2. 0.14142136] [ 0 13]
To query the nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[1])
>>> print(dd, ii)
[[2. ]
[0.14142136]] [[ 0]
[13]]
To query the second nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[2])
>>> print(dd, ii)
[[2.23606798]
[0.90553851]] [[ 6]
[12]]
To query the first and second nearest neighbours, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=2)
>>> print(dd, ii)
[[2. 2.23606798]
[0.14142136 0.90553851]] [[ 0 6]
[13 12]]
or, be more specific
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[1, 2])
>>> print(dd, ii)
[[2. 2.23606798]
[0.14142136 0.90553851]] [[ 0 6]
[13 12]]
"""
cdef:
np.intp_t n, i, j
int overflown
const np.float64_t [:, ::1] xx
xshape = np.shape(x)
if len(xshape) == 0 or xshape[-1] != self.m:
raise ValueError("x must consist of vectors of length %d but "
"has shape %s" % (int(self.m), xshape))
n = <np.intp_t> np.prod(xshape[:-1])
xx = np.ascontiguousarray(x, dtype=np.float64).reshape(n, self.m)
if p < 1:
raise ValueError("Only p-norms with 1<=p<=infinity permitted")
if len(xshape) == 1:
single = True
else:
single = False
nearest = False
if np.isscalar(k):
if k == 1:
nearest = True
k = np.arange(1, k + 1)
retshape = xshape[:-1]
# The C++ function touches all dd and ii entries,
# setting the missing values.
cdef:
np.float64_t [:, ::1] dd = np.empty((n,len(k)),dtype=np.float64)
np.intp_t [:, ::1] ii = np.empty((n,len(k)),dtype=np.intp)
np.intp_t [::1] kk = np.array(k, dtype=np.intp)
np.intp_t kmax = np.max(k)
# Do the query in an external C++ function.
def _thread_func(np.intp_t start, np.intp_t stop):
cdef:
np.float64_t *pdd = &dd[start,0]
np.intp_t *pii = &ii[start,0]
const np.float64_t *pxx = &xx[start,0]
np.intp_t *pkk = &kk[0]
with nogil:
query_knn(self.cself, pdd, pii,
pxx, stop-start, pkk, kk.shape[0], kmax, eps, p, distance_upper_bound)
if (n_jobs == -1):
n_jobs = number_of_processors
_run_threads(_thread_func, n, n_jobs)
# massage the output in conformabity to the documented behavior
if sizeof(long) < sizeof(np.intp_t):
# ... e.g. Windows 64
overflown = False
for i in range(n):
for j in range(len(k)):
if ii[i,j] > <np.intp_t>LONG_MAX:
# C long overlow, return array of dtype=np.int_p
overflown = True
break
if overflown:
break
if overflown:
ddret = np.reshape(dd,retshape+(len(k),))
iiret = np.reshape(ii,retshape+(len(k),))
else:
ddret = np.reshape(dd,retshape+(len(k),))
iiret = np.reshape(ii,retshape+(len(k),)).astype(int)
else:
# ... most other platforms
ddret = np.reshape(dd,retshape+(len(k),))
iiret = np.reshape(ii,retshape+(len(k),))
if nearest:
ddret = ddret[..., 0]
iiret = iiret[..., 0]
# the only case where we return a python scalar
if single:
ddret = float(ddret)
iiret = int(iiret)
return ddret, iiret
# ----------------
# query_ball_point
# ----------------
def query_ball_point(cKDTree self, object x, object r,
np.float64_t p=2., np.float64_t eps=0, n_jobs=1,
return_sorted=None,
return_length=False):
"""
query_ball_point(self, x, r, p=2., eps=0)
Find all points within distance r of point(s) x.
Parameters
----------
x : array_like, shape tuple + (self.m,)
The point or points to search for neighbors of.
r : array_like, float
The radius of points to return, shall broadcast to the length of x.
p : float, optional
Which Minkowski p-norm to use. Should be in the range [1, inf].
A finite large p may cause a ValueError if overflow can occur.
eps : nonnegative float, optional
Approximate search. Branches of the tree are not explored if their
nearest points are further than ``r / (1 + eps)``, and branches are
added in bulk if their furthest points are nearer than
``r * (1 + eps)``.
n_jobs : int, optional
Number of jobs to schedule for parallel processing. If -1 is given
all processors are used. Default: 1.
return_sorted : bool, optional
Sorts returned indicies if True and does not sort them if False. If
None, does not sort single point queries, but does sort
multi-point queries which was the behavior before this option
was added.
.. versionadded:: 1.2.0
return_length: bool, optional
Return the number of points inside the radius instead of a list
of the indices.
.. versionadded:: 1.3.0
Returns
-------
results : list or array of lists
If `x` is a single point, returns a list of the indices of the
neighbors of `x`. If `x` is an array of points, returns an object
array of shape tuple containing lists of neighbors.
Notes
-----
If you have many points whose neighbors you want to find, you may save
substantial amounts of time by putting them in a cKDTree and using
query_ball_tree.
Examples
--------
>>> from scipy import spatial
>>> x, y = np.mgrid[0:4, 0:4]
>>> points = np.c_[x.ravel(), y.ravel()]
>>> tree = spatial.cKDTree(points)
>>> tree.query_ball_point([2, 0], 1)
[4, 8, 9, 12]
"""
cdef:
const np.float64_t[::1] vrr
const np.float64_t[:, ::1] vxx
object[::1] vout
np.intp_t[::1] vlen
list tmp
np.intp_t i, j, n, m
np.intp_t xndim
xshape = np.shape(x)
if xshape[-1] != self.m:
raise ValueError("Searching for a %d-dimensional point in a "
"%d-dimensional KDTree" %
(int(xshape[-1]), int(self.m)))
vxx = np.ascontiguousarray(x, dtype=np.float64).reshape(-1, self.m)
vrr = np.ascontiguousarray(np.broadcast_to(r, xshape[:-1]), dtype=np.float64).reshape(-1)
retshape = xshape[:-1]
# scalar query if xndim == 1
xndim = len(xshape)
# allocate an array of std::vector<npy_intp>
n = np.prod(retshape)
if return_length:
result = np.empty(retshape, dtype=np.intp)
vlen = result.reshape(-1)
else:
result = np.empty(retshape, dtype=object)
vout = result.reshape(-1)
def _thread_func(np.intp_t start, np.intp_t stop):
cdef:
vector[np.intp_t] **vvres
np.intp_t i
np.intp_t *cur
int rlen
const np.float64_t *pvxx
const np.float64_t *pvrr
rlen = <int> return_length
try:
vvres = (<vector[np.intp_t] **>
PyMem_Malloc((stop-start) * sizeof(void*)))
if vvres == NULL:
raise MemoryError()
memset(<void*> vvres, 0, (stop-start) * sizeof(void*))
for i in range(stop - start):
vvres[i] = new vector[np.intp_t]()
pvxx = &vxx[start, 0]
pvrr = &vrr[start + 0]
with nogil:
query_ball_point(self.cself, pvxx,
pvrr, p, eps, stop - start, vvres, rlen)
for i in range(stop - start):
if return_length:
vlen[start + i] = vvres[i].front()
continue
if return_sorted:
with nogil:
sort(vvres[i].begin(), vvres[i].end())
elif return_sorted is None and xndim > 1:
# compatibility with the old bug not sorting scalar queries.
with nogil:
sort(vvres[i].begin(), vvres[i].end())
m = <np.intp_t> (vvres[i].size())
tmp = m * [None]
cur = vvres[i].data()
for j in range(m):
tmp[j] = cur[0]
cur += 1
vout[start + i] = tmp
finally:
if vvres != NULL:
for i in range(stop-start):
if vvres[i] != NULL:
del vvres[i]
PyMem_Free(vvres)
# multithreading logic is similar to cKDTree.query
if n_jobs == -1:
n_jobs = number_of_processors
_run_threads(_thread_func, n, n_jobs)
if xndim == 1: # scalar query, unpack result.
result = result[()]
return result
# ---------------
# query_ball_tree
# ---------------