forked from bendemott/Python-Shapely-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtree_area_example.py
82 lines (62 loc) · 2.36 KB
/
rtree_area_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'''
@author Ben
@file rtree_area_example.py
In this example we will compare Shapely AGAINST RTREE for performance
NOTE: to get this to work I had to install libspatialindex 1.5 from source
and then:
export LD_LIBRARY_PATH=/usr/local/lib
'''
import random, os, sys, time, numpy
from rtree import Rtree
# instantiate the Rtree class
RtreeIndex = Rtree()
import random, os, sys, time, numpy
from shapely import *
from shapely.geometry import Point
filename = 'rtree_radius_search.png'
numberOfPoints = 50000
gridWidth = 10000
gridHeight = 10000
shapePoints = []
circleRadius = random.randint(500, 1500)
circleX = random.randint(0, gridWidth)
circleY = random.randint(0, gridHeight)
boxLeft = circleX - circleRadius
boxRight = circleX + circleRadius
boxTop = circleY + circleRadius
boxBottom = circleY - circleRadius
sCircle = Point(circleX, circleY)
sCircle = sCircle.buffer(circleRadius, 16)
shapePoints = []
pointList = []
for i in range(numberOfPoints):
x = random.randint(0, gridWidth)
y = random.randint(0, gridHeight)
# Add the points to a python list of lists
pointList.append((x, y))
# Create a Shapely point object
iPoint = Point(x, y)
iPoint.idx = i # set our custom attribute. (if this doesnt work I have other ways)
shapePoints.append(iPoint)
# Add the point to an RTREE index
# index.add(id=id, (left, bottom, right, top))
# Note that this would work if the
RtreeIndex.add(i, (x, y, x, y))
matchingPoints = []
searchBench = time.time()
for idx, point in enumerate(shapePoints):
if sCircle.contains(point):
matchingPoints.append(idx)
searchBench = time.time() - searchBench
#-------------------------------------------------------------------------------
# NOW TEST RTREE
RtreeBench = time.time()
RtreeIndex
rtreeMatches = list(RtreeIndex.intersection((boxLeft, boxBottom, boxRight, boxTop)))
RtreeBench = time.time() - RtreeBench
print "\n\n"
print "SHAPELY: There were %d points within the circle [%d, %d] - r[%d]" % (len(matchingPoints), circleX, circleY, circleRadius)
print "SHAPELY: Calculation Took %s seconds for %s points" % (searchBench, numberOfPoints)
print "------------------------------------------------------------------"
print "RTREE: There were %d points within the box [x1:%d,y1:%d, x2:%d, y2:%d]" % (len(rtreeMatches), boxLeft, boxBottom, boxRight, boxTop)
print "RTREE: Calculation Took %s seconds for %s points\n" % (RtreeBench, numberOfPoints)