I have a 2D map divided in a grid of rectangles - about 45,000 of them - and a number of polygons/multipolygons derived from shapefiles (I currently read them with the shapefile library pyshp). Unfortunately, a few of these polygons are rather complex and made up by a large number of points (one of them has 640,000 points) and can have holes in them.
What I am trying to do is to check, for each of these polygons, which cell centers (the cells of my grid) fall inside that specific polygon. However, having about 45,000 cell centers and 150 polygons is taking quite a while to check everything using shapely. This is what I am doing, more or less:
# nx and ny are the number of cells in the x and y direction respectively
# x, y are the coordinates of the cell centers in the grid - numpy arrays
# shapes is a list of shapely shapes - either Polygon or MultiPolygon
# Point is a shapely.geometry.Point class
for j in range(ny):
for i in range(nx):
p = Point([x[i], y[j]])
for s in shapes:
if s.contains(p):
# The shape s contains the point p - remove the cell
Depending on the polygon in question, it takes between 200 microseconds to 80 milliseconds per check, and with more than 6 million checks to do the runtime goes easily into the hours.
I guess there must be a more intelligent way to handle this problem - I'd rather stay with shapely if possible, but any suggestion is most appreciated.
Thank you in advance.
