geokdtree.core

  1from operator import itemgetter
  2
  3_GETTERS = [itemgetter(i) for i in range(16)]
  4
  5
  6def kdtree(points, depth, axis_count):
  7    """
  8    Function:
  9
 10    - Build a KDTree from a list of points.
 11
 12    Required Arguments:
 13
 14    - `points`
 15        - Type: list of tuples
 16        - What: A list of points to build the KDTree from
 17
 18    Optional Arguments:
 19
 20    - `depth`
 21        - Type: int
 22        - What: The current depth in the tree (used for axis selection)
 23    - `axis_count`
 24        - Type: int
 25        - What: The number of dimensions in the points (default is 2 for 2D points)
 26
 27    Returns:
 28
 29    - The constructed KDTree as a tuple in the format (point, axis, left, right).
 30    - Where left and right are subtrees.
 31    """
 32    if not points:
 33        return 0
 34    axis = depth % axis_count
 35    getter = _GETTERS[axis] if axis < 16 else itemgetter(axis)
 36    points.sort(key=getter)
 37    median = len(points) // 2
 38    return (
 39        points[median],
 40        axis,
 41        kdtree(points=points[:median], depth=depth + 1, axis_count=axis_count),
 42        kdtree(
 43            points=points[median + 1 :], depth=depth + 1, axis_count=axis_count
 44        ),
 45    )
 46
 47
 48def squared_distance(p1, p2, axis_count=2):
 49    """
 50    Function:
 51
 52    - Calculate the squared distance between two points.
 53
 54    Required Arguments:
 55
 56    - `p1`
 57        - Type: tuple
 58        - What: The first point
 59    - `p2`
 60        - Type: tuple
 61        - What: The second point
 62
 63    Optional Arguments:
 64
 65    - `axis_count`
 66        - Type: int
 67        - What: The number of dimensions in the points
 68        - Default: 2 (for 2D points)
 69
 70    Returns:
 71
 72    - The squared distance between the two points.
 73    """
 74    if axis_count == 2:
 75        dx = p1[0] - p2[0]
 76        dy = p1[1] - p2[1]
 77        return dx * dx + dy * dy
 78    elif axis_count == 3:
 79        dx = p1[0] - p2[0]
 80        dy = p1[1] - p2[1]
 81        dz = p1[2] - p2[2]
 82        return dx * dx + dy * dy + dz * dz
 83    total = 0.0
 84    for i in range(axis_count):
 85        d = p1[i] - p2[i]
 86        total += d * d
 87    return total
 88
 89
 90def closest_point(node, point, best=None, axis_count=2, best_dist=float("inf")):
 91    """
 92    Function:
 93
 94    - Find the closest point in the KDTree to a given point.
 95
 96    Required Arguments:
 97
 98    - `node`
 99        - Type: tuple
100        - What: The node of the KDTree
101    - `point`
102        - Type: tuple
103        - What: The point to find the closest point to
104
105    Optional Arguments:
106
107    - `best`
108        - Type: tuple or None
109        - What: The best point found so far (default is None)
110    - `axis_count`
111        - Type: int
112        - What: The number of dimensions in the points (default is 2 for 2D points)
113    - `best_dist`
114        - Type: float
115        - What: The best distance found so far (default is infinity)
116
117    Returns:
118
119    - The closest point found in the KDTree to the given point.
120    """
121    if node == 0:
122        return best, best_dist
123    # Get the median node and its distance
124    median_node = node[0]
125    median_node_dist = squared_distance(
126        point, median_node, axis_count=axis_count
127    )
128    # Update the best point and distance if necessary
129    if best is None or median_node_dist < best_dist:
130        best = median_node
131        best_dist = median_node_dist
132    # Calculate the difference for node selection given the current axis
133    axis = node[1]
134    diff = point[axis] - median_node[axis]
135    # Choose side to search
136    close, away = (node[2], node[3]) if diff < 0 else (node[3], node[2])
137    # Search the close side first
138    best, best_dist = closest_point(
139        close,
140        point,
141        best,
142        axis_count=axis_count,
143        best_dist=best_dist,
144    )
145    # Check the other side if needed
146    if diff * diff < best_dist:
147        best, best_dist = closest_point(
148            away,
149            point,
150            best,
151            axis_count=axis_count,
152            best_dist=best_dist,
153        )
154    return best, best_dist
155
156
157def closest_point_per_quadrant_2d(node, point):
158    """
159    Function:
160
161    - Find the closest point in each of the 4 quadrants (ne, nw, se, sw)
162      for 2D Cartesian points.
163
164    Required Arguments:
165
166    - `node`
167        - Type: tuple
168        - What: The root node of the KDTree
169    - `point`
170        - Type: tuple
171        - What: The 2D query point (x, y)
172
173    Returns:
174
175    - A dictionary mapping 'ne', 'nw', 'se', 'sw' to their closest point tuple or None.
176    """
177    bests = [None, None, None, None]
178    best_dists = [float("inf"), float("inf"), float("inf"), float("inf")]
179
180    px, py = point[0], point[1]
181
182    def _search(curr, active_mask):
183        if curr == 0 or curr is None or active_mask == 0:
184            return
185
186        median_node = curr[0]
187        mx, my = median_node[0], median_node[1]
188        dist = (px - mx) * (px - mx) + (py - my) * (py - my)
189
190        is_east = mx >= px
191        is_west = mx <= px
192        is_north = my >= py
193        is_south = my <= py
194
195        if is_north and is_east and (active_mask & 1):
196            if dist < best_dists[0]:
197                bests[0] = median_node
198                best_dists[0] = dist
199
200        if is_north and is_west and (active_mask & 2):
201            if dist < best_dists[1]:
202                bests[1] = median_node
203                best_dists[1] = dist
204
205        if is_south and is_east and (active_mask & 4):
206            if dist < best_dists[2]:
207                bests[2] = median_node
208                best_dists[2] = dist
209
210        if is_south and is_west and (active_mask & 8):
211            if dist < best_dists[3]:
212                bests[3] = median_node
213                best_dists[3] = dist
214
215        axis = curr[1]
216        diff = point[axis] - median_node[axis]
217
218        if diff < 0:
219            close, away = curr[2], curr[3]
220            close_mask = active_mask
221            away_mask = (
222                active_mask & (1 | 4) if axis == 0 else active_mask & (1 | 2)
223            )
224        else:
225            close, away = curr[3], curr[2]
226            close_mask = active_mask
227            away_mask = (
228                active_mask & (2 | 8) if axis == 0 else active_mask & (4 | 8)
229            )
230
231        _search(close, close_mask)
232
233        if away_mask:
234            diff_sq = diff * diff
235            max_away = 0.0
236            if (away_mask & 1) and best_dists[0] > max_away:
237                max_away = best_dists[0]
238            if (away_mask & 2) and best_dists[1] > max_away:
239                max_away = best_dists[1]
240            if (away_mask & 4) and best_dists[2] > max_away:
241                max_away = best_dists[2]
242            if (away_mask & 8) and best_dists[3] > max_away:
243                max_away = best_dists[3]
244
245            if diff_sq < max_away:
246                _search(away, away_mask)
247
248    _search(node, 15)
249    return {"ne": bests[0], "nw": bests[1], "se": bests[2], "sw": bests[3]}
250
251
252def validate_points(points, dimensions):
253    """Materialize and validate a batch before starting nearest searches."""
254    from math import isfinite
255
256    pts = [tuple(point) for point in points]
257    for point in pts:
258        if len(point) != dimensions:
259            raise ValueError("query dimensions must match tree dimensions")
260        if not all(isfinite(value) for value in point):
261            raise ValueError("query coordinates must be finite")
262    return pts
def kdtree(points, depth, axis_count):
 7def kdtree(points, depth, axis_count):
 8    """
 9    Function:
10
11    - Build a KDTree from a list of points.
12
13    Required Arguments:
14
15    - `points`
16        - Type: list of tuples
17        - What: A list of points to build the KDTree from
18
19    Optional Arguments:
20
21    - `depth`
22        - Type: int
23        - What: The current depth in the tree (used for axis selection)
24    - `axis_count`
25        - Type: int
26        - What: The number of dimensions in the points (default is 2 for 2D points)
27
28    Returns:
29
30    - The constructed KDTree as a tuple in the format (point, axis, left, right).
31    - Where left and right are subtrees.
32    """
33    if not points:
34        return 0
35    axis = depth % axis_count
36    getter = _GETTERS[axis] if axis < 16 else itemgetter(axis)
37    points.sort(key=getter)
38    median = len(points) // 2
39    return (
40        points[median],
41        axis,
42        kdtree(points=points[:median], depth=depth + 1, axis_count=axis_count),
43        kdtree(
44            points=points[median + 1 :], depth=depth + 1, axis_count=axis_count
45        ),
46    )

