def test_issue_7b(): centroids = np.array([[496712, 232672], [497987, 235942], [496425, 230252], [497482, 234933], [499331, 238351], [496081, 231033], [497090, 233846], [496755, 231645], [498604, 237018]]) n_pts = len(centroids) polygon = Polygon([[495555, 230875], [496938, 235438], [499405, 239403], [499676, 239474], [499733, 237877], [498863, 237792], [499120, 237335], [498321, 235010], [497295, 233185], [497237, 231359], [496696, 229620], [495982, 230047], [496154, 230347], [496154, 230347], [495555, 230875]]) region_polys, region_pts = voronoi_regions_from_coords(centroids, polygon) assert isinstance(region_polys, dict) assert isinstance(region_pts, dict) assert len(region_polys) == len(region_pts) == n_pts assert all([ len(pts_in_region) == 1 for pts_in_region in region_pts.values() ]) # no duplicates fig, ax = subplot_for_map(show_spines=True) plot_voronoi_polys_with_points_in_area(ax, polygon, region_polys, centroids, region_pts) return fig
def test_voronoi_geopandas_with_plot(): world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities')) # focus on South America, convert to World Mercator (unit: meters) south_am = world[world.continent == 'South America'].to_crs(epsg=3395) cities = cities.to_crs( south_am.crs) # convert city coordinates to same CRS! # create the bounding shape as union of all South American countries' shapes south_am_shape = unary_union(south_am.geometry) south_am_cities = cities[cities.geometry.within( south_am_shape)] # reduce to cities in South America # convert the pandas Series of Point objects to NumPy array of coordinates coords = points_to_coords(south_am_cities.geometry) # calculate the regions region_polys, region_pts = voronoi_regions_from_coords(coords, south_am_shape, per_geom=False) # full checks for voronoi_regions_from_coords() are done in test_voronoi_regions_from_coords_italy() assert isinstance(region_polys, dict) assert isinstance(region_pts, dict) assert len(region_polys) == len(region_pts) == len(coords) # generate plot fig, ax = subplot_for_map(show_spines=True) plot_voronoi_polys_with_points_in_area(ax, south_am_shape, region_polys, coords, region_pts) return fig
def test_voronoi_spain_area_with_plot(): area_shape = _get_country_shape('Spain') coords = _rand_coords_in_shape(area_shape, 20) # generate Voronoi regions region_polys, region_pts = voronoi_regions_from_coords(coords, area_shape) # full checks for voronoi_regions_from_coords() are done in test_voronoi_regions_from_coords_italy() assert isinstance(region_polys, dict) assert isinstance(region_pts, dict) assert len(region_polys) == len(region_pts) assert 0 < len(region_polys) <= 20 # generate covered area region_areas = calculate_polygon_areas( region_polys, m2_to_km2=True) # converts m² to km² assert isinstance(region_areas, dict) assert set(region_areas.keys()) == set(region_polys.keys()) # generate plot fig, ax = subplot_for_map(show_x_axis=True, show_y_axis=True) voronoi_labels = {k: '%d km²' % round(a) for k, a in region_areas.items()} plot_voronoi_polys_with_points_in_area(ax, area_shape, region_polys, coords, region_pts, voronoi_labels=voronoi_labels, voronoi_label_fontsize=7, voronoi_label_color='gray') return fig
def test_voronoi_italy_with_plot(n_pts, per_geom): area_shape = _get_country_shape('Italy') coords = _rand_coords_in_shape(area_shape, n_pts) # generate Voronoi regions region_polys, region_pts = voronoi_regions_from_coords(coords, area_shape, per_geom=per_geom) # full checks for voronoi_regions_from_coords() are done in test_voronoi_regions_from_coords_italy() assert isinstance(region_polys, dict) assert isinstance(region_pts, dict) assert len(region_polys) == len(region_pts) assert 0 < len(region_polys) <= n_pts # generate plot fig, ax = subplot_for_map(show_spines=True) plot_voronoi_polys_with_points_in_area(ax, area_shape, region_polys, coords, region_pts, point_labels=list( map(str, range(len(coords))))) return fig
def test_issue_7b(): centroids = np.array([[496712, 232672], [497987, 235942], [496425, 230252], [497482, 234933], [499331, 238351], [496081, 231033], [497090, 233846], [496755, 231645], [498604, 237018]]) polygon = Polygon([[495555, 230875], [496938, 235438], [499405, 239403], [499676, 239474], [499733, 237877], [498863, 237792], [499120, 237335], [498321, 235010], [497295, 233185], [497237, 231359], [496696, 229620], [495982, 230047], [496154, 230347], [496154, 230347], [495555, 230875]]) poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( centroids, polygon) assert isinstance(poly_shapes, list) assert 0 < len(poly_shapes) <= len(centroids) assert all([isinstance(p, (Polygon, MultiPolygon)) for p in poly_shapes]) assert np.array_equal(points_to_coords(pts), centroids) assert isinstance(poly_to_pt_assignments, list) assert len(poly_to_pt_assignments) == len(poly_shapes) assert all([isinstance(assign, list) for assign in poly_to_pt_assignments]) assert all([len(assign) == 1 for assign in poly_to_pt_assignments ]) # in this case there is a 1:1 correspondance fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, polygon, poly_shapes, centroids, poly_to_pt_assignments) return fig
def test_voronoi_sweden_duplicate_points_with_plot(): area_shape = _get_country_shape('Sweden') coords = _rand_coords_in_shape(area_shape, 20) # duplicate a few points rand_dupl_ind = np.random.randint(len(coords), size=10) coords = np.concatenate((coords, coords[rand_dupl_ind])) n_pts = len(coords) # generate Voronoi regions region_polys, region_pts = voronoi_regions_from_coords(coords, area_shape) # full checks for voronoi_regions_from_coords() are done in test_voronoi_regions_from_coords_italy() assert isinstance(region_polys, dict) assert isinstance(region_pts, dict) assert 0 < len(region_polys) <= n_pts assert 0 < len(region_pts) <= n_pts assert all([ 0 < len(pts_in_region) <= 10 for pts_in_region in region_pts.values() ]) # make point labels: counts of duplicate assignments per points count_per_pt = { pt_indices[0]: len(pt_indices) for pt_indices in region_pts.values() } pt_labels = list(map(str, count_per_pt.values())) distinct_pt_coords = coords[np.asarray(list(count_per_pt.keys()))] # highlight voronoi regions with point duplicates vor_colors = { i_poly: (1, 0, 0) if len(pt_indices) > 1 else (0, 0, 1) for i_poly, pt_indices in region_pts.items() } # generate plot fig, ax = subplot_for_map(show_spines=True) plot_voronoi_polys_with_points_in_area( ax, area_shape, region_polys, distinct_pt_coords, plot_voronoi_opts={'alpha': 0.2}, plot_points_opts={'alpha': 0.4}, voronoi_color=vor_colors, voronoi_edgecolor=(0, 0, 0, 1), point_labels=pt_labels, points_markersize=np.square(np.array(list(count_per_pt.values()))) * 10) return fig
def test_voronoi_sweden_duplicate_points_with_plot(): area_shape = _get_country_shape('Sweden') coords = _rand_coords_in_shape(area_shape, 20) # duplicate a few points rand_dupl_ind = np.random.randint(len(coords), size=10) coords = np.concatenate((coords, coords[rand_dupl_ind])) poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, area_shape, accept_n_coord_duplicates=10) assert isinstance(poly_shapes, list) assert 0 < len(poly_shapes) <= 20 assert all([isinstance(p, (Polygon, MultiPolygon)) for p in poly_shapes]) assert np.array_equal(points_to_coords(pts), coords) assert isinstance(poly_to_pt_assignments, list) assert len(poly_to_pt_assignments) == len(poly_shapes) assert all([isinstance(assign, list) for assign in poly_to_pt_assignments]) assert all([0 < len(assign) <= 10 for assign in poly_to_pt_assignments ]) # in this case there is not # everywhere a 1:1 correspondance pts_to_poly_assignments = np.array( get_points_to_poly_assignments(poly_to_pt_assignments)) # make point labels: counts of duplicates per points count_per_pt = [ sum(pts_to_poly_assignments == i_poly) for i_poly in pts_to_poly_assignments ] pt_labels = list(map(str, count_per_pt)) # highlight voronoi regions with point duplicates count_per_poly = np.array(list(map(len, poly_to_pt_assignments))) vor_colors = np.repeat('blue', len(poly_shapes)) # default color vor_colors[count_per_poly > 1] = 'red' # hightlight color fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area( ax, area_shape, poly_shapes, coords, plot_voronoi_opts={'alpha': 0.2}, plot_points_opts={'alpha': 0.4}, voronoi_color=list(vor_colors), point_labels=pt_labels, points_markersize=np.array(count_per_pt) * 10) return fig
def main(): df = pd.read_csv('data.csv', header=None) lon = df[1] lat = df[2] #points = np.delete(df.values, 0, 1) #print(points) box = (0, 0, 15, 15) area = [[0, 0], [15, 0], [15, 13], [13, 13], [13, 15], [0, 15]] ext = [(0, 0), (15, 0), (15, 13), (13, 13), (13, 15), (0, 15)] int = [(11, 12), (12, 12), (12, 11), (11, 11)] grint = [(1, 14), (1, 12), (3, 12), (3, 14)] area_shape = Polygon(ext, [grint, int]) coords = np.random.randint(1, 12, size=(3, 2)) print(coords) points = [] for point in coords: if area_shape.contains(Point(point)) is True: points.append(point) points = coords #points = [point for point in coords if area_shape.contains(Point(point)) is True] print("points:") print(area_shape) vor = spatial.Voronoi(points) #regions, vertices = voronoi_finite_polygons_2d(vor) poly_shapes, pts, poly_to_pt_assignment = voronoi_regions_from_coords( points, area_shape) print(type(poly_shapes)) print(dir(pts)) print(poly_to_pt_assignment) fig, ax = subplot_for_map() plt.figure(dpi=96, figsize=(20 / 96, 20 / 96)) plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, points, poly_to_pt_assignment) polygons = []
def plotVoronoi(cityCoords, boundaryShape, regionPolys, regionPoints, saveName=None): """plot the voronoi diagram. Params: cityCoords (numpy ndarray) : the seeds converted to proper coordinate system for the diagram boundaryShape (shapely polygon) : the boundary simplified or converted to a single outer ring polygon regionPolys (dict) : a dict of the internal polygons created around each seed regionPoints (dict) : a dict of the points used in the creation of the polygon saveName (string) : path / filename to save file for plot if wanted """ fig, ax = subplot_for_map(figsize=(8, 6)) plot_voronoi_polys_with_points_in_area( ax, boundaryShape, regionPolys, cityCoords, regionPoints ) if saveName: plt.savefig(saveName, bbox_inches="tight") plt.show()
def test_voronoi_geopandas_with_plot(): world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities')) # focus on South America, convert to World Mercator (unit: meters) south_am = world[world.continent == 'South America'].to_crs(epsg=3395) cities = cities.to_crs( south_am.crs) # convert city coordinates to same CRS! # create the bounding shape as union of all South American countries' shapes south_am_shape = cascaded_union(south_am.geometry) south_am_cities = cities[cities.geometry.within( south_am_shape)] # reduce to cities in South America # convert the pandas Series of Point objects to NumPy array of coordinates coords = points_to_coords(south_am_cities.geometry) # calculate the regions poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, south_am_shape) assert isinstance(poly_shapes, list) assert 0 < len(poly_shapes) <= len(coords) assert all([isinstance(p, (Polygon, MultiPolygon)) for p in poly_shapes]) assert np.array_equal(points_to_coords(pts), coords) assert isinstance(poly_to_pt_assignments, list) assert len(poly_to_pt_assignments) == len(poly_shapes) assert all([isinstance(assign, list) for assign in poly_to_pt_assignments]) assert all([len(assign) == 1 for assign in poly_to_pt_assignments ]) # in this case there is a 1:1 correspondance fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, south_am_shape, poly_shapes, pts, poly_to_pt_assignments) return fig
def test_voronoi_spain_area_with_plot(): area_shape = _get_country_shape('Spain') coords = _rand_coords_in_shape(area_shape, 20) poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, area_shape) assert isinstance(poly_shapes, list) assert 0 < len(poly_shapes) <= 20 assert all([isinstance(p, (Polygon, MultiPolygon)) for p in poly_shapes]) assert np.array_equal(points_to_coords(pts), coords) assert isinstance(poly_to_pt_assignments, list) assert len(poly_to_pt_assignments) == len(poly_shapes) assert all([isinstance(assign, list) for assign in poly_to_pt_assignments]) assert all([len(assign) == 1 for assign in poly_to_pt_assignments ]) # in this case there is a 1:1 correspondance poly_areas = calculate_polygon_areas(poly_shapes, m2_to_km2=True) # converts m² to km² assert isinstance(poly_areas, np.ndarray) assert np.issubdtype(poly_areas.dtype, np.float_) assert len(poly_areas) == len(poly_shapes) assert np.all(poly_areas > 0) fig, ax = subplot_for_map(show_x_axis=True, show_y_axis=True) voronoi_labels = ['%d km²' % round(a) for a in poly_areas] plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords, poly_to_pt_assignments, voronoi_labels=voronoi_labels, voronoi_label_fontsize=7, voronoi_label_color='gray') return fig
def test_voronoi_italy_with_plot(): area_shape = _get_country_shape('Italy') coords = _rand_coords_in_shape(area_shape, 100) poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, area_shape) assert isinstance(poly_shapes, list) assert 0 < len(poly_shapes) <= 100 assert all([isinstance(p, (Polygon, MultiPolygon)) for p in poly_shapes]) assert np.array_equal(points_to_coords(pts), coords) assert isinstance(poly_to_pt_assignments, list) assert len(poly_to_pt_assignments) == len(poly_shapes) assert all([isinstance(assign, list) for assign in poly_to_pt_assignments]) assert all([len(assign) == 1 for assign in poly_to_pt_assignments ]) # in this case there is a 1:1 correspondance fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords, poly_to_pt_assignments) return fig
sum(pts_to_poly_assignments == i_poly) for i_poly in pts_to_poly_assignments ] pt_labels = list(map(str, count_per_pt)) # highlight voronoi regions with point duplicates count_per_poly = np.array(list(map(len, poly_to_pt_assignments))) vor_colors = np.repeat('blue', len(poly_shapes)) # default color vor_colors[count_per_poly > 1] = 'red' # hightlight color fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area( ax, area_shape, poly_shapes, coords, plot_voronoi_opts={'alpha': 0.2}, plot_points_opts={'alpha': 0.4}, voronoi_color=list(vor_colors), point_labels=pt_labels, points_markersize=np.array(count_per_pt) * 10) ax.set_title( '%d random points (incl. %d duplicates)\nand their Voronoi regions in %s' % (len(pts), N_DUPL, COUNTRY)) plt.tight_layout() plt.savefig('duplicate_points.png') plt.show()
coords = np.vstack((randx, randy)).T # use only the points inside the geographic area pts = [p for p in coords_to_points(coords) if p.within(area_shape)] # converts to shapely Point print('will use %d of %d randomly generated points that are inside geographic area' % (len(pts), N_POINTS)) coords = points_to_coords(pts) # convert back to simple NumPy coordinate array del pts # # calculate the Voronoi regions, cut them with the geographic area shape and assign the points to them # poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords(coords, area_shape) # # plotting # fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords, poly_to_pt_assignments) #plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords) # monocolor ax.set_title('%d random points and their Voronoi regions in %s' % (len(pts), COUNTRY)) plt.tight_layout() plt.savefig('random_points_across_italy.png') plt.show()
def update(self, outer_pos, inner_pos, UPDATE, EPS=0.1): global t t = time.time() - start outputs = [] global FLAG if FLAG: fig, ax = subplot_for_map() global ax, fig FLAG = False def reshape_coords(coords): new_coords = [] for p in poly_shapes: for n in coords: m = Point(n) if m.within(p): new_coords.append(n) return new_coords def reshape_centroids(centroids): new_centroids = [] for p in poly_shapes: for n in centroids: m = Point(n) if m.within(p): new_cent roids.append(n) return new_centroids def match_pair(poly_shapes, coords, new_centroids): sorted_coords = [] points = coords_to_points(coords) for i, p in enumerate(points): c = coords[i] #print("c: ", c[0],c[1]) for j, poly in enumerate(poly_shapes): if p.within(poly): pair = new_centroids[j] sorted_coords.append(pair) return sorted_coords N = 4 #len(inner_pos) area_shape = Polygon(outer_pos) #update_outer(outer_pos) # generate some random points within the bounds minx, miny, maxx, maxy = area_shape.bounds pts = [p for p in coords_to_points(inner_pos) if p.within(area_shape)] # converts to shapely Point while len(pts) < N: #isinstance(compensated, int): inner_pos = points_to_coords(pts) print('%d of %d drone"s pos is available' % (len(pts), N)) #print("compensated!!", compensated, type(compensated)) randx = np.random.uniform(minx, maxx, N - len(pts)) randy = np.random.uniform(miny, maxy, N - len(pts)) compensated = np.vstack((randx, randy)).T inner_pos = np.append(inner_pos, compensated, axis=0) #print(inner_pos) #inner_pos = inner_pos[sorted(np.random.choice(inner_pos.shape[0], N, replace=False)), :] pts = [ p for p in coords_to_points(inner_pos) if p.within(area_shape) ] # converts to shapely Point ax.clear() # comment out if you want to plot trajectory coords = points_to_coords( pts) # convert back to simple NumPy coordinate array poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, area_shape, accept_n_coord_duplicates=0) poly_centroids = np.array([p.centroid.coords[0] for p in poly_shapes]) #new_centroids = reshape_centroids(poly_centroids) # plotting EPS = EPS err = 99999 #old_coords = coords new_centroids = match_pair(poly_shapes, coords, poly_centroids) for i in range(len(coords)): xo = coords[i][0] yo = coords[i][1] #old_coords[i][0] = xo #old_coords[i][1] = yo xc = new_centroids[i][0] yc = new_centroids[i][1] #err = np.sqrt((xo-xc)**2 + (yo-yc)**2) data = [xc, yc] outputs.append(data) #(np.array((xc, yc)).astype(np.float64)) #if err > EPS: # # print("UPDARED!!") # coords[i][0] = xc#xo + 0.2*(xc-xo) # coords[i][1] = yc#yo + 0.2*(yc-yo) # draw centroid that each drone follow for i, centroid in enumerate(new_centroids): c1 = centroid ax.plot(c1[0], c1[1], '*', label=str(i)) for coord in coords: c = coord ax.plot(c[0], c[1], 'o', alpha=0.5) fig = plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords, poly_to_pt_assignments) plt.title(str(t) + "[s]") plt.pause(0.00001) return outputs
gdf_proj =gdf.to_crs(epsg=4326) # set the projection of the AoI shapefile boundary = boundary.set_crs(epsg=4326, inplace = True) boundary_shape = cascaded_union(boundary.geometry) coords = points_to_coords(gdf_proj.geometry) # Calculate Voronoi Regions poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords(coords, boundary_shape) # plot the voronoi regions in a map fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, boundary_shape, poly_shapes, pts, poly_to_pt_assignments) ax.set_title('Voronoi regions') plt.tight_layout() plt.savefig(shpdir + 'Voronoi_polygons_validation_attributes3.png') # save the polygon objects in a shapefile depth = gdf['Z'] time_of_failure = gdf['time_of_failure'] factor_of_safety = gdf['factor_of_safety'] poly = poly_shapes # Define a polygon feature geometry with one attribute schema = {
m2_to_km2=True) # converts m² to km² print('areas in km²:') print(poly_areas) print('sum:') print(sum(poly_areas)) # # plotting # fig, ax = subplot_for_map(show_x_axis=True, show_y_axis=True) voronoi_labels = ['%d km²' % round(a) for a in poly_areas] plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, coords, poly_to_pt_assignments, voronoi_labels=voronoi_labels, voronoi_label_fontsize=7, voronoi_label_color='gray') ax.set_title('%d random points and their Voronoi regions in %s' % (len(pts), COUNTRY)) plt.tight_layout() plt.savefig('random_points_and_area.png') plt.show()
pt_labels = list(map(str, count_per_pt.values())) distinct_pt_coords = coords[np.asarray(list(count_per_pt.keys()))] # highlight voronoi regions with point duplicates vor_colors = { i_poly: (1, 0, 0) if len(pt_indices) > 1 else (0, 0, 1) for i_poly, pt_indices in region_pts.items() } fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area( ax, area_shape, region_polys, distinct_pt_coords, plot_voronoi_opts={'alpha': 0.2}, plot_points_opts={'alpha': 0.4}, voronoi_color=vor_colors, voronoi_edgecolor=(0, 0, 0, 1), point_labels=pt_labels, points_markersize=np.square(np.array(list(count_per_pt.values()))) * 10) ax.set_title( '%d random points (incl. %d duplicates)\nand their Voronoi regions in %s' % (len(coords), N_DUPL, COUNTRY)) plt.tight_layout() plt.savefig('duplicate_points.png') plt.show()
points = np.array([[1, 1], [1.1, 0.9], [1.15, 0.8], [2.5, 0]]) #points = np.array([[1, 1], [1.1, 0.91], [1.2, 0.8]]) # surrounding shape shape = Polygon([[-1, -1], [3, -1], [3, 3], [-1, 3]]) #%% Voronoi region generation region_polys, region_pts = voronoi_regions_from_coords(points, shape) print('Voronoi region to point assignments:') print(region_pts) #%% plotting fig, ax = subplot_for_map(show_x_axis=True, show_y_axis=True) plot_voronoi_polys_with_points_in_area( ax, shape, region_polys, points, region_pts, point_labels=list(map(str, range(len(points)))), voronoi_labels=list(map(str, region_polys.keys()))) ax.set_title('toy example') plt.tight_layout() plt.show()
#%% # # calculate the Voronoi regions, cut them with the geographic area shape and assign the points to them # region_polys, region_pts = voronoi_regions_from_coords(pts, brandenburg) print('Voronoi region to point assignments:') pprint(region_pts) #%% plotting fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, brandenburg, region_polys, pts, region_pts, point_labels=list( map(str, range(len(pts))))) ax.set_title('%d random points and their Voronoi regions in Brandenburg' % len(pts)) plt.tight_layout() plt.savefig('random_points_brandenburg.png') plt.show()
print('Voronoi region to point assignments:') pprint(region_pts) print('Unassigned points:') for i_pt in unassigned_pts: print('#%d: %.2f, %.2f' % (i_pt, pts[i_pt].x, pts[i_pt].y)) #%% plotting fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, area_shape, region_polys, pts, region_pts, point_labels=list( map(str, range(len(pts))))) ax.set_title('%d random points and their Voronoi regions in %s' % (len(pts), COUNTRY)) plt.tight_layout() plt.savefig('random_points_across_italy.png') plt.show() #%% # Now we change `per_geom` to False. Since all geometries of the country are treated as one during Voronoi region # generation, also the single point on Sardinia gets a Voronoi region. Note however, that these regions now can
from geovoronoi import voronoi_regions_from_coords, points_to_coords df = pd.read_excel('primarias_muestra.xlsx', index_col=0) ########| Escuelas_primarias = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy( df.long, df.lat)) ### Geodataframe Escuelas_primarias.head() Escuelas_primarias.crs = "EPSG:4326" #Alcaldias = gpd.read_file("Alcaldias.shp") Miguel_Hidalgo = Alcaldias.drop( [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15], axis=0) Alcaldia = Miguel_Hidalgo fig, ax = plt.subplots(figsize=(12, 10)) Alcaldia.plot(ax=ax, color="Green") Escuelas_primarias.plot(ax=ax, markersize=3.5, color="black") ax.axis("off") plt.axis('equal') plt.show() Alcaldia = Alcaldia.to_crs(epsg=3395) gdf_proj = Escuelas_primarias.to_crs(Alcaldia.crs) Alcaldia_shape = cascaded_union(Alcaldia.geometry) coords = points_to_coords(gdf_proj.geometry) poly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords( coords, Alcaldia_shape) fig, ax = subplot_for_map(figsize=(14.5, 10)) plot_voronoi_polys_with_points_in_area(ax, Alcaldia_shape, poly_shapes, pts, poly_to_pt_assignments) ax.set_title('Diagrama de voronoi Escuelas primarias miguel hidalgo muestra') plt.tight_layout() plt.show()
print('areas in km²:') pprint(poly_areas) print('sum:') print(sum(poly_areas.values())) #%% plotting fig, ax = subplot_for_map(show_x_axis=True, show_y_axis=True) voronoi_labels = { poly_i: '%d km²' % round(a) for poly_i, a in poly_areas.items() } plot_voronoi_polys_with_points_in_area(ax, area_shape, region_polys, coords, region_pts, voronoi_labels=voronoi_labels, voronoi_label_fontsize=7, voronoi_label_color='gray') ax.set_title('%d random points and their Voronoi regions in %s\n' % (n_pts, COUNTRY)) plt.tight_layout() plt.savefig('random_points_and_area.png') plt.show()
#%% # # calculate the Voronoi regions, cut them with the geographic area shape and assign the points to them # # convert the pandas Series of Point objects to NumPy array of coordinates coords = points_to_coords(south_am_cities.geometry) # calculate the regions # we set "per_geom=False" so that the whole continent is treated as one area and Voronoi regions # span over to Tierra del Fuego region_polys, region_pts = voronoi_regions_from_coords(coords, south_am_shape, per_geom=False) #%% Plotting fig, ax = subplot_for_map() plot_voronoi_polys_with_points_in_area(ax, south_am_shape, region_polys, coords, region_pts, point_labels=south_am_cities.name.tolist()) ax.set_title('Cities data for South America from GeoPandas\nand Voronoi regions around them') plt.tight_layout() plt.savefig('using_geopandas.png') plt.show()