简体   繁体   中英

How can I efficiently find every combination of intersection of two arrays of polygons?

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

It is not yet the ideal answer, but something that sped up my code ~3 times was putting my polygons into a geopandas.GeoSeries which can vectorize the intersects function and bring me down to one for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM