| 1 |
|
|---|
| 2 |
import random |
|---|
| 3 |
import timeit |
|---|
| 4 |
|
|---|
| 5 |
try: |
|---|
| 6 |
import pkg_resources |
|---|
| 7 |
pkg_resources.require('Rtree') |
|---|
| 8 |
except: |
|---|
| 9 |
pass |
|---|
| 10 |
|
|---|
| 11 |
from rtree import Rtree |
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
class Point(object): |
|---|
| 15 |
def __init__(self, x, y): |
|---|
| 16 |
self.x = x |
|---|
| 17 |
self.y = y |
|---|
| 18 |
|
|---|
| 19 |
|
|---|
| 20 |
|
|---|
| 21 |
minx = 0 |
|---|
| 22 |
miny = 0 |
|---|
| 23 |
maxx = 6000000 |
|---|
| 24 |
maxy = 6000000 |
|---|
| 25 |
|
|---|
| 26 |
bounds = (minx, miny, maxx, maxy) |
|---|
| 27 |
count = 50000 |
|---|
| 28 |
points = [] |
|---|
| 29 |
index = Rtree() |
|---|
| 30 |
disk_index = Rtree('test', overwrite=1) |
|---|
| 31 |
for i in xrange(count): |
|---|
| 32 |
x = random.randrange(minx, maxx) * random.random() |
|---|
| 33 |
y = random.randrange(miny, maxy) * random.random() |
|---|
| 34 |
points.append(Point(x, y)) |
|---|
| 35 |
index.add(i, (x, y)) |
|---|
| 36 |
disk_index.add(i, (x,y)) |
|---|
| 37 |
|
|---|
| 38 |
bbox = (240000, 130000, 400000, 350000) |
|---|
| 39 |
|
|---|
| 40 |
print count, "points" |
|---|
| 41 |
print "Query box: ", bbox |
|---|
| 42 |
print "" |
|---|
| 43 |
|
|---|
| 44 |
|
|---|
| 45 |
s = """ |
|---|
| 46 |
hits = [p for p in points if p.x >= bbox[0] and p.x <= bbox[2] and p.y >= bbox[1] and p.y <= bbox[3]] |
|---|
| 47 |
""" |
|---|
| 48 |
t = timeit.Timer(stmt=s, setup='from __main__ import points, bbox') |
|---|
| 49 |
print "\nBrute Force:" |
|---|
| 50 |
print len([p for p in points if p.x >= bbox[0] and p.x <= bbox[2] and p.y >= bbox[1] and p.y <= bbox[3]]), "hits" |
|---|
| 51 |
print "%.2f usec/pass" % (1000000 * t.timeit(number=100)/100) |
|---|
| 52 |
|
|---|
| 53 |
|
|---|
| 54 |
|
|---|
| 55 |
s = """ |
|---|
| 56 |
hits = [points[id] for id in index.intersection(bbox)] |
|---|
| 57 |
""" |
|---|
| 58 |
t = timeit.Timer(stmt=s, setup='from __main__ import points, index, bbox') |
|---|
| 59 |
print "\nMemory-based Rtree Intersection:" |
|---|
| 60 |
print len([points[id] for id in index.intersection(bbox)]), "hits" |
|---|
| 61 |
print "%.2f usec/pass" % (1000000 * t.timeit(number=100)/100) |
|---|
| 62 |
|
|---|
| 63 |
|
|---|
| 64 |
s = """ |
|---|
| 65 |
hits = [points[id] for id in disk_index.intersection(bbox)] |
|---|
| 66 |
""" |
|---|
| 67 |
t = timeit.Timer(stmt=s, setup='from __main__ import points, disk_index, bbox') |
|---|
| 68 |
print "\Disk-based Rtree Intersection:" |
|---|
| 69 |
print len([points[id] for id in disk_index.intersection(bbox)]), "hits" |
|---|
| 70 |
print "%.2f usec/pass" % (1000000 * t.timeit(number=100)/100) |
|---|