def voronoi_finite_polygons_2d(vor, radius=None):
if vor.points.shape[<NUM_LIT:1>] != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>new_regions = []<EOL>new_vertices = vor.vertices.tolist()<EOL>center = vor.points.mean(axis=<NUM_LIT:0>)<EOL>if radius is None:<EOL><INDENT>radius = vor.points.ptp().max()*<NUM_LIT:2><EOL><DEDENT>all_ridges = {}<EOL>for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):<EOL><INDENT>all_ridges.setdefault(p1, []).append((p2, v1, v2))<EOL>all_ridges.setdefault(p2, []).append((p1, v1, v2))<EOL><DEDENT>for p1, region in enumerate(vor.point_region):<EOL><INDENT>vertices = vor.regions[region]<EOL>if all(v >= <NUM_LIT:0> for v in vertices):<EOL><INDENT>new_regions.append(vertices)<EOL>continue<EOL><DEDENT>ridges = all_ridges[p1]<EOL>new_region = [v for v in vertices if v >= <NUM_LIT:0>]<EOL>for p2, v1, v2 in ridges:<EOL><INDENT>if v2 < <NUM_LIT:0>:<EOL><INDENT>v1, v2 = v2, v1<EOL><DEDENT>if v1 >= <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>t = vor.points[p2] - vor.points[p1] <EOL>t /= np.linalg.norm(t)<EOL>n = np.array([-t[<NUM_LIT:1>], t[<NUM_LIT:0>]])  <EOL>midpoint = vor.points[[p1, p2]].mean(axis=<NUM_LIT:0>)<EOL>direction = np.sign(np.dot(midpoint - center, n)) * n<EOL>far_point = vor.vertices[v2] + direction * radius<EOL>new_region.append(len(new_vertices))<EOL>new_vertices.append(far_point.tolist())<EOL><DEDENT>vs = np.asarray([new_vertices[v] for v in new_region])<EOL>c = vs.mean(axis=<NUM_LIT:0>)<EOL>angles = np.arctan2(vs[:,<NUM_LIT:1>] - c[<NUM_LIT:1>], vs[:,<NUM_LIT:0>] - c[<NUM_LIT:0>])<EOL>new_region = np.array(new_region)[np.argsort(angles)]<EOL>new_regions.append(new_region.tolist())<EOL><DEDENT>return new_regions, np.asarray(new_vertices)<EOL>
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
    Input diagram
radius : float, optional
    Distance to 'points at infinity'.
Returns
-------
regions : list of tuples
    Indices of vertices in each revised Voronoi regions.
vertices : list of tuples
    Coordinates for revised Voronoi vertices. Same as coordinates
    of input vertices, with 'points at infinity' appended to the
    end.