Example #1
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    map = pygame.Surface((map_width, map_height))
    pygame.display.set_caption("quadtree")
    font = pygame.font.SysFont('arial', 20)

    clock = pygame.time.Clock()

    particles = Group([
        Particle(
            random.gauss(map_width / 2, 150) % map_width,
            random.gauss(map_height / 2, 150) % map_height, 4, map)
        for _ in range(1000)
    ])

    qtree = Quadtree(map.get_rect(), 4, map)
    for p in particles:
        qtree.insert(p)

    while True:
        clock.tick(60)
        fps_text = font.render(f'fps:{int(clock.get_fps())}', True,
                               THECOLORS['white'])
        fps_rect = fps_text.get_rect()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        qtree = Quadtree(map.get_rect(), 4, map)
        for p in particles:
            qtree.insert(p)

        particles.update()

        for p in particles:
            p.highlight = False
            query_rect = Rect(p.rect.x, p.rect.y, p.radius * 2, p.radius * 2)
            if len(qtree.query(query_rect)) != 1:
                p.highlight = True

        map.fill(THECOLORS['black'])
        particles.draw(map)

        pygame.transform.scale(map, (width, height), screen)

        screen.blit(fps_text, fps_rect)

        pygame.display.update()
Example #2
0
def test_quadtree_buildup(points: List[Point]) -> float:
    tracemalloc.start()
    starting_mem, _ = tracemalloc.get_traced_memory()
    tree = Quadtree(points)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak - starting_mem
Example #3
0
def _get_tree(paths, closed):
    """ Add all paths to the tree and create mapping from ids of elements added to the
    tree to the elements data:
    Closed paths:
        [id of path, 1st point of segment, 2nd point of segment]
    Open paths
        [id of path, point of segment]
    """

    # TODO: use models aabb?
    aabb = get_aabb(np.concatenate(paths))
    tree = Quadtree([aabb.min[0], aabb.min[1], aabb.max[0], aabb.max[1]])
    mapping = {}

    for path in paths:
        if closed:
            for i, j in zip(range(-1, len(path) - 1), range(len(path))):
                # add whole edge into the tree
                _add_edge(tree, mapping, path, i, j)

        else:
            _add_point(tree, mapping, path, 0)
            _add_point(tree, mapping, path, -1)

    tree.prune()
    return tree, mapping
Example #4
0
    def __init__(self, definition_file, points):
        # Open definition file and background image
        definition = ElementTree.parse(open(definition_file)).getroot()
        map_file = os.path.join(
            os.path.split(definition_file)[0], definition.attrib['bg'])
        self.background = Image.open(map_file)

        self.north = math.radians(float(definition.attrib['maxlat']))
        self.south = math.radians(float(definition.attrib['minlat']))
        self.west = math.radians(float(definition.attrib['minlon']))
        self.east = math.radians(float(definition.attrib['maxlon']))

        # Store ranges color and distance
        self.ranges = [(float(r.attrib['distance']), (int(r.attrib['red']),
                                                      int(r.attrib['green']),
                                                      int(r.attrib['blue'])))
                       for r in definition.getiterator("range")]

        self.width, self.height = self.background.size
        self.points = points

        # Creating top quadtree element
        self.grid = Quadtree(self.north, self.south, self.west, self.east, 6)
        for point in points:
            self.grid.add(point)

        # Precompute latitude and longitude at each row and column
        self.pixel_lons = [
            self.west + (self.east - self.west) *
            (float(i) / float(self.width)) for i in range(self.width)
        ]
        self.pixel_lats = [
            self.north - (self.north - self.south) *
            (float(j) / float(self.height)) for j in range(self.height)
        ]
def test_quadtree_search(points: List[Point],
                         rectangles: List[Rectangle]) -> List[float]:
    tree = Quadtree(points)

    def time_individual(rectangle: Rectangle) -> float:
        start_time = default_timer()
        tree.find(rectangle)
        end_time = default_timer()
        return end_time - start_time

    return list(map(time_individual, rectangles))
Example #6
0
def update_boids():

    tree = Quadtree(b[0], 0, 0, WIDTH, HEIGHT)
    for i in range(1, len(b)):
        tree.insert(b[i])

    for boid in b:
        accel = [0, 0]
        possible_close_boids = tree.findInCircle(boid.pos[0], boid.pos[1], NEIGHBORHOOD_THRESHOLD)
        if len(possible_close_boids) > 1:
            accel = boid.compute_acceleration(possible_close_boids, SEPARATION_THRESHOLD, C, A, S)
        if Quadtree.pointInCircle(tree, boid.pos[0], boid.pos[1], mouse[0], mouse[1], NEIGHBORHOOD_THRESHOLD):
            accel = list(map(sum, zip(accel, boid.avoid(mouse))))
        boid.update(WIDTH, HEIGHT, accel)
