kdtree 0.17__tar.gz → 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kdtree-1.0/MANIFEST.in ADDED
@@ -0,0 +1,7 @@
1
+ include AUTHORS
2
+ include LICENSE
3
+ include readme.md
4
+ include test.py
5
+ include kdtree.pyi
6
+ include test_typing.py
7
+ include typing_sample.py
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kdtree
3
- Version: 0.17
4
- Summary: A Python implemntation of a kd-tree
3
+ Version: 1.0
4
+ Summary: A Python implementation of a kd-tree
5
5
  Home-page: https://github.com/stefankoegl/kdtree
6
- Download-URL: http://pypi.python.org/packages/source/k/kdtree/kdtree-0.17.tar.gz
6
+ Download-URL: http://pypi.python.org/packages/source/k/kdtree/kdtree-1.0.tar.gz
7
7
  Author: Stefan Kögl
8
8
  Author-email: stefan@skoegl.net
9
9
  License: ISC license
@@ -14,16 +14,17 @@ Classifier: Operating System :: OS Independent
14
14
  Classifier: Programming Language :: Python
15
15
  Classifier: Programming Language :: Python :: 3
16
16
  Classifier: Programming Language :: Python :: 3 :: Only
17
- Classifier: Programming Language :: Python :: 3.9
18
- Classifier: Programming Language :: Python :: 3.10
19
17
  Classifier: Programming Language :: Python :: 3.11
20
18
  Classifier: Programming Language :: Python :: 3.12
21
19
  Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
22
  Classifier: Programming Language :: Python :: Implementation :: CPython
23
23
  Classifier: Programming Language :: Python :: Implementation :: PyPy
24
24
  Classifier: Topic :: Software Development :: Libraries
25
25
  Classifier: Topic :: Utilities
26
- Requires-Python: >=3.9
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
27
28
  License-File: LICENSE
28
29
  License-File: AUTHORS
29
30
  Dynamic: author
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kdtree
3
- Version: 0.17
4
- Summary: A Python implemntation of a kd-tree
3
+ Version: 1.0
4
+ Summary: A Python implementation of a kd-tree
5
5
  Home-page: https://github.com/stefankoegl/kdtree
6
- Download-URL: http://pypi.python.org/packages/source/k/kdtree/kdtree-0.17.tar.gz
6
+ Download-URL: http://pypi.python.org/packages/source/k/kdtree/kdtree-1.0.tar.gz
7
7
  Author: Stefan Kögl
8
8
  Author-email: stefan@skoegl.net
9
9
  License: ISC license
@@ -14,16 +14,17 @@ Classifier: Operating System :: OS Independent
14
14
  Classifier: Programming Language :: Python
15
15
  Classifier: Programming Language :: Python :: 3
16
16
  Classifier: Programming Language :: Python :: 3 :: Only
17
- Classifier: Programming Language :: Python :: 3.9
18
- Classifier: Programming Language :: Python :: 3.10
19
17
  Classifier: Programming Language :: Python :: 3.11
20
18
  Classifier: Programming Language :: Python :: 3.12
21
19
  Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
22
  Classifier: Programming Language :: Python :: Implementation :: CPython
23
23
  Classifier: Programming Language :: Python :: Implementation :: PyPy
24
24
  Classifier: Topic :: Software Development :: Libraries
25
25
  Classifier: Topic :: Utilities
26
- Requires-Python: >=3.9
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
27
28
  License-File: LICENSE
28
29
  License-File: AUTHORS
29
30
  Dynamic: author
@@ -2,10 +2,13 @@ AUTHORS
2
2
  LICENSE
3
3
  MANIFEST.in
4
4
  kdtree.py
5
+ kdtree.pyi
5
6
  readme.md
6
7
  setup.cfg
7
8
  setup.py
8
9
  test.py
10
+ test_typing.py
11
+ typing_sample.py
9
12
  kdtree.egg-info/PKG-INFO
10
13
  kdtree.egg-info/SOURCES.txt
11
14
  kdtree.egg-info/dependency_links.txt