Function:

  • Build a KDTree from a list of points.

Required Arguments:

  • points
    • Type: list of tuples
    • What: A list of points to build the KDTree from

Optional Arguments:

  • depth
    • Type: int
    • What: The current depth in the tree (used for axis selection)
  • axis_count
    • Type: int
    • What: The number of dimensions in the points (default is 2 for 2D points)

Returns:

  • The constructed KDTree as a tuple in the format (point, axis, left, right).
  • Where left and right are subtrees.
def squared_distance(p1, p2, axis_count=2):
49def squared_distance(p1, p2, axis_count=2):
50    """
51    Function:
52
53    - Calculate the squared distance between two points.
54
55    Required Arguments:
56
57    - `p1`
58        - Type: tuple
59        - What: The first point
60    - `p2`
61        - Type: tuple
62        - What: The second point
63
64    Optional Arguments:
65
66    - `axis_count`
67        - Type: int
68        - What: The number of dimensions in the points
69        - Default: 2 (for 2D points)
70
71    Returns:
72
73    - The squared distance between the two points.
74    """
75    if axis_count == 2:
76        dx = p1[0] - p2[0]
77        dy = p1[1] - p2[1]
78        return dx * dx + dy * dy
79    elif axis_count == 3:
80        dx = p1[0] - p2[0]
81        dy = p1[1] - p2[1]
82        dz = p1[2] - p2[2]
83        return dx * dx + dy * dy + dz * dz
84    total = 0.0
85    for i in range(axis_count):
86        d = p1[i] - p2[i]
87        total += d * d
88    return total