Example #7
0
    def __init__(self, canvas=None):
        self._matrix = Matrix()
        self._painter = DefaultPainter(self)
        self._bounding_box_painter = BoundingBoxPainter(self)

        # Handling selections.
        ### TODO: Move this to a context?
        self._selected_items = set()
        self._focused_item = None
        self._hovered_item = None
        self._dropzone_item = None
        ###/

        self._qtree = Quadtree()
        self._bounds = Rectangle(0, 0, 0, 0)

        self._canvas = None
        if canvas:
            self._set_canvas(canvas)
    def __init__(self, MI, NI, granulometry, matrixLabel):

        self.MI = MI
        self.NI = NI
        self.granulometry = granulometry
        self.matrixLabel = matrixLabel

        xv = np.linspace(0, self.MI - 1, self.MI,
                         endpoint=True).astype(np.int32)
        yv = np.linspace(0, self.NI - 1, self.NI,
                         endpoint=True).astype(np.int32)
        X, Y = np.int32(np.meshgrid(xv, yv))

        self.coords = {(x, y) for x, y in zip(X.ravel(), Y.ravel())}

        depth = 4
        self.qtree = Quadtree(int(depth), Rect(0, 0, int(self.MI),
                                               int(self.NI)))
        (self.XX, self.YY) = np.meshgrid(range(0, self.NI), range(0, self.MI))
Example #9
0
               nargs='?',
               default=10)
p.add_argument("-p",
               "--maxpoints",
               help="the maximum number of points in each area (required)",
               type=int,
               required=True)
p.add_argument("-u",
               "--upper",
               help="upper left point (required)",
               type=float,
               nargs=2,
               metavar=('X', 'Y'),
               required=True)
p.add_argument("-l",
               "--lower",
               help="loewr right point (required)",
               type=float,
               nargs=2,
               metavar=('X', 'Y'),
               required=True)
args = p.parse_args()

X = read_data(args.infile)

qtree = Quadtree(args.upper[0], args.upper[1], args.lower[0], args.lower[1],
                 args.maxpoints, args.maxdepth)
qtree.fit(X)

pickle.dump(qtree, args.outfile)
def test_quadtree_buildup(points: List[Point]) -> float:
    start_time = default_timer()
    _ = Quadtree(points)
    end_time = default_timer()
    return end_time - start_time
Example #11
0
from quadtree import Quadtree
import numpy as np
import time

np.random.seed(5)

p = Quadtree(0, 0, 100, 100, 5)

N = 5000000
data = 100 * np.random.random(size=(N, 2))
data = data.astype(np.float32)

start = time.time()
p.insert(data)
print(time.time() - start)

start = time.time()
r = .1
d = p.select_from(data, r)
print(time.time() - start)

print(d[0])
print()
Example #12
0
from quadtree import Quadtree, RGB
from PIL import Image


def is_valid_read_file(parser, arg):
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return arg


parser = argparse.ArgumentParser()

parser.add_argument('image',
                    help='image file',
                    type=lambda x: is_valid_read_file(parser, x))
parser.add_argument('operation', help='operation to do on image', type=str)

args = parser.parse_args()
img_raw = Image.open(args.image)
img_rgb = img_raw.convert('RGB')
width, height = img_rgb.size
shape = (height, width)
colors = np.empty(shape, dtype=RGB)
pixels = img_rgb.load()
for h in range(height):
    for w in range(width):
        colors[h][w] = RGB(pixels[w, h])
qtree = Quadtree(colors)
modified = qtree.outline()
Example #13
0
gmaxx = GALAXY_WIDTH
gmaxy = GALAXY_HEIGHT

testimage = Image.new('RGBA', (int(gmaxx), int(gmaxy)))
nebulae = Image.new('RGB', (int(gmaxx), int(gmaxy)))
draw = ImageDraw.Draw(testimage)
draw2 = ImageDraw.Draw(nebulae)
povfile = open("stars.pov", "w")
squares = {}
numstars = 0
totalstars = 0
sectors = {}
planets = []
nplanets = []

tree = Quadtree((gminx, gminy, gmaxx, gmaxy), maxdepth=16)
ntree = Quadtree((gminx, gminy, gmaxx, gmaxy), maxdepth=16)


def is_nan2(num):
    return str(num) == "nan"