@@ -1,7 +1,7 @@
1
1
  # -*- coding: utf-8 -*-
2
2
 
3
3
 
4
- """A Python implemntation of a kd-tree
4
+ """A Python implementation of a kd-tree
5
5
 
6
6
  This package provides a simple implementation of a kd-tree in Python.
7
7
  https://en.wikipedia.org/wiki/K-d_tree
@@ -17,7 +17,7 @@ from collections import deque
17
17
  from functools import wraps
18
18
 
19
19
  __author__ = u'Stefan Kögl <stefan@skoegl.net>'
20
- __version__ = '0.17'
20
+ __version__ = '1.0'
21
21
  __website__ = 'https://github.com/stefankoegl/kdtree'
22
22
  __license__ = 'ISC license'
23
23
 
@@ -44,7 +44,7 @@ class Node(object):
44
44
  >>> Node( 1, left=Node(2) ).is_leaf
45
45
  False
46
46
  """
47
- return (not self.data) or \
47
+ return (self.data is None) or \
48
48
  (all(not bool(c) for c, p in self.children))
49
49
 
50
50
 
@@ -175,10 +175,10 @@ class Node(object):
175
175
  __bool__ = __nonzero__
176
176
 
177
177
  def __eq__(self, other):
178
- if isinstance(other, tuple):
179
- return self.data == other
180
- else:
178
+ if isinstance(other, Node):
181
179
  return self.data == other.data
180
+ else:
181
+ return self.data == other
182
182
 
183
183
  def __hash__(self):
184
184
  return id(self)
@@ -190,7 +190,7 @@ def require_axis(f):
190
190
  @wraps(f)
191
191
  def _wrapper(self, *args, **kwargs):
192
192
  if None in (self.axis, self.sel_axis):
193
- raise ValueError('%(func_name) requires the node %(node)s '
193
+ raise ValueError('%(func_name)s requires the node %(node)s '
194
194
  'to have an axis and a sel_axis function' %
195
195
  dict(func_name=f.__name__, node=repr(self)))
196
196
 
@@ -229,10 +229,10 @@ class KDNode(Node):
229
229
  Users should call add() only to the topmost tree.
230
230
  """
231
231
 
232
+ check_dimensionality([point], dimensions=self.dimensions)
233
+
232
234
  current = self
233
235
  while True:
234
- check_dimensionality([point], dimensions=current.dimensions)
235
-
236
236
  # Adding has hit an empty leaf-node, add here
237
237
  if current.data is None:
238
238
  current.data = point
@@ -294,33 +294,49 @@ class KDNode(Node):
294
294
 
295
295
  If there are multiple points matching "point", only one is removed. The
296
296
  optional "node" parameter is used for checking the identity, once the
297
- removeal candidate is decided."""
297
+ removal candidate is decided."""
298
+
299
+ return self._remove_one(point, node)[0]
300
+
301
+
302
+ def _remove_one(self, point, node):
303
+ """ Removes at most one matching node from the (sub)tree
304
+
305
+ Returns a (new-subtree-root, removed) tuple, where removed indicates
306
+ whether a node has been removed. """
298
307
 
299
308
  # Recursion has reached an empty leaf node, nothing here to delete
300
309
  if not self:
301
- return
310
+ return self, False
302
311
 
303
312
  # Recursion has reached the node to be deleted
304
313
  if self.should_remove(point, node):
305
- return self._remove(point)
314
+ return self._remove(point), True
306
315
 
307
316
  # Remove direct subnode
308
317
  if self.left and self.left.should_remove(point, node):
309
318
  self.left = self.left._remove(point)
319
+ return self, True
310
320
 
311
321
  elif self.right and self.right.should_remove(point, node):
312
322
  self.right = self.right._remove(point)
323
+ return self, True
313
324
 
314
- # Recurse to subtrees
325
+ # Recurse to subtrees. If the point lies on the splitting plane, both
326
+ # subtrees may contain it, but only one node must be removed
315
327
  if point[self.axis] <= self.data[self.axis]:
316
328
  if self.left:
