I have two arrays of polygons called grid_1
and grid_2
. grid_1
has 1,500,000 polygons and grid_2
has 60,000 polygons. As it is much too computationally expensive to calculate the intersecting polygon of each combination and then calculate its area, I instead would like to first calculate those polygons that intersect and then proceed. With nested for loops, it could look something like this:
from shapely.geometry import Polygon
from scipy import sparse
intersection_bool = sparse.lil_matrix((len(grid_1),len(grid_2))),astype("bool")
for i in range(len(grid_1)):
for j in range(len(grid_2)):
if i.intersects(j):
intersection_bool[i,j] = 1.0
However, this is still too computationally expensive. This question recommends the use of STRtrees from shapely. However, I am not sure what the best way to do this efficiently is. I have tried the implementation below, but it is slower than the nested for loops. I think STRtrees are my answer, I am just not sure how to use them most efficiently. Thank you!
from shapely.strtree import STRtree
from shapely.geometry import Polygon
from scipy import sparse
intersection_bool = sparse.lil_matrix((len(grid_1),len(grid_2))),astype("bool")
grid_1_tree = STRtree(grid_1)
for j in range(len(grid_2)):
result = tree.query(grid_2[j])
for i in range(len(grid_1)):
if grid_1[i] in result:
intersection_bool[i,j] = 1.0