def setsize(color):
    basesize = .05
    sizemods = {'blue': 2.0, 'red': .7, 'yellow': 1.0, 'orange': 4, 'green': 4}

    size = basesize * sizemods[color]
    if color == 'red' and random.random() < .011:
        # red giant star
        size *= random.randint(4, 5)
Example #14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', type=int, action='store',
            dest='data_num', help='choose which data set to use')
    if len(sys.argv) != 3:
        print 'Command e.g.: python findNearPlace.py -d 0(1,2)'
        sys.exit(1)

    para = parser.parse_args()
    if para.data_num == 0:
        location_infile = settings["ROOT_PATH"] + settings["SRC_DATA_FILE1_1"]
        nearplace_outfile = settings["ROOT_PATH"] + settings["NEAR_PLACE_FILE1"]
    elif para.data_num == 1:
        location_infile = settings["ROOT_PATH"] + settings["SRC_DATA_FILE2_1"]
        nearplace_outfile = settings["ROOT_PATH"] + settings["NEAR_PLACE_FILE2"]
    elif para.data_num == 2:
        location_infile = settings["ROOT_PATH"] + settings["SRC_DATA_FILE3_3"]
        nearplace_outfile = settings["ROOT_PATH"] + settings["NEAR_PLACE_FILE3"]
    else:
        print 'Invalid choice of data set'
        sys.exit(1)

    loc_latlng = {}
    try:
        for entry in csv.reader(open(location_infile, 'rU')):
            pid, lat, lng = int(entry[0]), float(entry[2]), float(entry[3])
            loc_latlng[pid] = (lat, lng)
    except:
        print entry
        sys.exit(1)

    # directly scanning all POIs to get answer, which is too slow
    '''writer = csv.writer(open(nearplace_outfile, "w"), lineterminator="\r\n")
    pids = loc_latlng.keys()
    for i in xrange(len(pids)):
        pid1 = pids[i]
        near_place = []
        for j in xrange(len(pids)):
            pid2 = pids[j]
            dis = distance.distance(loc_latlng[pid1], loc_latlng[pid2]).miles
            if dis < settings["DISTANCE_THRESHOLD"]:
                near_place.append(pid2)
        writer.writerow([pid1] + near_place)
        print i'''

    # quad tree
    index_extent = (-90, -180, 90, 180)
    index = Quadtree(index_extent)
    for pid in loc_latlng:
        index.add(pid, loc_latlng[pid])

    for pid in loc_latlng:
        start_time = time.clock()
        pid_set = findNearPlaceByQuadtree(loc_latlng,
                                          loc_latlng[pid],
                                          index.struct(),
                                          settings["DISTANCE_THRESHOLD"])
        end_time = time.clock()
        print "Time Cost: %f(s)" % (end_time-start_time)
        raw_input()
        print len(pid_set)
        raw_input()
Example #15
0
        pt.normal = -pt.position / np.sqrt(np.dot(pt.position, pt.position))
    return pc


def get_dist_func(pc):
    def dist(x, y):
        pt = Point(x, y, 0)
        neighbors = pc.nearest_neighbors(pt, 50)
        d = 0
        for pt2 in neighbors:
            diff = pt.position - pt2.position
            d += np.dot(diff, pt2.normal)
        return d

    return dist


if __name__ == '__main__':
    pc = get_circle()
    dist = get_dist_func(pc)
    quadtree = Quadtree(pc.points, 4)
    contour = quadtree.compute_contour(dist)
    print 'Found %d edges' % len(contour)
    # quadtree.display()
    for (pt1, pt2) in contour:
        x1, y1, _ = pt1.position
        x2, y2, _ = pt2.position
        plt.plot([x1, x2], [y1, y2])
    # plt.show()
    quadtree.display()
Example #16
0
import numpy as np
import matplotlib.pyplot as plt
from quadtree import Point, Rectangle, Quadtree

DPI = 72
np.random.seed(60)

width, height = 600, 400

N = 500
coords = np.random.randn(N, 2) * height / 3 + (width / 2, height / 2)
points = [Point(*coord) for coord in coords]
print(len(points))
center = Point(width / 2, height / 2)
domain = Rectangle(center, height, width)
qtree = Quadtree(domain, 3)
for point in points:
    qtree.insert(point)

print('Number of points in the domain =',
      len(qtree))  # it might not be adding all the points for some reason

fig = plt.figure(figsize=(700 / DPI, 500 / DPI), dpi=DPI)
ax = plt.subplot()
ax.set_xlim(0, width)
ax.set_ylim(0, height)
qtree.draw(ax)

ax.scatter([p.x for p in points], [p.y for p in points], s=4)
ax.set_xticks([])
ax.set_yticks([])