317
- self.left = self.left.remove(point, node)
329
+ self.left, removed = self.left._remove_one(point, node)
330
+ if removed:
331
+ return self, True
318
332
 
319
333
  if point[self.axis] >= self.data[self.axis]:
320
334
  if self.right:
321
- self.right = self.right.remove(point, node)
335
+ self.right, removed = self.right._remove_one(point, node)
336
+ if removed:
337
+ return self, True
322
338
 
323
- return self
339
+ return self, False
324
340
 
325
341
 
326
342
  @require_axis
@@ -376,7 +392,10 @@ class KDNode(Node):
376
392
  Returns the (possibly new) root of the rebalanced tree
377
393
  """
378
394
 
379
- return create([x.data for x in self.inorder()])
395
+ points = [x.data for x in self.inorder()]
396
+ axis = self.axis if self.axis is not None else 0
397
+ return create(points, dimensions=self.dimensions, axis=axis,
398
+ sel_axis=self.sel_axis)
380
399
 
381
400
 
382
401
  def axis_dist(self, point, axis):
@@ -516,12 +535,16 @@ class KDNode(Node):
516
535
 
517
536
  # get the splitting plane
518
537
  split_plane = self.data[self.axis]
538
+ # dist is compared against squared distances, so the distance to the
539
+ # splitting plane has to be squared as well
540
+ plane_dist = self.axis_dist(point, self.axis)
519
541
 
520
- # Search the side of the splitting plane that the point is in
521
- if point[self.axis] <= split_plane + dist:
542
+ # Search each side of the splitting plane that may contain points
543
+ # within the given distance
544
+ if point[self.axis] <= split_plane or plane_dist < dist:
522
545
  if self.left is not None:
523
546
  self.left._search_nn_dist(point, dist, results, get_dist)
524
- if point[self.axis] >= split_plane - dist:
547
+ if point[self.axis] >= split_plane or plane_dist < dist:
525
548
  if self.right is not None:
526
549
  self.right._search_nn_dist(point, dist, results, get_dist)
527
550
 
@@ -668,8 +691,8 @@ def create(point_list=None, dimensions=None, axis=0, sel_axis=None):
668
691
  median = len(point_list) // 2
669
692
 
670
693
  loc = point_list[median]
671
- left = create(point_list[:median], dimensions, sel_axis(axis))
672
- right = create(point_list[median + 1:], dimensions, sel_axis(axis))
694
+ left = create(point_list[:median], dimensions, sel_axis(axis), sel_axis)
695
+ right = create(point_list[median + 1:], dimensions, sel_axis(axis), sel_axis)
673
696
  return KDNode(loc, left, right, axis=axis, sel_axis=sel_axis, dimensions=dimensions)
674
697
 
675
698
 
@@ -713,7 +736,8 @@ def visualize(tree, max_level=100, node_width=10, left_padding=5):
713
736
  in_level = 0
714
737
  level = 0
715
738
 
716
- for node in level_order(tree, include_all=True):
739
+ # level_order() is infinite with include_all; the loop ends with break
740
+ for node in level_order(tree, include_all=True): # pragma: no branch
717
741
 
718
742
  if in_level == 0:
719
743
  print()
kdtree-1.0/kdtree.pyi ADDED
@@ -0,0 +1,165 @@
1
+ """Type stubs for the kdtree module
2
+
3
+ kdtree is distributed as a single-file module. Type information is therefore
4
+ shipped as this stub file, which is installed next to kdtree.py.
5
+ """
6
+
7
+ from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
8
+ from typing import Any, Generic, ParamSpec, Protocol, Self, TypeVar, overload
9
+
10
+ __author__: str
11
+ __version__: str
12
+ __website__: str
13
+ __license__: str
14
+
15
+ class _Point(Protocol):
16
+ """Anything that can be used as a point: it has a length and its
17
+ coordinates can be accessed by index"""
18
+
19
+ def __len__(self) -> int: ...
20
+ def __getitem__(self, index: int, /) -> Any: ...
21
+
22
+ _T = TypeVar("_T")
23
+ _P = TypeVar("_P", bound=_Point)
24
+ _Q = TypeVar("_Q", bound=_Point)
25
+ _P_contra = TypeVar("_P_contra", contravariant=True)
26
+ _Q_contra = TypeVar("_Q_contra", contravariant=True)
27
+ _D_co = TypeVar("_D_co", covariant=True)
28
+ _N = TypeVar("_N", bound=Node[Any])
29
+ _D = TypeVar("_D", bound=_Distance)
30
+ _R = TypeVar("_R")
31
+ _Params = ParamSpec("_Params")
32
+
33
+ class _Distance(Protocol):
34
+ """A distance value: search_knn() negates distances and compares them"""
35
+
36
+ def __neg__(self) -> Self: ...
37
+ def __lt__(self, other: Any, /) -> bool: ...
38
+ def __gt__(self, other: Any, /) -> bool: ...
39
+
40
+ class _DistFunc(Protocol[_P_contra, _Q_contra, _D_co]):
41
+ """A distance function, always called as dist(a, b, axis=axis)
42
+
43
+ a is a point stored in the tree, b is the point that is searched for."""
44
+
45
+ def __call__(
46
+ self, a: _P_contra, b: _Q_contra, /, *, axis: int | None
47
+ ) -> _D_co: ...
48
+
49
+ class Node(Generic[_T]):
50
+ data: _T | None
51
+ left: Self | None
52
+ right: Self | None
53
+ def __init__(
54
+ self,
55
+ data: _T | None = None,
56
+ left: Self | None = None,
57
+ right: Self | None = None,
58
+ ) -> None: ...
59
+ @property
60
+ def is_leaf(self) -> bool: ...
61
+ def preorder(self) -> Iterator[Self]: ...
62
+ def inorder(self) -> Iterator[Self]: ...
63
+ def postorder(self) -> Iterator[Self]: ...
64
+ @property
65
+ def children(self) -> Iterator[tuple[Self, int]]: ...
66
+ def set_child(self, index: int, child: Self | None) -> None: ...
67
+ def height(self) -> int: ...
68
+ def get_child_pos(self, child: Node[Any]) -> int | None: ...
69
+ def __nonzero__(self) -> bool: ...
70
+ def __bool__(self) -> bool: ...
71
+ def __eq__(self, other: object) -> bool: ...
72
+ def __hash__(self) -> int: ...
73
+
74
+ def require_axis(f: Callable[_Params, _R]) -> Callable[_Params, _R]: ...
75
+
76
+ class KDNode(Node[_P]):
77
+ axis: int | None
78
+ sel_axis: Callable[[int], int] | None
79
+ dimensions: int | None
80
+ def __init__(
81
+ self,
82
+ data: _P | None = None,
83
+ left: Self | None = None,
84
+ right: Self | None = None,
85
+ axis: int | None = None,
86
+ sel_axis: Callable[[int], int] | None = None,
87
+ dimensions: int | None = None,
88
+ ) -> None: ...
89
+ def add(self, point: _P) -> Self: ...
90
+ def create_subnode(self, data: _P | None) -> Self: ...
91
+ def find_replacement(self) -> tuple[Self | None, Self]: ...
92
+ def should_remove(self, point: _Point, node: KDNode[Any] | None) -> bool: ...
93
+ def remove(self, point: _Point, node: KDNode[Any] | None = None) -> Self: ...
94
+ @property
95
+ def is_balanced(self) -> bool: ...
96
+ def rebalance(self) -> KDNode[_P]: ...
97
+ def axis_dist(self, point: _Point, axis: int) -> float: ...
98
+ def dist(self, point: _Point, axis: int | None = None) -> float: ...
99
+ @overload
100
+ def search_knn(
101
+ self, point: _Point, k: int, dist: None = None
102
+ ) -> list[tuple[Self, float]]: ...
103
+ @overload
104
+ def search_knn(
105
+ self, point: _Q, k: int, dist: _DistFunc[_P, _Q, _D]
106
+ ) -> list[tuple[Self, _D]]: ...
107
+ @overload
108
+ def search_nn(self, point: _Point, dist: None = None) -> tuple[Self, float]: ...
109
+ @overload
110
+ def search_nn(
111
+ self, point: _Q, dist: _DistFunc[_P, _Q, _D]
112
+ ) -> tuple[Self, _D]: ...
113
+ def search_nn_dist(self, point: _Point, distance: float) -> list[_P]: ...
114
+ def range_search(self, top_left: _Point, bottom_right: _Point) -> list[Self]: ...
115
+ def is_valid(self) -> bool: ...
116
+ def extreme_child(
117
+ self,
118
+ sel_func: Callable[..., Any],
119
+ axis: int,
120
+ ) -> tuple[Self, Self | None] | tuple[None, None]: ...
121
+
122
+ @overload
123
+ def create(
124
+ point_list: None = None,
125
+ *,
126
+ dimensions: int,
127
+ axis: int = 0,
128
+ sel_axis: Callable[[int], int] | None = None,
129
+ ) -> KDNode[Any]: ...
130
+ @overload
131
+ def create(
132
+ point_list: None,
133
+ dimensions: int,
134
+ axis: int = 0,
135
+ sel_axis: Callable[[int], int] | None = None,
136
+ ) -> KDNode[Any]: ...
137
+ @overload
138
+ def create(
139
+ point_list: Sequence[_P],
140
+ dimensions: int | None = None,
141
+ axis: int = 0,
142
+ sel_axis: Callable[[int], int] | None = None,
143
+ ) -> KDNode[_P]: ...
144
+ @overload
145
+ def create(
146
+ # without dimensions, they are taken from point_list[0]. Iterators are
147
+ # not supported, as the dimensionality check consumes them
148
+ point_list: Collection[_P],
149
+ dimensions: int,
150
+ axis: int = 0,
151
+ sel_axis: Callable[[int], int] | None = None,
152
+ ) -> KDNode[_P]: ...
153
+ @overload
154
+ def check_dimensionality(
155
+ point_list: Sequence[_Point], dimensions: int | None = None
156
+ ) -> int: ...
157
+ @overload
158
+ def check_dimensionality(point_list: Iterable[_Point], dimensions: int) -> int: ...
159
+ def level_order(tree: _N, include_all: bool = False) -> Iterator[_N]: ...
160
+ def visualize(
161
+ tree: Node[Any],
162
+ max_level: int = 100,
163
+ node_width: int = 10,
164
+ left_padding: int = 5,
165
+ ) -> None: ...
@@ -55,7 +55,7 @@ Usage
55
55
 
56
56
  # Find the nearest node to the location (1, 2, 3)
57
57
  >>> tree.search_nn( (1, 2, 3) )
58
- <KDNode - (2, 3, 4)>
58
+ (<KDNode - (2, 3, 4)>, 3.0)
59
59
 
60
60
  # Add a point to make the tree more interesting
61
61
  >>> tree.add( (10, 2, 1) )
@@ -73,7 +73,7 @@ Usage
73
73
  # Take the right subtree of the root
74
74
  >>> subtree = tree.right
75
75
 
76
- # and detatch it
76
+ # and detach it
77
77
  >>> tree.right = None
78
78
  >>> kdtree.visualize(tree)
79
79
 
@@ -122,6 +122,21 @@ Usage
122
122
 
123
123
  (2, 3, 4)
124
124
 
125
+ ### Type hints
126
+
127
+ Type information is provided in the stub file `kdtree.pyi`, which is installed
128
+ next to `kdtree.py` and, for mypy, as the stub-only package `kdtree-stubs`.
129
+ Trees are generic in the type of their points:
130
+
131
+ ```python
132
+ tree = kdtree.create([(1, 2), (3, 4)]) # KDNode[tuple[int, int]]
133
+ node, dist = tree.search_nn((1, 1)) # KDNode[tuple[int, int]], float
134
+ ```
135
+
136
+ The classes are only generic for type checkers; at runtime write
137
+ annotations like `kdtree.KDNode[tuple[int, int]]` as strings or use
138
+ `from __future__ import annotations`.
139
+
125
140
  ### Adding a payload
126
141
 
127
142
  Indexing a dict by a pair of floats is not a good idea, since there might be unexpected precision errors.
kdtree-1.0/setup.cfg ADDED
@@ -0,0 +1,15 @@
1
+ [bdist_wheel]
2
+ universal = 0
3
+
4
+ [coverage:run]
5
+ branch = True
6
+ source = kdtree
7
+
8
+ [coverage:report]
9
+ show_missing = True
10
+ fail_under = 100
11
+
12
+ [egg_info]
13
+ tag_build =
14
+ tag_date = 0
15
+
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env python
2
2
 
3
3
  from setuptools import setup
4
+ from setuptools.command.build_py import build_py
4
5
  import re
5
6
  import os.path
6
7
 
@@ -16,6 +17,32 @@ MODULES = (
16
17
  PACKAGE,
17
18
  )
18
19
 
20
+ # Type stubs (PEP 484) for the modules. kdtree is a single-file module, so
21
+ # PEP 561's py.typed marker can not be used. Instead each stub is installed
22
+ # twice: next to its module (picked up by e.g. pyright and PyCharm) and as a
23
+ # stub-only package <module>-stubs (picked up by mypy). setuptools only
24
+ # installs .py files for py_modules, so the stubs are copied explicitly.
25
+ STUBS = {}
26
+ for module in MODULES:
27
+ STUBS[module + '.pyi'] = module + '.pyi'
28
+ STUBS[os.path.join(module + '-stubs', '__init__.pyi')] = module + '.pyi'
29
+
30
+
31
+ class build_py_with_stubs(build_py):
32
+ """ build_py command that also installs the type stubs """
33
+
34
+ def run(self):
35
+ super().run()
36
+ for target, source in STUBS.items():
37
+ target = os.path.join(self.build_lib, target)
38
+ self.mkpath(os.path.dirname(target))
39
+ self.copy_file(os.path.join(dirname, source), target)
40
+
41
+ def get_outputs(self, *args, **kwargs):
42
+ outputs = super().get_outputs(*args, **kwargs)
43
+ return outputs + [os.path.join(self.build_lib, t) for t in STUBS]
44
+
45
+
19
46
  AUTHOR_EMAIL = metadata['author']
20
47
  VERSION = metadata['version']
21
48
  WEBSITE = metadata['website']
@@ -37,15 +64,16 @@ CLASSIFIERS = [
37
64
  'Programming Language :: Python',
38
65
  'Programming Language :: Python :: 3',
39
66
  'Programming Language :: Python :: 3 :: Only',
40
- 'Programming Language :: Python :: 3.9',
41
- 'Programming Language :: Python :: 3.10',
42
67
  'Programming Language :: Python :: 3.11',
43
68
  'Programming Language :: Python :: 3.12',
44
69
  'Programming Language :: Python :: 3.13',
70
+ 'Programming Language :: Python :: 3.14',
71
+ 'Programming Language :: Python :: 3.15',
45
72
  'Programming Language :: Python :: Implementation :: CPython',
46
73
  'Programming Language :: Python :: Implementation :: PyPy',
47
74
  'Topic :: Software Development :: Libraries',
48
75
  'Topic :: Utilities',
76
+ 'Typing :: Typed',
49
77
  ]
50
78
 
51
79
 
@@ -58,9 +86,10 @@ setup(name=PACKAGE,
58
86
  license=LICENSE,
59
87
  url=WEBSITE,
60
88
  py_modules=MODULES,
89
+ cmdclass={'build_py': build_py_with_stubs},
61
90
  download_url='http://pypi.python.org/packages/source/' + \
62
91
  PACKAGE[0] + '/' + PACKAGE + '/' + \
63
92
  PACKAGE + '-' + VERSION + '.tar.gz',
64
93
  classifiers=CLASSIFIERS,
65
- python_requires='>=3.9',
94
+ python_requires='>=3.11',
66
95
  )