Function:

  • Calculate the squared distance between two points.

Required Arguments:

  • p1
    • Type: tuple
    • What: The first point
  • p2
    • Type: tuple
    • What: The second point

Optional Arguments:

  • axis_count
    • Type: int
    • What: The number of dimensions in the points
    • Default: 2 (for 2D points)

Returns:

  • The squared distance between the two points.
def closest_point(node, point, best=None, axis_count=2, best_dist=inf):
 91def closest_point(node, point, best=None, axis_count=2, best_dist=float("inf")):
 92    """
 93    Function:
 94
 95    - Find the closest point in the KDTree to a given point.
 96
 97    Required Arguments:
 98
 99    - `node`
100        - Type: tuple
101        - What: The node of the KDTree
102    - `point`
103        - Type: tuple
104        - What: The point to find the closest point to
105
106    Optional Arguments:
107
108    - `best`
109        - Type: tuple or None
110        - What: The best point found so far (default is None)
111    - `axis_count`
112        - Type: int
113        - What: The number of dimensions in the points (default is 2 for 2D points)
114    - `best_dist`
115        - Type: float
116        - What: The best distance found so far (default is infinity)
117
118    Returns:
119
120    - The closest point found in the KDTree to the given point.
121    """
122    if node == 0:
123        return best, best_dist
124    # Get the median node and its distance
125    median_node = node[0]
126    median_node_dist = squared_distance(
127        point, median_node, axis_count=axis_count
128    )
129    # Update the best point and distance if necessary
130    if best is None or median_node_dist < best_dist:
131        best = median_node
132        best_dist = median_node_dist
133    # Calculate the difference for node selection given the current axis
134    axis = node[1]
135    diff = point[axis] - median_node[axis]
136    # Choose side to search
137    close, away = (node[2], node[3]) if diff < 0 else (node[3], node[2])
138    # Search the close side first
139    best, best_dist = closest_point(
140        close,
141        point,
142        best,
143        axis_count=axis_count,
144        best_dist=best_dist,
145    )
146    # Check the other side if needed
147    if diff * diff < best_dist:
148        best, best_dist = closest_point(
149            away,
150            point,
151            best,
152            axis_count=axis_count,
153            best_dist=best_dist,
154        )
155    return best, best_dist

Function:

  • Find the closest point in the KDTree to a given point.

Required Arguments:

  • node
    • Type: tuple
    • What: The node of the KDTree
  • point
    • Type: tuple
    • What: The point to find the closest point to

