Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def voronoi_finite_polygons_2d(vor, radius=None):
- new_regions = []
- new_vertices = vor.vertices.tolist()
- center = vor.points.mean(axis=0)
- if radius is None:
- radius = vor.points.ptp().max()
- # Construct a map containing all ridges for a given point
- all_ridges = {}
- for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
- all_ridges.setdefault(p1, []).append((p2, v1, v2))
- all_ridges.setdefault(p2, []).append((p1, v1, v2))
- # Reconstruct infinite regions
- for p1, region in enumerate(vor.point_region):
- vertices = vor.regions[region]
- if all(v >= 0 for v in vertices):
- # finite region
- new_regions.append(vertices)
- continue
- # reconstruct a non-finite region
- ridges = all_ridges[p1]
- new_region = [v for v in vertices if v >= 0]
- for p2, v1, v2 in ridges:
- if v2 < 0:
- v1, v2 = v2, v1
- if v1 >= 0:
- # finite ridge: already in the region
- continue
- # Compute the missing endpoint of an infinite ridge
- t = vor.points[p2] - vor.points[p1] # tangent
- t /= np.linalg.norm(t)
- n = np.array([-t[1], t[0]]) # normal
- midpoint = vor.points[[p1, p2]].mean(axis=0)
- direction = np.sign(np.dot(midpoint - center, n)) * n
- far_point = vor.vertices[v2] + direction * radius
- new_region.append(len(new_vertices))
- new_vertices.append(far_point.tolist())
- # sort region counterclockwise
- vs = np.asarray([new_vertices[v] for v in new_region])
- c = vs.mean(axis=0)
- angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0])
- new_region = np.array(new_region)[np.argsort(angles)]
- # finish
- new_regions.append(new_region.tolist())
- return new_regions, np.asarray(new_vertices)
- def get_polygons(X, Y, yard_line):
- points = list(zip(X, Y))
- vor = Voronoi(points)
- regions, vertices = voronoi_finite_polygons_2d(vor)
- x_diff = max(yard_line-vor.min_bound[0], vor.max_bound[0]-yard_line)
- min_x = yard_line - x_diff - 1
- max_x = yard_line + x_diff + 1
- min_y = vor.min_bound[1]
- max_y = vor.max_bound[1]
- mins = np.tile((min_x, min_y), (vertices.shape[0], 1))
- bounded_vertices = np.max((vertices, mins), axis=0)
- maxs = np.tile((max_x, max_y), (vertices.shape[0], 1))
- bounded_vertices = np.min((bounded_vertices, maxs), axis=0)
- box_vertices = [[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]
- box = Polygon(box_vertices)
- polygons = []
- for region in regions:
- polygon = vertices[region]
- try:
- poly = Polygon(polygon)
- poly = poly.intersection(box)
- # Currently getting this error for PlayID 20181014052141
- except shapely.geos.TopologicalError:
- polygon = np.clip(polygon, -1000000000,1000000000)
- poly = Polygon(polygon)
- poly = poly.intersection(box)
- polygons.append(poly)
- return polygons
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement