Ahoq / quadtree

Python implementation of a quadtree for 2D points.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Quadtree

Python quadtree implementation written as a learning exercise. It should not be taken too seriously and the whole implementation is self contained within 1 file. If you for any reason want a python implementation of a Quadtree, feel free to copy and paste quadtree.py into your project.

A quadtree should allow you to answer a query like Get me all the points within this region in log(n) time, here's the wikipedia (https://en.wikipedia.org/wiki/Quadtree).

The result could look something like this, where an area between -100 to 100 in x and -100 to 100 in y is covered by a quadtree. The tree has then been queried with a request to get all points within the green rectangle.

rect query plot

This example is generated by running example/draw_quadtree_query.py

The whole implementation is in the quadtree/quadtee.py file.

Dependencies

  • Python

The queadtree itself does not have any dependencies except for a reasonable python interpreter but for plotting the examples matplotlib is required.

Usage example

Clone the project and run the following

> python -m example.draw_quadtree_query

From within your scripts,

from quadtree import QuadTree, Point

points = [] # List of all the points, fill this with your data
qt = QuadTree() # Initialize the quadtree

# For now we will fill our list of points with generated data
# Make equally spaced 2D points
for x in range(-100, 100, 10):
  for y in range(-100,100, 10):
    # Generate some noise to make things interresting
    rx = random.normalvariate(0, 20)
    ry = random.normalvariate(0, 20)
    # Add noisy point to list of points
    points.append(Point(x + rx, y + ry))

# Add points to quadtree
for p in points:
  qt.add_point(p)

# Query the tree for points a particular location

# Rectangle example
bottomLeft = Point(-23, -48)
topRight = Point(33, -8)
points_in_rect = qt.get_points_in_rect(bottomLeft, topRight)

# Circle example
circle = Point(-23, -18, 30) # x= -23, y= -18, radius = 30
points_in_circle = qt.get_points_in_circle(circle)

About

Python implementation of a quadtree for 2D points.


Languages

Language:Python 100.0%