Optional Arguments:

  • best
    • Type: tuple or None
    • What: The best point found so far (default is None)
  • axis_count
    • Type: int
    • What: The number of dimensions in the points (default is 2 for 2D points)
  • best_dist
    • Type: float
    • What: The best distance found so far (default is infinity)

Returns:

  • The closest point found in the KDTree to the given point.
def closest_point_per_quadrant_2d(node, point):
158def closest_point_per_quadrant_2d(node, point):
159    """
160    Function:
161
162    - Find the closest point in each of the 4 quadrants (ne, nw, se, sw)
163      for 2D Cartesian points.
164
165    Required Arguments:
166
167    - `node`
168        - Type: tuple
169        - What: The root node of the KDTree
170    - `point`
171        - Type: tuple
172        - What: The 2D query point (x, y)
173
174    Returns:
175
176    - A dictionary mapping 'ne', 'nw', 'se', 'sw' to their closest point tuple or None.
177    """
178    bests = [None, None, None, None]
179    best_dists = [float("inf"), float("inf"), float("inf"), float("inf")]
180
181    px, py = point[0], point[1]
182
183    def _search(curr, active_mask):
184        if curr == 0 or curr is None or active_mask == 0:
185            return
186
187        median_node = curr[0]
188        mx, my = median_node[0], median_node[1]
189        dist = (px - mx) * (px - mx) + (py - my) * (py - my)
190
191        is_east = mx >= px
192        is_west = mx <= px
193        is_north = my >= py
194        is_south = my <= py
195
196        if is_north and is_east and (active_mask & 1):
197            if dist < best_dists[0]:
198                bests[0] = median_node
199                best_dists[0] = dist
200
201        if is_north and is_west and (active_mask & 2):
202            if dist < best_dists[1]:
203                bests[1] = median_node
204                best_dists[1] = dist
205
206        if is_south and is_east and (active_mask & 4):
207            if dist < best_dists[2]:
208                bests[2] = median_node
209                best_dists[2] = dist
210
211        if is_south and is_west and (active_mask & 8):
212            if dist < best_dists[3]:
213                bests[3] = median_node
214                best_dists[3] = dist
215
216        axis = curr[1]
217        diff = point[axis] - median_node[axis]
218
219        if diff < 0:
220            close, away = curr[2], curr[3]
221            close_mask = active_mask
222            away_mask = (
223                active_mask & (1 | 4) if axis == 0 else active_mask & (1 | 2)
224            )
225        else:
226            close, away = curr[3], curr[2]
227            close_mask = active_mask
228            away_mask = (
229                active_mask & (2 | 8) if axis == 0 else active_mask & (4 | 8)
230            )
231
232        _search(close, close_mask)
233
234        if away_mask:
235            diff_sq = diff * diff
236            max_away = 0.0
237            if (away_mask & 1) and best_dists[0] > max_away:
238                max_away = best_dists[0]
239            if (away_mask & 2) and best_dists[1] > max_away:
240                max_away = best_dists[1]
241            if (away_mask & 4) and best_dists[2] > max_away:
242                max_away = best_dists[2]
243            if (away_mask & 8) and best_dists[3] > max_away:
244                max_away = best_dists[3]
245
246            if diff_sq < max_away:
247                _search(away, away_mask)
248
249    _search(node, 15)
250    return {"ne": bests[0], "nw": bests[1], "se": bests[2], "sw": bests[3]}

Function:

  • Find the closest point in each of the 4 quadrants (ne, nw, se, sw) for 2D Cartesian points.

Required Arguments:

  • node
    • Type: tuple
    • What: The root node of the KDTree
  • point
    • Type: tuple
    • What: The 2D query point (x, y)

Returns:

  • A dictionary mapping 'ne', 'nw', 'se', 'sw' to their closest point tuple or None.
def validate_points(points, dimensions):
253def validate_points(points, dimensions):
254    """Materialize and validate a batch before starting nearest searches."""
255    from math import isfinite
256
257    pts = [tuple(point) for point in points]
258    for point in pts:
259        if len(point) != dimensions:
260            raise ValueError("query dimensions must match tree dimensions")
261        if not all(isfinite(value) for value in point):
262            raise ValueError("query coordinates must be finite")
263    return pts

Materialize and validate a batch before starting nearest searches.