data, numPoints, matDim = test.kMeans() # data = np.random.random((100, 2)) # numPoints = 100 print(np.shape(data)) numBots = 3 print(numPoints) demand = (numPoints - (numPoints % numBots)) / numBots demand = [demand for i in range(numBots)] t = time.time() (C, M, f) = test.constrained_kmeans(data, demand) print('Elapsed:', (time.time() - t) * 1000, 'ms') print('C:', C) unique, counts = np.unique(M, return_counts=True) a = dict(zip(unique, counts)) print(a) vor = Voronoi(C) voronoi_plot_2d(vor) plt.scatter(C[:, 0], C[:, 1]) plt.scatter(data[:, 0], data[:, 1]) plt.xlim((0, matDim[0])) plt.ylim((0, matDim[1])) plt.show() # roi.getVoronoi(C) # roi.saveBMP()
vor.regions vor.max_bound vor.ndim vor.ridge_dict vor.ridge_points vor.ridge_vertices vor.npoints vor.point_region vor.points vor.vertices ''' points = np.array([[-1, 0.5], [3, 3], [0.0, 2.5], [3.0, 0.0], [0.0, -1.0], [1, 0], [1, 3], [2, 0], [2, 3]]) vor = Voronoi(points) # Draw infinity vertices center = points.mean(axis=0) for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices): simplex = np.asarray(simplex) if np.any(simplex < 0): i = simplex[simplex >= 0][0] # finite end Voronoi vertex t = points[pointidx[1]] - points[pointidx[0]] # tangent t = t / np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = points[pointidx].mean(axis=0) far_point = vor.vertices[i] + np.sign(np.dot(midpoint - center, n)) * n * 1.2 plt.plot([vor.vertices[i, 0], far_point[0]], [vor.vertices[i, 1], far_point[1]],
from scipy.spatial import Voronoi from time import time from random import randint point_nums = [10, 50, 100, 200, 500, 1000, 5000, 10000, 20000, 50000, 100000] for num in point_nums: begin = time() points = [(randint(0, 100), randint(0, 100)) for i in range(num)] v = Voronoi(points) print(round(time() - begin, 2))
def findClusters(h5_name, density_factor, min_size, verbose=True): """ h5_name - The localizations HDF5 file. density_factor - Multiple of the median density to be a cluster member. min_size - The minimum number of localizations a cluster can have. """ with clSAH5Py.SAH5Clusters(h5_name) as cl_h5: [x, y, z, c, cl_dict] = cl_h5.getDataForClustering() n_locs = x.size labels = numpy.zeros(n_locs, dtype=numpy.int32) - 1 density = numpy.zeros(n_locs) # Convert data to nanometers pix_to_nm = cl_h5.getPixelSize() x_nm = x * pix_to_nm y_nm = y * pix_to_nm points = numpy.column_stack((x_nm, y_nm)) if verbose: print("Creating Voronoi object.") vor = Voronoi(points) if verbose: print("Calculating 2D region sizes.") for i, region_index in enumerate(vor.point_region): if ((i % 10000) == 0) and verbose: print("Processing point", i) vertices = [] for vertex in vor.regions[region_index]: # I think these are edge regions? if (vertex == -1): vertices = [] break vertices.append(vor.vertices[vertex]) if (len(vertices) > 0): area = Polygon(vertices).area density[i] = 1.0 / area # Used median density based threshold. ave_density = numpy.median(density) if verbose: print("Min density", numpy.amin(density)) print("Max density", numpy.amax(density)) print("Median density", ave_density) # Record the neighbors of each point. These are polygons so there shouldn't # be that many neighbors (sides). 40 is more than safe? # max_neighbors = 40 neighbors = numpy.zeros((n_locs, max_neighbors), dtype=numpy.int32) - 1 neighbors_counts = numpy.zeros((n_locs), dtype=numpy.int32) if verbose: print("Calculating neighbors") for ridge_p in vor.ridge_points: p1 = ridge_p[0] p2 = ridge_p[1] # Add p2 to the list for p1 neighbors[p1, neighbors_counts[p1]] = p2 neighbors_counts[p1] += 1 # Add p1 to the list for p2 neighbors[p2, neighbors_counts[p2]] = p1 neighbors_counts[p2] += 1 if False: n1 = neighbors[0, :] print(n1) print(neighbors[n1[0], :]) # Mark connected points that meet the minimum density criteria. if verbose: print("Marking connected regions") min_density = density_factor * ave_density visited = numpy.zeros(n_locs, dtype=numpy.int32) def neighborsList(index): nlist = [] for i in range(neighbors_counts[index]): loc_index = neighbors[index, i] if (visited[loc_index] == 0): nlist.append(neighbors[index, i]) visited[loc_index] = 1 return nlist cluster_id = 0 for i in range(n_locs): if (visited[i] == 0): visited[i] = 1 if (density[i] > min_density): cluster_elt = [i] c_size = 1 to_check = neighborsList(i) while (len(to_check) > 0): # Remove last localization from the list. loc_index = to_check[-1] to_check = to_check[:-1] # If the localization has sufficient density add to cluster and # check neighbors. if (density[loc_index] > min_density): to_check += neighborsList(loc_index) cluster_elt.append(loc_index) c_size += 1 # Mark as visited. visited[loc_index] = 1 # Mark the cluster if there are enough localizations in the cluster. if (c_size > min_size): if verbose: print("cluster", cluster_id, "size", c_size) for elt in cluster_elt: labels[elt] = cluster_id cluster_id += 1 if verbose: print(cluster_id, "clusters") # Save the clustering results. cl_dict["x"] = x cl_dict["y"] = y cl_dict["z"] = z cl_dict["density"] = density cl_dict["category"] = c cl_h5.addClusters(labels, cl_dict) # Save clustering info. info = "voronoi,df,{0:0.3f},ms,{1:d}".format(density_factor, min_size) cl_h5.setClusteringInfo(info)
r = np.array([ geometry.circumcircle_radius(*tri.points[tri.simplices[m]]) for m in members[0] ]) print('circumcenters:\n', cc) print('radii\n', r) ########################################### # Draw the natural neighbor triangles and their circumcenters. Also plot a `Voronoi diagram # <https://docs.scipy.org/doc/scipy/reference/tutorial/spatial.html#voronoi-diagrams>`_ # which serves as a complementary (but not necessary) # spatial data structure that we use here simply to show areal ratios. # Notice that the two natural neighbor triangle circumcenters are also vertices # in the Voronoi plot (green dots), and the observations are in the polygons (blue dots). vor = Voronoi(list(zip(xp, yp))) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) ax.ishold = lambda: True # Work-around for Matplotlib 3.0.0 incompatibility voronoi_plot_2d(vor, ax=ax) nn_ind = np.array([0, 5, 7, 8]) z_0 = zp[nn_ind] x_0 = xp[nn_ind] y_0 = yp[nn_ind] for x, y, z in zip(x_0, y_0, z_0): ax.annotate(f'{x}, {y}: {z:.3f} F', xy=(x, y)) ax.plot(sim_gridx[0], sim_gridy[0], 'k+', markersize=10) ax.annotate(f'{sim_gridx[0]}, {sim_gridy[0]}',
def create_grid_and_edges(data, drone_altitude, safety_distance): """ Returns a grid representation of a 2D configuration space along with Voronoi graph edges given obstacle data and the drone's altitude. """ # minimum and maximum north coordinates north_min = np.floor(np.min(data[:, 0] - data[:, 3])) north_max = np.ceil(np.max(data[:, 0] + data[:, 3])) # minimum and maximum east coordinates east_min = np.floor(np.min(data[:, 1] - data[:, 4])) east_max = np.ceil(np.max(data[:, 1] + data[:, 4])) # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil(north_max - north_min)) east_size = int(np.ceil(east_max - east_min)) # Initialize an empty grid grid = np.zeros((north_size, east_size)) # Initialize an empty list for Voronoi points points = [] # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: bottom = north - d_north - safety_distance - north_min top = north + d_north + safety_distance - north_min left = east - d_east - safety_distance - east_min right = east + d_east + safety_distance - east_min obstacle = [ int(np.clip(np.floor(bottom), 0, north_size - 1)), int(np.clip(np.ceil(top), 0, north_size - 1)), int(np.clip(np.floor(left), 0, east_size - 1)), int(np.clip(np.ceil(right), 0, east_size - 1)), ] grid[obstacle[0]:obstacle[1] + 1, obstacle[2]:obstacle[3] + 1] = 1 # add center of obstacles to points list points.append([north - north_min, east - east_min]) # TODO: create a voronoi graph based on # location of obstacle centres graph = Voronoi(points) # TODO: check each edge from graph.ridge_vertices for collision edges = [] for v in graph.ridge_vertices: p1 = graph.vertices[v[0]] p2 = graph.vertices[v[1]] cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]))) hit = False for c in cells: # First check if we're off the map if ((np.amin(c) < 0) or (c[0] >= grid.shape[0]) or (c[1] >= grid.shape[1])): hit = True break # Next check if we're in collision if grid[c[0], c[1]] == 1: hit = True break # If the edge does not hit on obstacle # add it to the list if not hit: # array to tuple for future graph creation step) p1 = (p1[0], p1[1]) p2 = (p2[0], p2[1]) edges.append((p1, p2)) return grid, edges, int(north_min), int(east_min)
import numpy as np from fealpy.mesh.mesh_tools import find_node import matplotlib.pyplot as plt from scipy.spatial import Voronoi, voronoi_plot_2d p = np.random.rand(10, 2) vor = Voronoi(p) voronoi_plot_2d(vor) fig = plt.gcf() axes = fig.gca() find_node(axes, vor.vertices, showindex=True) find_node(axes, vor.points, showindex=True) print(vor.vertices) print("Region:", vor.regions) print("Ridge_points:", vor.ridge_points) plt.show()
from shapely.geometry import LineString, MultiPoint, mapping, shape from scipy.spatial import Voronoi, ConvexHull import fiona from fiona.crs import from_epsg import shapely.ops dcsv = pd.read_csv('cleaned_Donors_record.csv', encoding = 'utf-8') # get the numpy array of latitude and longitude att_lon_lat = dcsv.loc[:, ['longitude','latitude']].values # Adding bounding box to extend the size of voronoi result extra_point = np.array([[5000, 5000], [5000, -5000], [-5000, -5000], [-5000, 5000]]) points_extend = np.concatenate((att_lon_lat, extra_point)) vor = Voronoi(points_extend) #convert voronoi to line objects lines = [ LineString(vor.vertices[line]) for line in vor.ridge_vertices # if -1 not in line ] # get a list of polygons of voronoi tesellation areas = list(shapely.ops.polygonize(lines)) # convert point records into multipoint # load coordinates into multipoints object mtpoints = MultiPoint(att_lon_lat)
def voronoi(points, shape=(500, 500), size=500, recur=1): print(recur) vor = Voronoi(points) regions = [] holdregions = [] for i in vor.regions: if -1 in i[:] or i == []: regions.append([]) else: hold = [] check = True for y in i: x1 = vor.vertices[y, 0] y1 = vor.vertices[y, 1] if x1 >= 0 and x1 < size and y1 >= 0 and y1 < size: hold.append((x1, y1)) else: hold.append((x1, y1)) check = False if recur != 0: check = True if check: regions.append(hold) else: holdregions.append(hold) regions.append([]) newPoints = [] newRegions = [] holdpoints = [] matrix = np.zeros((size, size), dtype=np.int32) matrix.fill(-1) x = 0 for i in points: holdpoints.append(i) if i[0] >= 0 and i[0] < size and i[1] >= 0 and i[1] < size: if matrix[int(i[0]), int(i[1])] == -1: matrix[int(i[0]), int(i[1])] = x x += 1 for i in regions: if i != []: x_min = size x_max = 0 y_min = size y_max = 0 polygon = Polygon(i) for x in i: if x[0] > x_max: x_max = x[0] if x[0] < x_min: x_min = x[0] if x[1] > y_max: y_max = x[1] if x[1] < y_min: y_min = x[1] if x_min >= 0 and x_max < size and y_min >= 0 and y_max < size: testregion = matrix[int(x_min):int(x_max), int(y_min):int(y_max)] testregion = testregion.flatten() z = 0 search = True while search: y = testregion[z] if y != -1: if polygon.contains(Point(points[y])): search = False newPoints.append(points[y]) newRegions.append(i) holdpoints.remove(points[y]) #print(len(newPoints)) z += 1 if z == len(testregion): search = False if recur > 0: for i in holdpoints: newPoints.append(i) dif = len(newPoints) - len(newRegions) for i in range(0, dif): newRegions.append([]) z = 0 for i in newRegions: if i != []: polygon = Polygon(i) x1, y1 = polygon.centroid.coords[0] newPoints[z] = [x1, y1] z += 1 return voronoi(newPoints, shape, size, recur - 1) else: tri = Delaunay(newPoints) voroLines = [] verts = [] for i in vor.ridge_vertices: if i[0] != -1 and i[1] != -1: x1 = vor.vertices[i[0], 0] y1 = vor.vertices[i[0], 1] x2 = vor.vertices[i[1], 0] y2 = vor.vertices[i[1], 1] hold = [x1, y1, x2, y2] check = True for x in hold: if x < 0 or x >= size: check = False if check: voroLines.append([x1, y1, x2, y2]) for i in vor.vertices: check = True for x in i: if x < 0 or x >= size: check = False if check: verts.append(i) return voroLines, verts, newPoints, newRegions, tri
def __init__(self, n, bounded=True, coord=None): # Define os principais parâmetros self.n = n self.bounded = bounded # Gera as coordenadas a partir de uma distribuição uniforme if coord is None: self.coord = np.random.rand(self.n, 2) # ou recebe coordenadas preestabelecidas else: self.coord = coord # Realiza a tesselação de Voronoi. A variável connection guarda os pares # de índices dos pontos que geram céluas contíguas. # Caso limitado: tesselação é realizada com quatro cópias dos pontos # refletidas acima, abaixo e aos lados, de maneira que as células # acabem nas bordas de [0,1]x[0,1] if self.bounded: aux = np.concatenate( (self.coord, self.coord, self.coord, self.coord)) aux[0:self.n, 1] = 2 - 1 * self.coord[:, 1] # up aux[self.n:2 * self.n, 1] = -1 * self.coord[:, 1] # down aux[2 * self.n:3 * self.n, 0] = -1 * self.coord[:, 0] # left aux[3 * self.n:4 * self.n, 0] = 2 - 1 * self.coord[:, 0] # right self.vor = Voronoi(np.concatenate((self.coord, aux))) self.connection = self.vor.ridge_points[np.where( np.logical_not( np.logical_or(self.vor.ridge_points[:, 1] > self.n, self.vor.ridge_points[:, 0] > self.n)))] else: self.vor = Voronoi(self.coord) self.connection = self.vor.ridge_points # Cria grafo e conexões de acordo com a contiguidade das células self.G = nx.Graph() self.G.add_nodes_from(range(0, self.n)) for i in range(np.size(self.connection, 0)): self.G.add_edge(self.connection[i, 0], self.connection[i, 1]) # Obtem a média e o desvio padrão do grau self.degree = np.array( sorted([d for n, d in self.G.degree()], reverse=True)) self.degree_mu = self.degree.mean() self.degree_sigma = self.degree.std() # Obtem a média e o desvio padrão do coeficiente de aglomeração self.clustering_coefficient = np.array( sorted([nx.clustering(self.G, n) for n in nx.clustering(self.G)], reverse=True)) self.clustering_coefficient_mu = self.clustering_coefficient.mean() self.clustering_coefficient_sigma = self.clustering_coefficient.std() # Obtem a média e o desvio padrão do caminho mínimo para todos os pares de pontos # através do método de Floyd-Warshall fw_aux = np.asarray(nx.floyd_warshall_numpy(self.G)).reshape(-1) self.floyd_warshall = np.array(np.delete( fw_aux, np.where(np.logical_or(fw_aux == 0, fw_aux == float('inf')))), dtype=int) self.shortest_path_length_mu = self.floyd_warshall.mean() self.shortest_path_length_sigma = self.floyd_warshall.std() #Identificador único do grafo gerado self.dt_string = datetime.now().strftime("_%d-%m-%Y_%H-%M-%S") self.filename = 'img/Voronoi_n=' + str(self.n) + self.dt_string
def setup_voronoi_list(self, indices, voronoi_cutoff): """ Set up of the voronoi list of neighbours by calling qhull :param indices: indices of the sites for which the Voronoi is needed :param voronoi_cutoff: Voronoi cutoff for the search of neighbours :raise RuntimeError: If an infinite vertex is found in the voronoi construction """ self.voronoi_list2 = [None] * len(self.structure) self.voronoi_list_coords = [None] * len(self.structure) logging.info('Getting all neighbors in structure') struct_neighbors = self.structure.get_all_neighbors(voronoi_cutoff, include_index=True) t1 = time.clock() logging.info('Setting up Voronoi list :') for jj, isite in enumerate(indices): logging.info( ' - Voronoi analysis for site #{:d} ({:d}/{:d})'.format( isite, jj + 1, len(indices))) site = self.structure[isite] neighbors1 = [(site, 0.0, isite)] neighbors1.extend(struct_neighbors[isite]) distances = [i[1] for i in sorted(neighbors1, key=lambda s: s[1])] neighbors = [i[0] for i in sorted(neighbors1, key=lambda s: s[1])] qvoronoi_input = [s.coords for s in neighbors] voro = Voronoi(points=qvoronoi_input, qhull_options="o Fv") all_vertices = voro.vertices results2 = [] maxangle = 0.0 mindist = 10000.0 for iridge, ridge_points in enumerate(voro.ridge_points): if 0 in ridge_points: ridge_vertices_indices = voro.ridge_vertices[iridge] if -1 in ridge_vertices_indices: raise RuntimeError("This structure is pathological," " infinite vertex in the voronoi " "construction") ridge_point2 = max(ridge_points) facets = [all_vertices[i] for i in ridge_vertices_indices] sa = my_solid_angle(site.coords, facets) maxangle = max([sa, maxangle]) mindist = min([mindist, distances[ridge_point2]]) for iii, sss in enumerate(self.structure): if neighbors[ridge_point2].is_periodic_image(sss): myindex = iii break results2.append({ 'site': neighbors[ridge_point2], 'angle': sa, 'distance': distances[ridge_point2], 'index': myindex }) for dd in results2: dd['normalized_angle'] = dd['angle'] / maxangle dd['normalized_distance'] = dd['distance'] / mindist self.voronoi_list2[isite] = results2 self.voronoi_list_coords[isite] = np.array( [dd['site'].coords for dd in results2]) t2 = time.clock() logging.info('Voronoi list set up in {:.2f} seconds'.format(t2 - t1))
def voronoi_patchs(ax, xy, c=None, vmax=None, vmin=None, cmap=mpl.cm.viridis, cbar=True, cblabel="", cbarprop={}, **kwargs): """ ax: [matplotlib.axes] where the data will be displaid xy: [N-2D array] the combination upon which the voronoi tesselation will be built. (scipy.spatial.Voronoi) - options - c: [array] an array of value for the color of the patchs. You can also provide 1 float between 0 and 1 (see cmap) vmin,vmax: [float,float] minimal and maximal values for the colormapping. If None the c-array's minimal/maximal value will be set. - other options - cmap: [mpl.cm] a colormap cbar: [bool or ax] provide here an ax where the colorbar should be drawn. You can also set True to have a default one or set False to avoid having a colorbar. - kwargs goes to matplotlib.collections.PolyCollection - Return ------ collection (output of matplotlib.collections.PolyCollection) """ from scipy.spatial import Voronoi from matplotlib.collections import PolyCollection # -------------------- # - Define the Cells npoint = np.shape(xy)[0] vor = Voronoi(xy) xy_poly = [ [ vor.vertices[x] for x in vor.regions[vor.point_region[i]] if x >= 0 # this others could be saved ] for i in range(npoint) ] # -------------------- # - Color of the Cells if c is not None: if "__iter__" not in dir(c): c = [c] * npoint else: c = np.asarray(c) # - because shift happens c[np.isinf(c)] = np.nanmax(c[~np.isinf(c)]) if vmin is None: vmin = np.nanmin(c) else: vmin = vmin if type(vmin) is not str else np.percentile( c[c == c], float(vmin)) if vmax is None: vmax = np.nanmax(c) else: vmax = vmax if type(vmax) is not str else np.percentile( c[c == c], float(vmax)) vmax = c.max() if vmax is None else vmax # --- nancleaning color = cmap((c - vmin) / (vmax - vmin)) # - because shift happens if len(color[c != c]) > 0: warnings.warn( "There is nan values you aim to convert in patch color. I set them transparent" ) color[c != c] = mpl.cm.binary(0., 0) edgecolors = kwargs.pop("edgecolors", "k") else: color = "None" edgecolors = kwargs.pop("edgecolors", "k") prop = kwargs_update({"alpha": 0.5}, **kwargs) collec = PolyCollection(xy_poly, facecolors=color, edgecolors=edgecolors, **prop) ax.add_collection(collec) # ----------------- # # - color bar - # # ----------------- # if not (color is "None" or not cbar): # - this means it is not an ax axcar = ax.insert_ax("right", shrunk=0.9,space=.0,axspace=0.03) \ if "imshow" not in dir(cbar) else cbar calpha = cbarprop.pop('alpha', kwargs.pop("alpha", None)) return collec, axcar.colorbar(cmap, vmin=vmin, vmax=vmax, label=cblabel, alpha=calpha, **cbarprop) # - no cbar return collec
# In[7]: # voronoi polys from just the cv shore points yielded some missing polygons around the exterior, # related to where the 'infinite points' were/weren't placed. # workaround is to make a big ole hull around points, buffer it generously, # then add the vertices of the hull to the point set, then create voronoi convex_hull = MultiPoint([Point(i) for i in pts]).convex_hull.buffer(10000) x, y = convex_hull.exterior.coords.xy pts = np.concatenate((pts, np.array(zip(x, y)))) # In[8]: # borrowed from top answer # https://stackoverflow.com/questions/27548363/from-voronoi-tessellation-to-shapely-polygons vor = Voronoi(pts) lines = [ shapely.geometry.LineString(vor.vertices[line]) for line in vor.ridge_vertices if -1 not in line ] # In[9]: polys = list(shapely.ops.polygonize(lines)) # In[10]: len(polys) == len(points) # In[11]:
pts.plot(ax=ax) sns.despine(left=True, bottom=True) #plt.savefig('tesdiag_3.svg') # In[18]: hull = limit.buffer(100) hull = _densify(hull, 10) hull_array = np.array(hull.boundary.coords).tolist() for i, a in enumerate(hull_array): points.append(hull_array[i]) ids.append(-1) # In[19]: voronoi_diagram = Voronoi(np.array(points)) # In[20]: def _regions(voronoi_diagram, unique_id, ids, crs): """ Generate GeoDataFrame of Voronoi regions from scipy.spatial.Voronoi. """ # generate DataFrame of results regions = pd.DataFrame() regions[unique_id] = ids # add unique id regions[ "region"] = voronoi_diagram.point_region # add region id for each point # add vertices of each polygon
def test_issue_8051(self): points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]) Voronoi(points)
def create_grid_and_edges(data, drone_altitude, safety_distance): """ Returns a grid representation of a 2D configuration space along with Voronoi graph edges given obstacle data and the drone's altitude. """ # minimum and maximum north coordinates north_min = np.floor(np.min(data[:, 0] - data[:, 3])) north_max = np.ceil(np.max(data[:, 0] + data[:, 3])) # minimum and maximum east coordinates east_min = np.floor(np.min(data[:, 1] - data[:, 4])) east_max = np.ceil(np.max(data[:, 1] + data[:, 4])) # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil((north_max - north_min))) east_size = int(np.ceil((east_max - east_min))) # Initialize an empty grid grid = np.zeros((north_size, east_size)) # Initialize an empty list for Voronoi points points = [] # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: obstacle = [ int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)), int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)), int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)), int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)), ] grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1 # add center of obstacles to points list points.append([north - north_min, east - east_min]) # Create a voronoi graph based on location of obstacle centres graph = Voronoi(points) # Check each edge from graph.ridge_vertices for collision edges = [] print("start building edges") print(len(graph.ridge_vertices)) for v in graph.ridge_vertices: p1 = tuple(graph.vertices[v[0]]) p2 = tuple(graph.vertices[v[1]]) # If any of the vertices is out of grid then skip if np.amin(p1) < 0 or np.amin(p2) < 0 or p1[0] >= grid.shape[0] or p1[1] >= grid.shape[1] or p2[0] >= grid.shape[0] or p2[1] >= grid.shape[1]: continue safe = True cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]))) # Test each pair p1 and p2 for collision using Bresenham # If the edge does not hit an obstacle # add it to the list for c in cells: # First check if we're off the map if np.amin(c) < 0 or c[0] >= grid.shape[0] or c[1] >= grid.shape[1]: return not safe # Next check if we're in collision if grid[c[0], c[1]] == 1: safe = False break if safe: edges.append((p1, p2)) print("done building edges") return grid, edges, int(north_min), int(east_min)
def draw_kmeans_clusters(self, filename, figsize=(4, 3)): import matplotlib as mpl mpl.use('Agg') import matplotlib.patches as mpatches import matplotlib.pyplot as plt from sklearn.cluster import KMeans from scipy.spatial import Voronoi, voronoi_plot_2d from mpl_toolkits.basemap import Basemap, cm, maskoceans #from matplotlib import style #import seaborn as sns #sns.set_style("white") #plt.rc('text', usetex=True) #plt.rc('font', family='serif') #plt.rcParams['axes.facecolor']='white' fig = plt.figure(figsize=figsize) lllat = 24.396308 lllon = -124.848974 urlat = 49.384358 urlon = -66.885444 m = Basemap(llcrnrlat=lllat, urcrnrlat=urlat, llcrnrlon=lllon, urcrnrlon=urlon, resolution='c', projection='cyl') m.drawmapboundary(fill_color='white') m.drawcoastlines(linewidth=0.2) m.drawcountries(linewidth=0.2) ax = plt.gca() ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) for spine in ax.spines.itervalues(): spine.set_visible(False) #fig = plt.figure() # figsize=(4,4.2) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) train_locs = self.df_train[['lat', 'lon']].values n_clusters = int(np.ceil(train_locs.shape[0] / self.bucket_size)) n_clusters = 128 logging.info('n_cluster %d' % n_clusters) clusterer = KMeans(n_clusters=n_clusters, n_jobs=10) clusterer.fit(train_locs) centroids = clusterer.cluster_centers_ centroids[:, [0, 1]] = centroids[:, [1, 0]] mlon, mlat = m(*(centroids[:, 0], centroids[:, 1])) centroids = np.transpose(np.vstack((mlon, mlat))) vor = Voronoi(centroids) #ax.set_xlim([-125, -60]) # pylab.xlim([-400, 400]) #ax.set_ylim([25, 50]) plt.setp(ax.get_yticklabels(), visible=False) plt.setp(ax.get_xticklabels(), visible=False) ax.yaxis.set_tick_params(size=0) ax.xaxis.set_tick_params(size=0) #plt.tick_params(axis='both', which='major', labelsize=25) #ax.labelsize = '25' #plt.subplots_adjust(bottom=0.2) voronoi_plot_2d(vor, show_points=False, show_vertices=False, ax=ax, line_width=0.7) m.drawlsmask(land_color='lightgray', ocean_color="#b0c4de", lakes=True) plt.tight_layout() plt.savefig(filename) #plt.close() print("the plot saved in " + filename)
def _voronoi_regions(x, y, f, xlim, ylim): """ Takes a set of ``(x, y, f)`` points and returns the edgepoints of the voronoi region around each point within the boundaries specified by ``xlim`` and ``ylim``. The actual voronoi diagram is constructed by ``scipy.spatial.Voronoi``. This method builds on the regions generated by scipy and truncates them to a rectangular area. Voronoi regions entirely outside of the bounds are removed, and a version of ``x``, ``y``, and ``f`` with these points filtered out is also created and returned. Parameters ---------- x A list of x-coorindates. y A list of y-coordinates. f The score function at the given x and y coordinates. xlim Lower and upper bound for the x coordinates. ylim Lower and upper bound for the y coordinates. Returns ------- A tuple ``(x, y, f, regions)`` where ``x``, ``y`` and ``f`` are the coordinates of the accepted points and each ``regions[i]`` is a list of the vertices making up the voronoi region for point ``(x[i], y[i])`` with score ``f[i]``. """ from scipy.spatial import Voronoi try: from itertools import izip # Python 2's izip acts like Python 3's zip except ImportError: izip = zip # Don't check x, y, f: handled by calling method n = len(x) # Check limits xmin, xmax = [float(a) for a in sorted(xlim)] ymin, ymax = [float(a) for a in sorted(ylim)] # Drop any points outside the bounds # within_bounds = (x >= xmin) & (x <= xmax) & (y >= ymin) & (y <= ymax) # x = x[within_bounds] # y = y[within_bounds] # f = f[within_bounds] # Create voronoi diagram vor = Voronoi(np.array([x, y]).transpose()) # The voronoi diagram consists of a number of ridges drawn between a set # of points. # # points Are the points the diagram is based on. # vertices The coordinates of the vertices connecting the ridges # ridge_points Is a list of tuples (p1, p2) defining the points each # ridge belongs to. Points are given as their index in # the list of points. # ridge_vertices Is a list of vertices (v1, v2) defining the vertices # between which each ridge is drawn. Vertices are given # as their index in the list of vertice coordinates. For # ridges extending to infinity, one of the vertices will # be given as -1. # # Get the center of the voronoi diagram's points and define a radius that # will bring us outside the visible area for any starting point / direction # center = vor.points.mean(axis=0) radius2 = 2 * np.sqrt((xmax - xmin)**2 + (ymax - ymin)**2) # Create a list containing the set of vertices defining each region regions = [set() for i in range(n)] for (p1, p2), (v1, v2) in izip(vor.ridge_points, vor.ridge_vertices): # Order the edges: if one of the edges extends to infinity, the value # v1/v2 will be -1. By ordering here we ensure that only v1 can ever be # negative, so we don't need to check for v2 < 0 in the code below. v1, v2 = (v2, v1) if v1 > v2 else (v1, v2) # Get vertice coordinates x2 = vor.vertices[v2] # Only v1 can be -1 if v1 >= 0: # Finite vertex: use as is x1 = vor.vertices[v1] else: # Replacement vertex needed # Tangent line to points involved y1, y2 = vor.points[p1], vor.points[p2] t = y2 - y1 t /= np.linalg.norm(t) # Normal line q = np.array([-t[1], t[0]]) # Midpoint between involved points midpoint = np.mean([y1, y2], axis=0) # Point beyond the outer boundary x1 = x2 + np.sign(np.dot(midpoint - center, q)) * q * radius2 # Add vertice coordinates to both region coordinate lists x1, x2 = tuple(x1), tuple(x2) # arrays and lists aren't hashable regions[p1].update((x1, x2)) regions[p2].update((x1, x2)) # Order vertices in regions counter clockwise, truncate the regions at the # border, and remove regions outside of the bounds. selection = [] for k, region in enumerate(regions): # Regions can be empty if points appear more than once if len(region) == 0: continue # Convert set of tuples to 2d array region = np.asarray([np.asarray(v) for v in region]) # Filter out any regions lying entirely outside the bounds xmn = region[:, 0] < xmin xmx = region[:, 0] > xmax ymn = region[:, 1] < ymin ymx = region[:, 1] > ymax if np.all(xmn | xmx) and np.all(ymn | ymx): continue # Sort vertices counter clockwise p = vor.points[k] angles = np.arctan2(region[:, 1] - p[1], region[:, 0] - p[0]) regions[k] = region[np.argsort(angles)] # Region fully contained? Then keep in selection and continue if not (np.any(xmn) or np.any(xmx) or np.any(ymn) or np.any(ymx)): selection.append(k) continue # Region needs truncating # Drop points outside of boundary and replace by 0, 1 or 2 new points # on the actual boundaries. # Run twice: once for x violations, once for y violations (two # successive corrections may be needed, to solve corner issues). new_region = [] for j, p in enumerate(region): if p[0] < xmin: q = region[j - 1] if j > 0 else region[-1] r = region[j + 1] if j < len(region) - 1 else region[0] if q[0] < xmin and r[0] < xmin: # Point connecting two outsiders: drop continue if q[0] >= xmin: # Add point on line p-q s = p[1] + (xmin - p[0]) * (q[1] - p[1]) / (q[0] - p[0]) new_region.append(np.array([xmin, s])) if r[0] >= xmin: # Add point on line p-r s = p[1] + (xmin - p[0]) * (r[1] - p[1]) / (r[0] - p[0]) new_region.append(np.array([xmin, s])) elif p[0] > xmax: q = region[j - 1] if j > 0 else region[-1] r = region[j + 1] if j < len(region) - 1 else region[0] if q[0] > xmax and r[0] > xmax: # Point connecting two outsiders: drop continue if q[0] <= xmax: # Add point on line p-q s = p[1] + (xmax - p[0]) * (q[1] - p[1]) / (q[0] - p[0]) new_region.append(np.array([xmax, s])) if r[0] <= xmax: # Add point on line p-r s = p[1] + (xmax - p[0]) * (r[1] - p[1]) / (r[0] - p[0]) new_region.append(np.array([xmax, s])) else: # Point is fine, just add new_region.append(p) region = new_region # Run again for y-violations new_region = [] for j, p in enumerate(region): if p[1] < ymin: q = region[j - 1] if j > 0 else region[-1] r = region[j + 1] if j < len(region) - 1 else region[0] if q[1] < ymin and r[1] < ymin: # Point connecting two outsiders: drop continue if q[1] >= ymin: # Add point on line p-q s = p[0] + (ymin - p[1]) * (q[0] - p[0]) / (q[1] - p[1]) new_region.append(np.array([s, ymin])) if r[1] >= ymin: # Add point on line p-r s = p[0] + (ymin - p[1]) * (r[0] - p[0]) / (r[1] - p[1]) new_region.append(np.array([s, ymin])) elif p[1] > ymax: q = region[j - 1] if j > 0 else region[-1] r = region[j + 1] if j < len(region) - 1 else region[0] if q[1] > ymax and r[1] > ymax: # Point connecting two outsiders: drop continue if q[1] <= ymax: # Add point on line p-q s = p[0] + (ymax - p[1]) * (q[0] - p[0]) / (q[1] - p[1]) new_region.append(np.array([s, ymax])) if r[1] <= ymax: # Add point on line p-r s = p[0] + (ymax - p[1]) * (r[0] - p[0]) / (r[1] - p[1]) new_region.append(np.array([s, ymax])) else: # Point is fine, just add new_region.append(p) region = new_region # Store regions that are still OK if len(region) > 2: selection.append(k) # Filter out bad regions regions = np.array(regions, dtype=object) regions = regions[selection] x = x[selection] y = y[selection] f = f[selection] # Return output # Note: Regions is transformed back to a list, which fixes an issue with # matplotlib 3.3.0 (which does not expect "ragged" ndarrays made of # objects). return x, y, f, regions.tolist()
def _initialize(self, x, y, reorient_links=True): """ Creates an unstructured grid around the given (x,y) points. """ x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float) if x.size != y.size: raise ValueError("x and y arrays must have the same size") # Make a copy of the points in a 2D array (useful for calls to geometry # routines, but takes extra memory space). xy_of_node = np.hstack((x.reshape((-1, 1)), y.reshape((-1, 1)))) self._xy_of_node = sort_points_by_x_then_y(xy_of_node) # NODES AND CELLS: Set up information pertaining to nodes and cells: # - number of nodes # - node x, y coordinates # - default boundary status # - interior and boundary nodes # - nodes associated with each cell and active cell # - cells and active cells associated with each node # (or BAD_VALUE_INDEX if none) # # Assumptions we make here: # - all interior (non-perimeter) nodes have cells (this should be # guaranteed in a Delaunay triangulation, but there may be # special cases) # - all cells are active (later we'll build a mechanism for the user # specify a subset of cells as active) self._find_perimeter_nodes_and_BC_set(self._xy_of_node) [self._cell_at_node, self._node_at_cell ] = self._node_to_cell_connectivity(self.status_at_node, self.number_of_cells) # ACTIVE CELLS: Construct Voronoi diagram and calculate surface area of # each active cell. vor = Voronoi(self._xy_of_node) self.vor = vor self._area_of_cell = np.zeros(self.number_of_cells) for node in self._node_at_cell: xv = vor.vertices[vor.regions[vor.point_region[node]], 0] yv = vor.vertices[vor.regions[vor.point_region[node]], 1] self._area_of_cell[self.cell_at_node[node]] = simple_poly_area( xv, yv) # LINKS: Construct Delaunay triangulation and construct lists of link # "from" and "to" nodes. ( node_at_link_tail, node_at_link_head, _, self._face_width, ) = self._create_links_and_faces_from_voronoi_diagram(vor) self._nodes_at_link = np.hstack((node_at_link_tail.reshape( (-1, 1)), node_at_link_head.reshape((-1, 1)))) # Sort them by midpoint coordinates self._sort_links_by_midpoint() # Optionally re-orient links so that they all point within upper-right # semicircle if reorient_links: self._reorient_links_upper_right() # NODES & LINKS: IDs and directions of links at each node self._create_links_and_link_dirs_at_node() # LINKS: set up link unit vectors and node unit-vector sums self._create_link_unit_vectors()
def InversionDispersion(vr, freq, params, dns, iters, ns0, nr0, ns, nr, maxerr): vrAll = [] OutPoint, OutPolygon, OutError, OutModel, OutVertices = [], [], [], [], [] TotalModel, TotalVr, TotalError = [], [], [] OutPoint_ = [None] * nr0 OutPolygon_ = [None] * nr0 OutError_ = [None] * nr0 OutVertices_ = [None] * nr0 for i in range(iters): if i == 0: points = gibbs(params, ns0) points = points[0:ns0] vor = Voronoi(points, qhull_options='QJ') vrAll_, OutModel_, OutError__ = [], [], [] for j in range(len(vor.regions)): vsIt, vpIt, thkIt = PointToParam(points[j], lapisan=(len(params) + 1) / 3) vrNew = mat_disperse(thkIt, dns, vpIt, vsIt, freq) error = ErrorPercentage(vrNew, vr) vrAll_.append(vrNew) OutModel_.append([vsIt, vpIt, thkIt]) OutError__.append(error) TotalModel.append([vsIt, vpIt, thkIt]) TotalVr.append(vrNew) TotalError.append(error) print 'it = {:} | Model {:} | Error = {:.2f} % | ErrMin = {:.2f} %'.format( i + 1, len(TotalModel), error, np.array(OutError__).min()) idxMin1 = findMin(np.array(OutError__), nr0, doubleasone=False) regions, vertices = voronoi_finite_polygons_2d(vor, point=idxMin1) OutVertices.append(vertices) for ii, ni in enumerate(idxMin1): OutPolygon.append(regions[ii]) OutPoint.append(vor.points[ni]) OutError.append(OutError__[ni]) OutModel.append(OutModel_[ni]) vrAll.append(vrAll_[ni]) OutPoint_[ii] = ([vor.points[ni]]) OutError_[ii] = ([OutError__[ni]]) OutVertices_[ii] = ([vertices]) OutPolygon_[ii] = ([regions[ii]]) elif i == 1: for ij in range(len(idxMin1)): bestRegions = OutPolygon[ij] bestPoints = OutPoint[ij] bestVertices = np.array(OutVertices[i - 1])[bestRegions] points = gibbs(params, ns, border=bestVertices, center=bestPoints) points = points[1::1] points = points[0:ns] vor = Voronoi(points, qhull_options='QJ') vrAll_, OutModel_, OutError__ = [], [], [] for j in range(len(vor.regions)): vsIt, vpIt, thkIt = PointToParam( points[j], lapisan=(len(params) + 1) / 3) vrNew = mat_disperse(thkIt, dns, vpIt, vsIt, freq) error = ErrorPercentage(vrNew, vr) vrAll_.append(vrNew) OutModel_.append([vsIt, vpIt, thkIt]) OutError__.append(error) TotalModel.append([vsIt, vpIt, thkIt]) TotalVr.append(vrNew) TotalError.append(error) print 'it = {:} | Model {:} | Error = {:.2f} % | ErrMin = {:.2f} %'.format( i + 1, len(TotalModel), error, np.array(OutError).min()) idxMin2 = findMin(np.array(OutError__), nr, doubleasone=False) regions, vertices = voronoi_finite_polygons_2d(vor, point=idxMin2) for ni, nn in enumerate(idxMin2): OutPolygon.append(regions[ni]) OutPoint.append(vor.points[nn]) OutError.append(OutError__[nn]) OutModel.append(OutModel_[nn]) vrAll.append(vrAll_[nn]) OutPoint_[ij].append(vor.points[nn].reshape(-1)) OutVertices_[ij].append(vertices) OutError_[ij].append(OutError__[nn]) OutPolygon_[ij].append(regions[ni]) else: for ij in range(nr0): minErrs = findMin(np.array(OutError_[ij]), nr, doubleasone=False) for minErr in minErrs: bestRegions = OutPolygon_[ij][minErr] bestPoints = OutPoint_[ij][minErr] bestVertices = np.array( OutVertices_[ij][minErr])[bestRegions] points = gibbs(params, ns, border=bestVertices, center=bestPoints) points = points[1::1] points = points[0:ns] vor = Voronoi(points, qhull_options='QJ') vrAll_, OutModel_, OutError__ = [], [], [] for j in range(len(vor.regions)): vsIt, vpIt, thkIt = PointToParam( points[j], lapisan=(len(params) + 1) / 3) vrNew = mat_disperse(thkIt, dns, vpIt, vsIt, freq) error = ErrorPercentage(vrNew, vr) vrAll_.append(vrNew) OutModel_.append([vsIt, vpIt, thkIt]) OutError__.append(error) TotalModel.append([vsIt, vpIt, thkIt]) TotalVr.append(vrNew) TotalError.append(error) print 'it = {:} | Model {:} | Error = {:.2f} % | ErrMin = {:.2f} %'.format( i + 1, len(TotalModel), error, np.array(OutError).min()) idxMin3 = findMin(np.array(OutError__), 1, doubleasone=False) regions, vertices = voronoi_finite_polygons_2d( vor, point=idxMin3) OutPoint_[ij].append(vor.points[idxMin3].reshape(-1)) OutVertices_[ij].append(vertices) OutError_[ij].append(OutError__[idxMin3[0]]) OutPolygon_[ij].append(regions[0]) for ni, nn in enumerate(idxMin3): OutPolygon.append(regions[ni]) OutPoint.append(vor.points[nn]) OutError.append(OutError__[nn]) OutModel.append(OutModel_[nn]) vrAll.append(vrAll_[nn]) if np.array(TotalError).min() < maxerr: break return TotalVr, TotalModel, TotalError
def cutout_image_polygons(image: Union[PILImage, np.ndarray], max_angle: int, plot_image: bool = False) -> List[PILImage]: """ Cut an image into voronoi polygons First we distribute random points on the picture. Then we create the voronoi polygons of these points and cut the image into parts according to these polygons. Finally each image is resized to constants.image_size. :param max_angle: Maximum rotation angle :param plot_image: Wether to plot the voronoi to an image :param image: Input image :return: A list of n x n images """ image_size = constants.image_size n = constants.n points = np.random.randint(low=0, high=image_size[0], size=(n * n, 2)) vor = Voronoi(points) regions, vertices = voronoi_finite_polygons_2d(vor) polygon_images = [] points = np.empty((n * n, 2)) for i, region in enumerate(regions): polygon = [tuple(x) for x in vertices[region]] # Create a masked image image_array = np.asarray(image) mask_image = Image.new('L', (image_array.shape[1], image_array.shape[0]), 0) ImageDraw.Draw(mask_image).polygon(polygon, outline=1, fill=1) mask = np.array(mask_image) image_array = image_array * np.stack([mask, mask, mask], axis=2) # Compute the center of mass for the mask. This is the center point for the region and will help us calculate # the index of the region later center = measurements.center_of_mass(mask) points[i, 0] = center[1] points[i, 1] = center[0] # Crop the image to the masked part coords = np.argwhere(image_array.sum(axis=2) > 0) x_min, y_min = coords.min(axis=0) x_max, y_max = coords.max(axis=0) cropped = image_array[x_min:x_max + 1, y_min:y_max + 1] # Append the resulting image polygon_image = Image.fromarray(cropped, "RGB").resize(constants.tile_size) if max_angle > 0: angle = np.random.randint(-max_angle, max_angle + 1) polygon_image = polygon_image.rotate(angle, expand=False) polygon_images.append(polygon_image) ind = np.lexsort((points[:, 0], -points[:, 1])) # Sort the image tiles from top to bottom and left to right polygon_images = [polygon_images[i] for i in ind] if plot_image: points = points[ind] plot_color = '#c2d2e9' # colorize ax = plt.gca() for region in regions: polygon = vertices[region] ax.add_patch( matplotlib.patches.Polygon(polygon, closed=True, fill=False, color=plot_color)) # plt.fill(*zip(*polygon), alpha=0.6) for i, point in enumerate(points): plt.plot(point[0], point[1], 'o', color=plot_color) # ax.annotate(i, (point[0], point[1])) # plt.xlim(0, 225) # plt.ylim(0, 225) plt.axis('off') plt.imshow(image, aspect='auto') plt.tight_layout() plt.savefig('plot.png') plt.show() return polygon_images
def voronoi_neighbors(points): vor = Voronoi(points) neighbor_pairs = vor.ridge_points return neighbor_pairs
def voronoialgo(self): sx = self.points[2][0] lx = self.points[0][0] sy = self.points[0][1] ly = self.points[2][1] # a_degree = [[0 for _ in range(len(trilist[i].simplices))] for i in # range(len(find_touchingpoint_keepinzone_list))] # coord = [[0 for _ in range(len(trilist[i].simplices))] for i in range(len(find_touchingpoint_keepinzone_list))] # arealist = [[0 for _ in range(len(trilist[i].simplices))] for i in # range(len(find_touchingpoint_keepinzone_list))] tri = Delaunay(self.points) vor = Voronoi(self.points[4:]) regions, vertices = self.voronoi_finite_polygons_2d(vor) # print(regions, vertices) ''' Visualization ''' fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) # ax1.set_xlim([self.points[2][0] - 0.05, self.points[1][0] + 0.05]) # ax1.set_ylim([self.points[0][1] - 0.05, self.points[1][1] + 0.05]) # ax2.set_xlim([self.points[2][0] - 0.05, self.points[1][0] + 0.05]) # ax2.set_ylim([self.points[0][1] - 0.05, self.points[1][1] + 0.05]) # ax3.set_xlim([self.points[2][0] - 0.05, self.points[1][0] + 0.05]) # ax3.set_ylim([self.points[0][1] - 0.05, self.points[1][1] + 0.05]) # ax4.set_ylim([self.points[2][0] - 0.05, self.points[1][0] + 0.05]) # ax4.set_xlim([self.points[0][1] - 0.05, self.points[1][1] + 0.05]) ax1.set_xlim([self.points[2][0], self.points[1][0]]) ax1.set_ylim([self.points[0][1], self.points[1][1]]) ax2.set_xlim([self.points[2][0], self.points[1][0]]) ax2.set_ylim([self.points[0][1], self.points[1][1]]) ax3.set_xlim([self.points[2][0], self.points[1][0]]) ax3.set_ylim([self.points[0][1], self.points[1][1]]) ax4.set_xlim([self.points[2][0], self.points[1][0]]) ax4.set_ylim([self.points[0][1], self.points[1][1]]) # print(self.points) # print(type(self.points[0])) # print(type(self.points)) #ax1.triplot(self.points[:, 0], self.points[:, 1], tri.simplices.copy()) ax1.plot(self.points[:, 0], self.points[:, 1], 'o') for i in range(len(self.points)): ax1.text(self.points[i][0], self.points[i][1], '{}'.format(i), fontsize=6) polygon_count = 0 region_count = 0 ''' Each polygon ''' nearpointslist = [] farpointslist = [] largepointslist = [] smallpointslist = [] nearpointslist_idx = [] farpointslist_idx = [] largepointslist_idx = [] smallpointslist_idx = [] totalpoints = [] waypointlist = [] for region in regions: convextest = [] in_keepinzone_points_coord = [] in_keepinzone_points_list = [] polygon = vertices[region] ax1.fill(*zip(*polygon), alpha=0.4) # print("-------------") # print(" ",str(polygon_count)," ") # print(vertices[region]) # print(region) ''' Points of Each polygon ''' for countvertices in range(len(vertices[region])): # print(countvertices, vertices[region]) if vertices[region][countvertices][0] > sx and vertices[ region][countvertices][0] < lx: if vertices[region][countvertices][1] > sy and vertices[ region][countvertices][1] < ly: # print(vertices[region][countvertices]) in_keepinzone_points_coord.append( vertices[region][countvertices].tolist()) # print(region[region_count]) in_keepinzone_points_list.append(region[region_count]) region_count += 1 # print("in_keepinzone_points_list\n",in_keepinzone_points_list) ''' keepinzone과 voronoi영역 만나는 점 추가 ''' in_keepinzone_points_coord = self.findtouchingpointkeepinzone( polygon, region, in_keepinzone_points_coord, in_keepinzone_points_list) ''' keepinzone의 꼭지점 추가 ''' in_keepinzone_points_coord = self.insertkeepinzonevertex( in_keepinzone_points_coord, polygon_count) #print(len(in_keepinzone_points_coord)) adjusted_polygon_points_coord = in_keepinzone_points_coord[:] ''' Visualization ''' in_keepinzone_points_coord = np.array(in_keepinzone_points_coord) # print("in_keepinzone_points_coord",in_keepinzone_points_coord) ax2.plot(in_keepinzone_points_coord[:, 0], in_keepinzone_points_coord[:, 1], 'o') ax2.plot(self.points[polygon_count + 4, 0], self.points[polygon_count + 4, 1], 'v') ax2.text(self.points[polygon_count + 4, 0], self.points[polygon_count + 4, 1] + 0.01, '{}'.format(polygon_count), fontsize=6) for ttt in range(len(in_keepinzone_points_coord)): ax2.text(in_keepinzone_points_coord[ttt][0], in_keepinzone_points_coord[ttt][1] + polygon_count * 0.02, '{} point:{}'.format(polygon_count, ttt), fontsize=6) ''' voronoi로 나눈 지역 delaunay로 나눔 ''' # recovery point 추가 adjusted_polygon_points_coord.insert( 0, self.points[polygon_count + 4].tolist()) trilist = Delaunay(adjusted_polygon_points_coord) #coordlist, arealist, degreelist = self.infotriangles(adjusted_polygon_points_coord, trilist) coordlist, arealist, oneofarea = self.infotriangles( adjusted_polygon_points_coord, trilist, self.points[polygon_count + 4]) # print("adjust\n",adjusted_polygon_points_coord) # print("trilist.simplices.copy()\n",trilist.simplices) # print("arealist\n",arealist) # print("coordlist\n",coordlist) totalpoints.append(coordlist) waypointlist.append(oneofarea) ''' NEAR POINTS ''' nearpoints_idx = self.calcdistancecenterandrecovery( coordlist, self.points[polygon_count + 4]) nearpoints = [0 for _ in range(len(coordlist))] for i in range(len(nearpoints_idx)): nearpoints[i] = coordlist[nearpoints_idx[i]] nearpointslist.append(nearpoints) nearpointslist_idx.append(nearpoints_idx) farpoints = nearpoints[::-1] farpointslist.append(farpoints) farpointslist_idx.append(nearpoints_idx[::-1]) # print("NEAR") # print(np.array(coordlist)) # print(np.array(nearpoints_idx)) # print(np.array(nearpoints)) ''' NEAR POINTS END ''' ''' SIZE POINTS ''' smallpoints_idx = self.sortaraesize(arealist) smallpoints = [0 for _ in range(len(coordlist))] for i in range(len(smallpoints_idx)): smallpoints[i] = coordlist[smallpoints_idx[i]] smallpointslist.append(smallpoints) smallpointslist_idx.append(smallpoints_idx) largepoints = smallpoints[::-1] largepointslist.append(largepoints) largepointslist_idx.append(smallpoints_idx[::-1]) ''' SIZE POINTS END ''' #print(np.array(nearpointslist)) # for i in range(len(nearpoints)): # convextest.append(nearpoints[i]) # # for i in range(len(adjusted_polygon_points_coord)): # # convextest.append(adjusted_polygon_points_coord[i]) # # convextest = np.array(convextest) # print("convextest\n",convextest) # hull = ConvexHull(convextest) # print(hull.points) # for simplex in hull.simplices: # ax4.plot(convextest[simplex, 0], convextest[simplex, 1], 'k-') # #ax4.text(coordlist[simplex, 0], coordlist[simplex, 1],'{}'.format()) # print("convextest[hull.simplices]\n", convextest[hull.simplices, 1]) ''' Visualization ''' coordlist = np.array(coordlist) #coordlist = coordlist adjusted_polygon_points_coord = np.array( adjusted_polygon_points_coord) ax3.triplot(adjusted_polygon_points_coord[:, 0], adjusted_polygon_points_coord[:, 1], trilist.simplices.copy()) ax3.plot(coordlist[:, 0], coordlist[:, 1], 'o') for ttt in range(len(trilist.simplices)): ax3.text(coordlist[ttt][0], coordlist[ttt][1] + polygon_count * 0.01, '{}\n{}'.format(ttt, round(arealist[ttt], 3)), fontsize=6) # ax4.triplot(adjusted_polygon_points_coord[:, 1], adjusted_polygon_points_coord[:, 0],trilist.simplices.copy()) # ax4.plot(coordlist[:, 1], coordlist[:, 0], 'o') # # for ttt in range(len(trilist.simplices)): # ax4.text(coordlist[ttt][1], coordlist[ttt][0] + polygon_count * 0.01, # '{}\n{}'.format(ttt, round(arealist[ttt], 3)), fontsize=6) polygon_count += 1 region_count = 0 print("waypoints!!!\n", waypointlist) waypointlist = np.array(waypointlist) for i in range(len(waypointlist)): waypointlist[i] = np.array(waypointlist[i]) for j in range(len(waypointlist[i])): ax4.plot(waypointlist[i][j][:, 0], waypointlist[i][j][:, 1], 'v') for k in range(len(waypointlist[i][j])): ax4.text(waypointlist[i][j][k][0], waypointlist[i][j][k][1], '{}'.format(k), fontsize=6) ''', set order of points ''' distancelist = [] shortestroute = [] for i in range(len(totalpoints)): #print("nearpointslist[i]\n",totalpoints[i]) if self.startway == 0: startidx = nearpointslist_idx[i][0] elif self.startway == 1: startidx = farpointslist_idx[i][0] elif self.startway == 2: startidx = smallpointslist_idx[i][0] else: startidx = largepointslist_idx[i][0] temp, route = self.findnearestlist(totalpoints[i], startidx) #print("route\n",route) distancelist.append(temp) shortestroute.append(route) ''' set order of points END ''' totalpoints = np.array(totalpoints) nearpointslist = np.array(nearpointslist) farpointslist = np.array(farpointslist) largepointslist = np.array(largepointslist) smallpointslist = np.array(smallpointslist) print("totalpoints\n", totalpoints) # print("near\n", nearpointslist) # print(nearpointslist_idx) # print("far\n", farpointslist) # print(farpointslist_idx) # print("large\n", largepointslist) # print(largepointslist_idx) # print("small\n", smallpointslist) # print(smallpointslist_idx) # # print("distancelist\n",np.array(distancelist)) # print("shortestroute\n",shortestroute) self.searchcoord = totalpoints self.searchroute = shortestroute plt.show()
def Seg(name, directory, ParentImg, id_oriImg): fullpath=directory+'/'+name img = cv2.imread(fullpath) #imgray = cv2.imread(fullpath,0) img_N = cv2.imread(fullpath) img_N[:,:,1] = 0 img_N[:,:,2]= 0 img2 = cv2.imread(fullpath) img2[:,:,0]= 0 img2[:,:,2]= 0 mito_grayimg = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) blur_mito = cv2.blur(mito_grayimg,(7,7)) (thresh1, im_bwmito) = cv2.threshold(blur_mito, 255, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) kernel1 = np.ones((20,20),np.uint8) dilate_mito = cv2.dilate(im_bwmito,kernel1,iterations = 1) label_mito=measure.label(dilate_mito,connectivity=2) properties_mito = regionprops(label_mito) masscenter_mito=[] for pro in properties_mito: masscenter_mito.append(pro.centroid) masscenter_mitop=np.array(masscenter_mito) masscenter_mitop[:, [0, 1]] = masscenter_mitop[:, [1, 0]] gray_image = cv2.cvtColor(img_N, cv2.COLOR_BGR2GRAY) imgb = gray_image (thresh, im_bw) = cv2.threshold(imgb, 255, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) median = cv2.medianBlur(im_bw,5) imgfill, contours, hierarchy = cv2.findContours(median,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: cv2.drawContours(median,[cnt],0,255,-1) kernel = np.ones((4,4),np.uint8) erosion = cv2.erode(imgfill,kernel,iterations = 1) kernel = np.ones((25,25),np.uint8) opening = cv2.morphologyEx(erosion, cv2.MORPH_OPEN, kernel) labels=measure.label(opening,connectivity=2) dst=color.label2rgb(labels) blobs = img >0.75 properties = regionprops(labels) for p in properties: min_row, min_col, max_row, max_col = p.bbox lbl,nlbls = ndimage.label(np.array(opening)) r, c = np.vstack(ndimage.center_of_mass(np.array(opening),lbl,np.arange(nlbls)+1)).T centerpoints = np.array(ndimage.center_of_mass(np.array(opening),lbl,np.arange(nlbls)+1)) centerpoints[:, [0, 1]] = centerpoints[:, [1, 0]] points = centerpoints vor = Voronoi(points) #voronoi_plot_2d(vor) voronoi_kdtree = cKDTree(points) extraPoints = [] imgSet = [] height, width = img2.shape[:2] extraPoints = masscenter_mitop test_point_dist, test_point_regions = voronoi_kdtree.query(extraPoints) true_regions=[] true_regions=test_point_regions+1 true_regions true_regions[1] shuzu = [[] for _ in range(nlbls+1)] for i in range(true_regions.shape[0]): shuzu[true_regions[i]].append(i+1) File_Path = os.getcwd()+'/media' #if not os.path.exists(File_Path): #os.makedirs(File_Path) def showandshoweachcell(shuzu): for i1 in range(len(shuzu)): imgoriginal = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) if len(shuzu[i1]) != 0: mask = (labels == i1) for i2 in range(len(shuzu[i1])): mask = mask|(label_mito==shuzu[i1][i2]) get_high_vals = mask ==0 imgoriginal[get_high_vals] = 0 plt.title('Cell%i'%i1) plt.axis('off') plt.imshow(imgoriginal) plt.savefig(File_Path+'/'+name+"_cell%s.png"%i1, dpi = 300) plt.show() SegImgName=name+'_cell%s.png'%i1 conn = pymysql.connect(host='localhost', port=3306, \ user='******', passwd='Yinchuandog45#',\ db='Seg', charset='utf8') c=conn.cursor() dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") c.execute('insert into Seg_segimg(SegImgName,ParentImg,FileDirectorySegImg,CreateTimeSeg,oriImg_id)\ values("{}", "{}", "{}", "{}", "{}")'.format(SegImgName,ParentImg,File_Path,dt,id_oriImg)) #data=(repr(SegImgName), repr(ParentImg), repr(dic), repr(dt), repr(id_oriImg)) #sql = "insert into citsec('SegImgName', 'ParentImg', 'FileDirectorySegImg', 'CreateTimeSeg', 'oriImg_id') values(%s,%s,%s,%s,%s)" #c.execute("insert into Seg_segimg \ #values(repr(SegImgName), repr(ParentImg), repr(dic), repr(dt), repr(id_oriImg)") #c.execute(sql_insert) c.close() conn.commit() showandshoweachcell(shuzu)
# point_list[3] = [-121.4366, 39.5177] # # point_list[4] = [-121.2713, 39.9669] # point_list[5] = [-120.747, 39.872] # point_list[6] = [-120.7513, 39.6712] # point_list[7] = [39.7181, -121.254] # point_list[8] = [39.8012, -121.1] # point_list[9] = [39.6964, -120.727] # point_list[10] = [39.6133, -121.077] # point_list[11] = [39.7381, -121.354] point_list = np.array(point_list) print(point_list) # compute Voronoi tesselation vor = Voronoi(point_list[4:]) # plot ver = vor.vertices.tolist() ver = np.array(ver) regions, vertices = voronoi_finite_polygons_2d(vor) # colorize idx = [] t = 0 vertex_list = [[] for _ in range(len(point_list[4:]))] findpointlist = [0 for _ in range(len(point_list[4:]))] sx = point_list[2][0] lx = point_list[0][0] sy = point_list[0][1]
def voronoi(adata, color_by=None, colors=None, x_coordinate='X_centroid', y_coordinate='Y_centroid', imageid='imageid', subset=None, voronoi_edge_color='black', voronoi_line_width=0.1, voronoi_alpha=0.5, size_max=np.inf, overlay_points=None, overlay_points_categories=None, overlay_drop_categories=None, overlay_points_colors=None, overlay_point_size=5, overlay_point_alpha=1, overlay_point_shape=".", plot_legend=True, legend_size=6, **kwargs): """ Parameters ---------- adata : Anndata object color_by : string, optional Color the voronoi diagram based on categorical variable (e.g. cell types or neighbourhoods). Pass the name of the column which contains the categorical variable. The default is None. colors : string or Dict, optional Custom coloring the voronoi diagram. The parameter accepts `sns color palettes` or a python dictionary mapping the categorical variable with the required color. The default is None. x_coordinate : float, required Column name containing the x-coordinates values. The default is 'X_centroid'. y_coordinate : float, required Column name containing the y-coordinates values. The default is 'Y_centroid'. imageid : string, optional Column name of the column containing the image id. The default is 'imageid'. subset : string, optional imageid of a single image to be subsetted for plotting. The default is None. voronoi_edge_color : string, optional A Matplotlib color for marking the edges of the voronoi. If `facecolor` is passed, the edge color will always be the same as the face color. The default is 'black'. voronoi_line_width : float, optional The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well. The default is 0.1. voronoi_alpha : float, optional The alpha blending value, between 0 (transparent) and 1 (opaque). The default is 0.5. overlay_points : string, optional It is possible to overlay a scatter plot on top of the voronoi diagram. Pass the name of the column which contains categorical variable to be overlayed. The default is None. overlay_points_categories : list, optional If the passed column in `overlay_points` contains multiple categories, however the user is only interested in a subset of categories, those specific names can be passed as a list. By default all categories will be overlayed on the voronoi diagram. The default is None. overlay_drop_categories : list, optional Similar to `overlay_points_categories`. Here for ease of use, especially if large number of categories are present. The user can drop a set of categories. The default is None. overlay_points_colors : string or dict, optional Similar to `colors`. User can pass in a a) solid color (like `black`) b) sns palettes name (like `Set1`) c) python dictionary mapping the categories with custom colors The default is None. overlay_point_size : float, optional Overlay scatter plot point size. The default is 5. overlay_point_alpha : float, optional The alpha blending value for the overlay, between 0 (transparent) and 1 (opaque). The default is 1. overlay_point_shape : string, optional The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. The default is ".". plot_legend : bool, optional Define if the figure legend should be plotted. Please note the figure legend may be out of view and you may need to resize the image to see it, especially the legend for the scatter plot which will be on the left side of the plot. The default is True. legend_size : float, optional Resize the legend if needed. The default is 6. Example ------- ``` sm.pl.voronoi(adata, color_by='phenotype', colors=None, x_coordinate='X_position', y_coordinate='Y_position', imageid='ImageId',subset=None, voronoi_edge_color = 'black',voronoi_line_width = 0.2, voronoi_alpha = 0.5, size_max=np.inf, overlay_points='phenotype', overlay_points_categories=None, overlay_drop_categories=None, overlay_point_size = 5, overlay_point_alpha= 1, overlay_point_shape=".", plot_legend=False, legend_size=6) ``` """ # create the data frame needed data = adata.obs # Subset the image of interest if subset is not None: data = data[data[imageid] == subset] # create an extra column with index information data['index_info'] = np.arange(data.shape[0]) # generate the x and y coordinates points = data[[x_coordinate, y_coordinate]].values # invert the Y-axis points[:, 1] = max(points[:, 1]) - points[:, 1] # Generate colors if color_by is None: colors = np.repeat('#e5e5e5', len(data)) # elif color_by is None and colors is not None: # if isinstance(colors,str): # colors = np.repeat(colors, len(data)) elif color_by is not None and colors is None: # auto color the samples if len(np.unique(data[color_by])) <= 9: c = sns.color_palette('Set1')[0:len(np.unique(data[color_by]))] if len(np.unique(data[color_by])) > 9 and len(np.unique( data[color_by])) <= 20: c = sns.color_palette('tab20')[0:len(np.unique(data[color_by]))] if len(np.unique(data[color_by])) > 20: # For large categories generate random colors np.random.seed(0) c = np.random.rand(len(np.unique(data[color_by])), 3).tolist() # merge colors with phenotypes/ categories of interest p = np.unique(data[color_by]) c_p = dict(zip(p, c)) # map to colors colors = list(map(c_p.get, list(data[color_by].values))) elif color_by is not None and colors is not None: # check if colors is a dictionary or a sns color scale if isinstance(colors, str): if len(sns.color_palette(colors)) < len(np.unique(data[color_by])): raise ValueError( str(colors) + ' includes a maximun of ' + str(len(sns.color_palette(colors))) + ' colors, while your data need ' + str(len(np.unique(data[color_by]))) + ' colors') else: c = sns.color_palette(colors)[0:len(np.unique(data[color_by]))] # merge colors with phenotypes/ categories of interest p = np.unique(data[color_by]) c_p = dict(zip(p, c)) if isinstance(colors, dict): if len(colors) < len(np.unique(data[color_by])): raise ValueError( 'Color mapping is not provided for all categories. Please check' ) else: c_p = colors # map to colors colors = list(map(c_p.get, list(data[color_by].values))) # create the voronoi object vor = Voronoi(points) # trim the object regions, vertices = voronoi_finite_polygons_2d(vor) # plotting pts = MultiPoint([Point(i) for i in points]) mask = pts.convex_hull new_vertices = [] if type(voronoi_alpha) != list: voronoi_alpha = [voronoi_alpha] * len(points) areas = [] for i, (region, alph) in enumerate(zip(regions, voronoi_alpha)): polygon = vertices[region] shape = list(polygon.shape) shape[0] += 1 p = Polygon(np.append(polygon, polygon[0]).reshape(*shape)).intersection(mask) areas += [p.area] if p.area < size_max: poly = np.array( list( zip(p.boundary.coords.xy[0][:-1], p.boundary.coords.xy[1][:-1]))) new_vertices.append(poly) if voronoi_edge_color == 'facecolor': plt.fill(*zip(*poly), alpha=alph, edgecolor=colors[i], linewidth=voronoi_line_width, facecolor=colors[i]) plt.xticks([]) plt.yticks([]) else: plt.fill(*zip(*poly), alpha=alph, edgecolor=voronoi_edge_color, linewidth=voronoi_line_width, facecolor=colors[i]) plt.xticks([]) plt.yticks([]) # Add scatter on top of the voronoi if user requests if overlay_points is not None: if overlay_points_categories is None: d = data if overlay_points_categories is not None: # convert to list if needed (cells to keep) if isinstance(overlay_points_categories, str): overlay_points_categories = [overlay_points_categories] # subset cells needed d = data[data[overlay_points].isin(overlay_points_categories)] if overlay_drop_categories is not None: # conver to list if needed (cells to drop) if isinstance(overlay_drop_categories, str): overlay_drop_categories = [overlay_drop_categories] # subset cells needed d = d[-d[overlay_points].isin(overlay_drop_categories)] # Find the x and y coordinates for the overlay category #points_scatter = d[[x_coordinate,y_coordinate]].values points_scatter = points[d.index_info.values] # invert the Y-axis #points_scatter[:,1] = max(points_scatter[:,1])-points_scatter[:,1] # Generate colors for the scatter plot if overlay_points_colors is None and color_by == overlay_points: # Borrow color from vornoi wanted_keys = np.unique(d[overlay_points]) # The keys to extract c_p_scatter = dict((k, c_p[k]) for k in wanted_keys if k in c_p) elif overlay_points_colors is None and color_by != overlay_points: # Randomly generate colors for all the categories in scatter plot # auto color the samples if len(np.unique(d[overlay_points])) <= 9: c_scatter = sns.color_palette( 'Set1')[0:len(np.unique(d[overlay_points]))] if len(np.unique(d[overlay_points])) > 9 and len( np.unique(d[overlay_points])) <= 20: c_scatter = sns.color_palette( 'tab20')[0:len(np.unique(d[overlay_points]))] if len(np.unique(d[overlay_points])) > 20: # For large categories generate random colors np.random.seed(1) c_scatter = np.random.rand(len(np.unique(d[overlay_points])), 3).tolist() # merge colors with phenotypes/ categories of interest p_scatter = np.unique(d[overlay_points]) c_p_scatter = dict(zip(p_scatter, c_scatter)) elif overlay_points_colors is not None: # check if the overlay_points_colors is a pallete if isinstance(overlay_points_colors, str): try: c_scatter = sns.color_palette(overlay_points_colors)[ 0:len(np.unique(d[overlay_points]))] if len(sns.color_palette(overlay_points_colors)) < len( np.unique(d[overlay_points])): raise ValueError( str(overlay_points_colors) + ' pallete includes a maximun of ' + str(len(sns.color_palette( overlay_points_colors))) + ' colors, while your data (overlay_points_colors) need ' + str(len(np.unique(d[overlay_points]))) + ' colors') except: c_scatter = np.repeat( overlay_points_colors, len(np.unique( d[overlay_points]))) #[overlay_points_colors] # create a dict p_scatter = np.unique(d[overlay_points]) c_p_scatter = dict(zip(p_scatter, c_scatter)) if isinstance(overlay_points_colors, dict): if len(overlay_points_colors) < len( np.unique(d[overlay_points])): raise ValueError( 'Color mapping is not provided for all categories. Please check overlay_points_colors' ) else: c_p_scatter = overlay_points_colors # map to colors colors_scatter = list( map(c_p_scatter.get, list(d[overlay_points].values))) #plt.scatter(x = points_scatter[:,0], y = points_scatter[:,1], s= overlay_point_size, alpha= overlay_point_alpha, c= colors_scatter, marker=overlay_point_shape) plt.scatter(x=points_scatter[:, 0], y=points_scatter[:, 1], s=overlay_point_size, alpha=overlay_point_alpha, c=colors_scatter, marker=overlay_point_shape, **kwargs) plt.xticks([]) plt.yticks([]) if plot_legend is True: # Add legend to voronoi patchList = [] for key in c_p: data_key = mpatches.Patch(color=c_p[key], label=key) patchList.append(data_key) first_legend = plt.legend(handles=patchList, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., prop={'size': legend_size}) plt.tight_layout() # Add the legend manually to the current Axes. ax = plt.gca().add_artist(first_legend) if overlay_points is not None: # Add legend to scatter patchList_scatter = [] for key in c_p_scatter: data_key_scatter = mpatches.Patch(color=c_p_scatter[key], label=key) patchList_scatter.append(data_key_scatter) plt.legend(handles=patchList_scatter, bbox_to_anchor=(-0.05, 1), loc=1, borderaxespad=0., prop={'size': legend_size})
def Fonction2(fichier, couleur): point=lis_point(fichier) vor_2d = Voronoi(point) t1=time.time() data=[] data=voronoi_cell_area(vor_2d) t2=time.time() print(t2-t1) vor_2d = Voronoi(point+create_border(point)) daaa=voronoi_cell_area_test(vor_2d) t3=time.time() print(t3-t2) """ """ histogramme(data[0], 200,1,1,0.1,1000, fichier, couleur, 2) #plt.legend() """ plt.figure(3) plt.hist(log10(data[0]), bins=200, normed=1, color = couleur, log=True) #plt.hist(log10(data), bins=200, normed=1, color = 'b') plt.xlabel('log10(x)') plt.savefig('Hist_log.png') #plt.figure(2) plt.figure(4) plt.yscale('log') n = 200 m, sig = moyenne(log10(data[0])), ecartype(log10(data[0])) X = npr.normal(m, sig, n) x = np.arange(X.min(), X.max() + 0.01, 0.01) plt.plot(x, st.norm.pdf(x, m, sig), couleur, linewidth=1, label=fichier[5:10]) plt.title('Log(Aire) des cellules de Voronoi') plt.legend() plt.savefig('Loi_log.png') """ dens=density(point, 100) """ histogramme(dens, int(max(dens)),0,0,0,40, "density", couleur, 4) loi_de_Poisson(moyenne(dens)) """ """ for i in range(len(dens)): dens[i]=dens[i]/(len(data[0])) """ """ histogramme(dens, 200,1,1,0,40, fichier, couleur, 5) histogramme(dens, int(max(dens)),0,1,0,1000, "Density", couleur, 7) loi_de_Poisson(moyenne(dens), int(max(dens))) plt.legend() plt.figure(6) rang=int(6*ecartype(dens)) plt.hist(log10(dens), bins=rang, normed=1, color = couleur, log=True) plt.title('Density_log') plt.savefig('Density_log.png') """ print("------------------------------------------") return dens, data
# Real space moire potential moire_potential = bandcalc.calc_moire_potential_on_grid(grid, GM, Vj) # Reciprocal space moire potential mp_moire = bandcalc.generate_monkhorst_pack_set(m, 100) moire_potential_pointwise = bandcalc.calc_moire_potential(mp_moire, GM, Vj) rec_moire_potential = bandcalc.calc_moire_potential_reciprocal_on_grid( mp_moire, grid_r, moire_potential_pointwise) # Results fig, axs = plt.subplots(nrows=2, ncols=2) contour = bandcalc.plot_moire_potential(axs[0,0], grid, np.real(moire_potential), alpha=0.4) moire_lattice = bandcalc.generate_lattice_by_shell(m, 2) bandcalc.plot_lattice(axs[0,0], moire_lattice, "ko") vor_m = Voronoi(moire_lattice) voronoi_plot_2d(vor_m, axs[0,0], show_points=False, show_vertices=False) bandcalc.plot_lattice(axs[0,0], mp_moire, "b,", alpha=0.4) rec_moire_lattice = bandcalc.generate_lattice_by_shell(rec_m, 3) axs[0,0].axis("scaled") axs[0,0].set_xlim([size.min(), size.max()]) axs[0,0].set_ylim([size.min(), size.max()]) for i, ax in enumerate(axs.ravel()[1:]): bandcalc.plot_lattice(ax, rec_moire_lattice, "ko") fun = [np.real, np.imag, np.abs][i] title = ["real", "imaginary", "absolute"][i] rec_contour = bandcalc.plot_moire_potential(ax, grid_r, fun(rec_moire_potential), alpha=0.4)
for id in region_id: # assign color for each region if not -1 in region_id[id]: polygon = [vor.vertices[i] for i in region_id[id]] plt.fill(*zip(*polygon), color=color_dict[id]) # def colorRegions2(vor): # regions, vertices = voronoi_finite_polygons_2d(vor) # polygons = [] # for reg in regions: # polygon = vertices[reg] # polygons.append(polygon) # for poly in polygons: if (__name__ == '__main__'): graphdataset, pos = construct_graph("gd.gv") coor_lis = [] for p in range(0, len(pos.keys())): coor_lis.append(pos[str(p)]) vor = Voronoi(np.stack(coor_lis)) colorRegions(vor) voronoi_plot_2d(vor, show_vertices=False) plt.show() #partition = node_clustering(graphdataset) #draw_vor(pos, partition)
# a = [rotate((0,0.5),10), # rotate((0,0.5),20), # rotate((0,0.5),50), # rotate((0,0.5),70), # rotate((0,0.5),80), # rotate((0,0.5),100), # rotate((0,0.5),120), # rotate((0,0.5),180), # rotate((0,0.5),190), # rotate((0,0.5),210), # rotate((0,0.5),300), # rotate((0,0.5),320), # rotate((0,0.5),380), # rotate((0,0.5),390), # rotate((0,0.5),310),] vor = Voronoi(np.array(a)) fig = voronoi_plot_2d(vor) plt.show() b = fortunes(a) # print(b, a) plot(b, a) import matplotlib.pyplot as plt import numpy as np from scipy.spatial import Voronoi, voronoi_plot_2d import sys # eps = sys.float_info.epsilon # n_towers = 100 # towers = np.random.rand(n_towers, 2)