Demonstrates the use of KD-Tree by building it from random points in a 10-dimensional hypercube and performing a nearest neighbor search.
()
| 14 | |
| 15 | |
| 16 | def main() -> None: |
| 17 | """ |
| 18 | Demonstrates the use of KD-Tree by building it from random points |
| 19 | in a 10-dimensional hypercube and performing a nearest neighbor search. |
| 20 | """ |
| 21 | num_points: int = 5000 |
| 22 | cube_size: float = 10.0 # Size of the hypercube (edge length) |
| 23 | num_dimensions: int = 10 |
| 24 | |
| 25 | # Generate random points within the hypercube |
| 26 | points: np.ndarray = hypercube_points(num_points, cube_size, num_dimensions) |
| 27 | hypercube_kdtree = build_kdtree(points.tolist()) |
| 28 | |
| 29 | # Generate a random query point within the same space |
| 30 | rng = np.random.default_rng() |
| 31 | query_point: list[float] = rng.random(num_dimensions).tolist() |
| 32 | |
| 33 | # Perform nearest neighbor search |
| 34 | nearest_point, nearest_dist, nodes_visited = nearest_neighbour_search( |
| 35 | hypercube_kdtree, query_point |
| 36 | ) |
| 37 | |
| 38 | # Print the results |
| 39 | print(f"Query point: {query_point}") |
| 40 | print(f"Nearest point: {nearest_point}") |
| 41 | print(f"Distance: {nearest_dist:.4f}") |
| 42 | print(f"Nodes visited: {nodes_visited}") |
| 43 | |
| 44 | |
| 45 | if __name__ == "__main__": |
no test coverage detected