I have several (order of M) points [(x0,y0),...,(xn,yn)]. I also have limited number of hexagons. I want to find each point falls in which hexagon. Using shapely this can be done for 1 point at a time so the loop below does the job. But is there any other way to do it faster?
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
zones = np.zeros(n)-1
for j,p in enumerate(points):
point = Point(p)
for i in range(len(poly_hex)): #poly_hex = list of hexagonal polygones
polygon = Polygon(poly_hex[i])
if polygon.contains(point):
zones[j] = int(i)
break
Some ideas to speed things up:
polygon = Polygon(poly_hex[i])
at each step of the inner loop. Calculate them once before the loop and store them in a list.p
and the centre of each hexagon, comparing to the radius. Only in case p
is less than the radius to the centre, do an explicit test to see whether it is inside the hexagon.p
is inside the convex hull of the hexagons.Some remarks:
zone[j] = int(i)
. You convert i
to an integer, while it already is an integer. Also, the way you store this, means a point can only be inside maximum one hexagon. Therefore, you can stop the loop as soon as you encountered such a hexagon. (There is also the rare case where a point is just on the edge between two hexagon. This might assign it to the first hexagon encountered. Or, due to rounding errors, even might have it outside both hexagons.) zones = np.zeros(n, dtype=int)-1
.
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.