Python-KD-Tree icon indicating copy to clipboard operation
Python-KD-Tree copied to clipboard

Add a basic example with geolocalized data

Open EricDuminil opened this issue 3 years ago • 0 comments

First : thanks a lot of the excellent script. It's fast and concise.

If you're interested, here's a basic example of using your KD-Tree with geolocalized data.

from kd_tree import KDTree
from dataclasses import dataclass

#######################################################################
#                Define a Point class, for convenience                #
#######################################################################


@dataclass
class Point2D:
    """
    Very basic dataclass, with 2D coordinates and a name.
    Feel free to add any field you'd like.
    """
    x: float
    y: float
    name: str

    def __getitem__(self, key):
        return [self.x, self.y][key]

    def __str__(self):
        return f"Point {self.name} ({self.x}, {self.y})"

    def __repr__(self):
        return self.__str__()

#######################################################################
#                      Define points and KDTree                       #
#######################################################################


points = [
    Point2D(1, 1, "A"),
    Point2D(1, 4, "B"),
    Point2D(4, 4, "C"),
    Point2D(4, 1, "D"),
]

#######################################################################
#                         Find nearest point                          #
#######################################################################


kd_tree = KDTree(points, 2)

# What's the closest to point (3, 3)?
distance2, nearest_point = kd_tree.get_nearest([3, 3])
print(nearest_point)
# Point C (4, 4)
print(nearest_point.x)
# 4
print(nearest_point.y)
# 4
print(nearest_point.name)
# C
print(distance2**0.5)
# 1.4142135623730951

EricDuminil avatar Apr 28 '22 15:04 EricDuminil