def Del_pnts(pnts, testing=False, plot=True): """Triangulate the points and return the triangles Parameters ---------- pnts : np.array Points in array format. out : array an array of triangle points Notes ----- >>> pnts = pnts.reshape((1,) + pnts.shape) # a 3D set of points (ndim=3) >>> [pnts] # or pass in as a list """ pnts = np.unique(pnts, axis=0) # get the unique points only avg = np.mean(pnts, axis=0) p = pnts - avg tri = Delaunay(p) simps = tri.simplices del_pnts = [p[s] + avg for s in simps] if testing: print("{}".format(del_pnts)) if plot: delaunay_plot_2d(tri) return del_pnts, pnts, simps
def Del_pnts(pnts, testing=False, plot=True): """Triangulate the points and return the triangles Parameters: ----------- pnts : np.array Points in array format. out : array an array of triangle points Notes: ------ >>> pnts = pnts.reshape((1,) + pnts.shape) # a 3D set of points (ndim=3) >>> [pnts] # or pass in as a list """ pnts = np.unique(pnts, axis=0) # get the unique points only avg = np.mean(pnts, axis=0) p = pnts - avg tri = Delaunay(p) simps = tri.simplices del_pnts = [p[s]+avg for s in simps] if testing: print("{}".format(del_pnts)) if plot: delaunay_plot_2d(tri) return del_pnts, pnts, simps
def test_delaunay(self): # Smoke test fig = plt.figure() obj = Delaunay(self.points) s_before = obj.simplices.copy() r = delaunay_plot_2d(obj, ax=fig.gca()) assert_array_equal(obj.simplices, s_before) # shouldn't modify assert_(r is fig) delaunay_plot_2d(obj, ax=fig.gca())
def test_delaunay(self): # Smoke test fig = plt.figure() obj = Delaunay(self.points) s_before = obj.simplices.copy() with suppress_warnings() as sup: # filter can be removed when matplotlib 1.x is dropped sup.filter(message="The ishold function was deprecated in version") r = delaunay_plot_2d(obj, ax=fig.gca()) assert_array_equal(obj.simplices, s_before) # shouldn't modify assert_(r is fig) delaunay_plot_2d(obj, ax=fig.gca())
def read_ncr_points_from_csv_and_plot_2D_and_hull(): pathfile = "/Users/mamuts/Desktop/ncr-param-vals.csv" raw = coio.read_from_csv(pathfile) # remember to transpose pnts = np.transpose(np.transpose(raw)[0:2]) # 0-1 #pnts = np.transpose(np.transpose(raw)[1:3]) # 1-2 pnts = np.transpose(np.transpose(raw)[2:]) # 0-3, 0-2, 1-3, #2-3 hull = scsp.ConvexHull(pnts) tri = scsp.Delaunay(pnts) pp.plot(np.transpose(pnts)[0], np.transpose(pnts)[1], 'o') for simplex in hull.simplices: pp.plot(pnts[simplex, 0], pnts[simplex, 1], 'k-') scsp.delaunay_plot_2d(tri) pp.show()
def _tri_demo(tri_type='Delaunay'): """Triangulation demo. """ from scipy.spatial import delaunay_plot_2d, voronoi_plot_2d import matplotlib.pyplot as plt xs =[ 48, 8, 623, 615, 196, 368, 112, 918, 318, 316, 427, 364, 849, 827, 438, 957, 495, 317, 985, 534] ys = [674, 215, 834, 235, 748, 630, 876, 407, 33, 872, 893, 360, 397, 902, 420, 430, 678, 523, 604, 292] aa = np.array(list(zip(xs, ys))) c = infinity_circle(aa, fac=0) a = np.vstack((aa, c)) d = v = None # initialize the output to None if tri_type == 'Delaunay': d = Delaunay(aa) plot = delaunay_plot_2d(d) x0, y0 = [0., 0.] x1, y1 = [1000., 1000.] else: c = infinity_circle(a, fac=2) # a = np.vstack((a, c)) x0, y0 = a.min(axis=0) x1, y1 = a.max(axis=0) v = Voronoi(a, qhull_options='Qbb Qc Qx') plot = voronoi_plot_2d(v, show_vertices=True, line_colors='y', line_alpha=0.8, point_size=5) # ---- plot.set_figheight(10) plot.set_figwidth(10) plt.axis([0, 1000, 0, 1000]) # plt.axis([x0, x1, y0, y1]) plt.show() return aa, (d or v)
def delaunayGraph(npPoints): # Use delaunay triangulation graph to get neighbors delaunay = Delaunay(npPoints[:-4], qhull_options='Qc') _ = delaunay_plot_2d(delaunay) # Annotate the points for i in range(0, len(npPoints[:-4])): plt.annotate(text=i, xy=(npPoints[:-4][i][0], npPoints[:-4][i][1])) # Use delaunay triangulation to get the neighbors indptr, indices = delaunay.vertex_neighbor_vertices # ([indptr], [indices]) # for index k, neighbors are indices[indptr[k]:indptr[k+1]] delaunayDict = dict() for k in range(0, len(npPoints[:-4])): startIndex = indptr[k] endIndex = indptr[k + 1] for i in range(startIndex, endIndex): if k in delaunayDict: delaunayDict[k].append(indices[i]) else: delaunayDict[k] = [indices[i]] # Change and print the plot to a square equal axis plt.axis('equal') plt.xlim([xLowerLimit, xHigherLimit]), plt.ylim([yLowerLimit, yHigherLimit]) plt.savefig('graph_Delaunay.png') return delaunayDict
def DrawVoronoiTesselation(hdf5_file, frame=0): """ wanted structure: np.array([[3, 0], [4.2, 1], [0, 8], ...]) :return: """ x_gfp, y_gfp, x_rfp, y_rfp = GetXandYcoordinatesPerFrame(hdf5_file=hdf5_file, frame=frame) #x_gfp, y_gfp, x_rfp, y_rfp = ConvertXandYcoordinates(x_gfp, y_gfp, x_rfp, y_rfp) # Restructure so that you get a matrix; merge channels as the cell identity is not important in this case: points = [] for x, y in zip(x_gfp + x_rfp, y_gfp + y_rfp): points.append([x, y]) points = np.array(points) vor = sp.Voronoi(points) tri = sp.Delaunay(points) fig = sp.voronoi_plot_2d(vor) fig = sp.delaunay_plot_2d(tri) plt.grid(which='major') plt.show() plt.close() return vor, tri
def plot(self): """lets just steal it """ from scipy.spatial import delaunay_plot_2d fig = delaunay_plot_2d(self) ax = fig.gca() ax.set_aspect("equal") return fig, ax
def Visualise_Delaunay_Triang(self, tri): _ = sp.delaunay_plot_2d(tri=tri) plt.xlim(0, 1200) plt.ylim(0, 1600) plt.title("Delaunay Triangulation for Local Density Calculations") plt.xlabel("FiJi Y-axis (pixels)") plt.ylabel("FiJi X-axis (pixels)") plt.show() plt.close()
def plot(mesh): """ 2D plot of mesh """ from scipy.spatial import delaunay_plot_2d fig = delaunay_plot_2d(SimpleMesh(mesh)) ax = fig.gca() ax.set_aspect("equal") return fig, ax
def run(filename): with open(filename, 'r') as in_file: file = in_file.read() points = [pair.split("\t") for pair in file.split("\n")] for i in range(len(points)): points[i] = [float(points[i][0]), float(points[i][1])] points.pop() computeEPS(points) fig, ax = plt.subplots() tri = Delaunay(points) delaunay_plot_2d(tri, ax=ax) plt.show() return edges, faces, vertices = triangulate(points) flip_edges(edges, faces, vertices) print("number of triangles = " + str(len(faces))) print("number of edges = " + str(len(edges))) print("number of vertices = " + str(len(vertices))) plt.show() return
def generate_inp_data(name, width, height, nodes_count): #generowanie wierzchołków na krawędziach nodes = [] nodes.append([1, 0, 0]) node_id = 2 for i in range(nodes_count): node = [node_id, width * (i + 1) / (nodes_count + 1), 0] nodes.append(node) node_id += 1 nodes.append([node_id, width, 0]) node_id += 1 for i in range(nodes_count): node = [node_id, width, height * (i + 1) / (nodes_count + 1)] nodes.append(node) node_id += 1 nodes.append([node_id, width, height]) node_id += 1 for i in range(nodes_count): node = [node_id, width - width * (i + 1) / (nodes_count + 1), height] nodes.append(node) node_id += 1 nodes.append([node_id, 0, height]) node_id += 1 for i in range(nodes_count): node = [node_id, 0, height - height * (i + 1) / (nodes_count + 1)] nodes.append(node) node_id += 1 nodes = np.array(nodes) #triangulacja przestrzeni tri = Delaunay(nodes[:, 1:]) fig = delaunay_plot_2d(tri) #generowanie obrazka .png z podglądem wyniku ax = fig.get_axes() ax[0].set_aspect("equal") fig.savefig("outputPreview.png") #tworzenie listy z opisem elementów, które stworzyliśmy triangulacją elements = np.append(np.array([[node_id + i] for i in range(len(tri.simplices))]), tri.simplices + 1, axis=1) return nodes, elements
def _tri_demo(tri_type='Delaunay'): """Triangulation demo. """ from scipy.spatial import delaunay_plot_2d, voronoi_plot_2d import matplotlib.pyplot as plt xs = [ 48, 8, 623, 615, 196, 368, 112, 918, 318, 316, 427, 364, 849, 827, 438, 957, 495, 317, 985, 534 ] ys = [ 674, 215, 834, 235, 748, 630, 876, 407, 33, 872, 893, 360, 397, 902, 420, 430, 678, 523, 604, 292 ] aa = np.array(list(zip(xs, ys))) c = infinity_circle(aa, fac=0) a = np.vstack((aa, c)) d = v = None # initialize the output to None if tri_type == 'Delaunay': d = Delaunay(aa) plot = delaunay_plot_2d(d) x0, y0 = [0., 0.] x1, y1 = [1000., 1000.] else: c = infinity_circle(a, fac=2) # a = np.vstack((a, c)) x0, y0 = a.min(axis=0) x1, y1 = a.max(axis=0) v = Voronoi(a, qhull_options='Qbb Qc Qx') plot = voronoi_plot_2d(v, show_vertices=True, line_colors='y', line_alpha=0.8, point_size=5) # ---- plot.set_figheight(10) plot.set_figwidth(10) plt.axis([0, 1000, 0, 1000]) # plt.axis([x0, x1, y0, y1]) plt.show() return aa, (d or v)
def Calculate_Local_Density(self, frame, show=False): """ """ # 1.) Extract the coordinates of all GFP & RFP cells at specified frame: cell_coords, cell_map = self.Extract_Cell_Coords(frame=frame) # Take care of blank frames: if len(cell_coords) < 3: # a triangle cannot be created return [0.0 for _ in range(len(cell_coords))] # 2.) Use the coordinates to construct the Delaunay triangulation of all GFP & RFP cells: tri = sp.Delaunay(cell_coords) if show is True: _ = sp.delaunay_plot_2d(tri=tri) plt.xlim(0, 1200) plt.ylim(0, 1600) plt.title("Delaunay Triangulation for Local Density Calculations") plt.xlabel("FiJi Y-axis (pixels)") plt.ylabel("FiJi X-axis (pixels)") plt.show() plt.close() # 3.) Create an array of the length of points: densities = [0 for _ in range(len(tri.points))] # 4.) Calculate the density of each triangle & add to vertex: for vertex_index, vertex_coords in zip(tri.simplices, cell_coords[tri.simplices]): density = self.Return_Partial_Density(a=vertex_coords[0], b=vertex_coords[1], c=vertex_coords[2]) for index in vertex_index: densities[index] += density # 5.) Write these definitive cell densities into the big density array: self.density[cell_map[0][0]:cell_map[0][1]] = np.array( densities, dtype=np.float64) # 6.) Return an intermediate so you can check if correctly calculated: return densities
def DelaunayPlot(tri): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) sp.delaunay_plot_2d(tri, ax)
def draw_word_crowd(self, DRAW_INDEX): #ワードクラウド描画 X_SIZE = int(self.x_max - self.x_min + 400) Y_SIZE = int(self.y_max - self.y_min + 400) adjust_x = self.x_min - 200 adjust_y = self.y_min - 200 campus = Image.new('RGB', (X_SIZE, Y_SIZE), (128, 128, 128)) draw = ImageDraw.Draw(campus) for wrec in self.wrec_list: if wrec.color == "RED": draw.rectangle((wrec.p_tl[0] - adjust_x, \ wrec.p_tl[1] - adjust_y, \ wrec.p_br[0] - adjust_x, \ wrec.p_br[1] - adjust_y), \ fill=(240, 0, 0), outline=(255, 255, 255)) print(wrec.p_tl[0]) if wrec.color == "BLUE": draw.rectangle((wrec.p_tl[0] - adjust_x, \ wrec.p_tl[1] - adjust_y, \ wrec.p_br[0] - adjust_x, \ wrec.p_br[1] - adjust_y), \ fill=(0, 0, 240), outline=(255, 255, 255)) if wrec.color == "PURPLE": draw.rectangle((wrec.p_tl[0] - adjust_x, \ wrec.p_tl[1] - adjust_y, \ wrec.p_br[0] - adjust_x, \ wrec.p_br[1] - adjust_y), \ fill=(150, 0, 150), outline=(255, 255, 255)) if wrec.color == "NO": draw.rectangle((wrec.p_tl[0] - adjust_x, \ wrec.p_tl[1] - adjust_y, \ wrec.p_br[0] - adjust_x, \ wrec.p_br[1] - adjust_y), \ fill=(50, 50, 50), outline=(255, 255, 255)) if wrec.color == "RED" or wrec.color == "BLUE" or wrec.color == "PURPLE" or wrec.color == "NO": ttfontname = "./logotypejp_mp_m_1.1.ttf" fontsize = wrec.size font = ImageFont.truetype(ttfontname, fontsize) text_position_x = wrec.p_tl[0] - adjust_x text_position_y = wrec.p_tl[1] - adjust_y textRGB = (20, 20, 20) text = wrec.word draw.text((text_position_x, text_position_y), text, fill=textRGB, font=font) if wrec.color == "Thumbnail": url = 'http://i.ytimg.com/vi/' + wrec.word + "/mqdefault.jpg" response = requests.get(url) image = response.content file_name = "Thumbnail/" + wrec.word + ".jpeg" with open(file_name, "wb") as aaa: aaa.write(image) img = Image.open("Thumbnail/" + wrec.word + ".jpeg") img_resize = img.resize( (int((wrec.p_br[0] - wrec.p_bl[0]) / 2), int((wrec.p_bl[1] - wrec.p_tl[1]) / 2)) ) campus.paste(img_resize, (int(wrec.p_c[0]), int(wrec.p_c[1])) ) campus.save('./Images/pillow_imagedraw.jpg', quality=95) tri_2 = Delaunay(self.word_positions_in_pic) fig_2 = delaunay_plot_2d(tri_2) fig_2.savefig('./Images/scipy_matplotlib_delaunay_after.png')
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None): """ A utility for plotting (m,2) zonotopes with associated designs and quadrature rules. :param ndarray vertices: M-by-2 matrix that contains the vertices that define the zonotope. :param ndarray design: N-by-2 matrix that contains a design-of-experiments on the zonotope. The plot will contain the Delaunay triangulation of the points in `design` and `vertices`. :param ndarray y: K-by-2 matrix that contains points to be plotted inside the zonotope. If `y` is given, then `f` must be given, too. :param ndarray f: K-by-1 matrix that contains a color value for the associated points in `y`. This is useful for plotting function values or quadrature rules with the zonotope. If `f` is given, then `y` must be given, too. :param str out_label: A label for the quantity of interest. :param dict opts: A dictionary with some plot options. **Notes** This function makes use of the scipy.spatial routines for plotting the zonotopes. """ if opts == None: opts = plot_opts() # set labels for plots if out_label is None: out_label = 'Output' if vertices.shape[1] != 2: raise Exception('Zonotope vertices should be 2d.') if design is not None: if design.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if y is not None: if y.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if (y is not None and f is None) or (y is None and f is not None): raise Exception('You need both y and f to plot.') if y is not None and f is not None: if y.shape[0] != f.shape[0]: raise Exception('Lengths of y and f are not the same.') # get the xlim and ylim xmin, xmax = np.amin(vertices), np.amax(vertices) # make the Polygon patch for the zonotope ch = ConvexHull(vertices) # make the Delaunay triangulation if design is not None: points = np.vstack((design, vertices)) dtri = Delaunay(points) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111) fig0 = convex_hull_plot_2d(ch, ax=ax) for l in fig0.axes[0].get_children(): if type(l) is Line2D: l.set_linewidth(3) if design is not None: fig1 = delaunay_plot_2d(dtri, ax=ax) for l in fig1.axes[0].get_children(): if type(l) is Line2D: l.set_color('0.75') if y is not None: plt.scatter(y[:,0], y[:,1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f)) plt.axes().set_aspect('equal') plt.title(out_label) plt.colorbar() plt.axis([1.1*xmin,1.1*xmax,1.1*xmin,1.1*xmax]) plt.xlabel('Active variable 1') plt.ylabel('Active variable 2') show_plot(plt) if opts['savefigs']: figname = 'figs/zonotope_2d_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)
import matplotlib.pyplot as plt from matplotlib.patches import Ellipse from scipy.spatial import Voronoi, voronoi_plot_2d from scipy.spatial import Delaunay, delaunay_plot_2d #%% Delaunay and Voronoi fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') np.random.seed(3) x, y = np.mgrid[0:1:10j, 0:1:10j] x[:, 1::2] = x[:, 1::2] + 0.05 x.shape = (100, 1) y.shape = (100, 1) pts = np.hstack([x, y]) + 0.02*np.random.normal(size=(100, 2)) vor = Voronoi(pts) voronoi_plot_2d(vor, ax=ax) tri = Delaunay(pts) delaunay_plot_2d(tri, ax=ax) scal = 0.9 for triang in tri.simplices: A = triang[0] B = triang[1] C = triang[2] vertices = np.array([pts[A], pts[B], pts[C]]) centroid, semi_minor, semi_major, ang = steiner_inellipse(vertices) ellipse = Ellipse(centroid, 2*scal*semi_major, 2*scal*semi_minor, angle=ang, facecolor="red", alpha=0.4) ax.add_artist(ellipse) plt.show()
for x, y in zip(x_coords, y_coords): cells.append([x, y]) else: raise ValueError( "Length of 'x-coords' and 'y-coords' vectors are not identical.") cells = tuple(cells) print(cells) areas = [0 for _ in range(len(cells))] print(areas) # Now calculate their densities - unit test: points = np.array(cells) print(points) tri = sp.Delaunay(points) fig = sp.delaunay_plot_2d(tri=tri) plt.title( "Unit Test - Local Density Analysis\n'MDCK_90WT_10Sc_NoComp', '17_07_24', 'pos0', slice #552" ) plt.show() print(tri.points) print("Uno") print(tri.simplices) print("Dos") print(points[tri.simplices]) print("Tres") triangles_all = points[tri.simplices] print("Total # of triangles: {}".format(len(triangles_all)))
def plot_web(): spat.delaunay_plot_2d(delaun) plt.show()
# # We then create two test points (grid 0 & grid 1) at which we want to # estimate a value using natural neighbor interpolation. # # The locations of these observations are then used to generate a Delaunay triangulation. np.random.seed(100) pts = np.random.randint(0, 100, (10, 2)) xp = pts[:, 0] yp = pts[:, 1] zp = (pts[:, 0] * pts[:, 0]) / 1000 tri = Delaunay(pts) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) delaunay_plot_2d(tri, ax=ax) for i, zval in enumerate(zp): ax.annotate('{} F'.format(zval), xy=(pts[i, 0] + 2, pts[i, 1])) sim_gridx = [30., 60.] sim_gridy = [30., 60.] ax.plot(sim_gridx, sim_gridy, '+', markersize=10) ax.set_aspect('equal', 'datalim') ax.set_title('Triangulation of observations and test grid cell ' 'natural neighbor interpolation values') members, tri_info = geometry.find_natural_neighbors( tri, list(zip(sim_gridx, sim_gridy)))
def hexagon_plot(self, *, tri=False): voronoi_plot_2d(self.Voronoi, ax) if tri: delaunay_plot_2d(self.Delaunay, ax) plt.xlim(self.xrange) plt.ylim(self.yrange)
def draw_word_crowd(self, DRAW_INDEX, X_SIZE, Y_SIZE): campus = Image.new('RGB', (X_SIZE, Y_SIZE), (128, 128, 128)) position_scale_rate = X_SIZE / 2 * (self.x_max + 0.5) draw = ImageDraw.Draw(campus) # 一回 DRAW_INDEX のt_elementに対して、描画してみる。 for i, word in zip(range(len(self.elements_list[DRAW_INDEX].extracted_w_info_dict)), \ self.elements_list[DRAW_INDEX].extracted_w_info_dict\ ): x = self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].position[0] y = self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].position[1] size = self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].frequency size = int(math.log(size, 1.5) * 5) ### ここ考えよ ttfontname = "./logotypejp_mp_m_1.1.ttf" fontsize = size text = word textRGB = (0, 0, 0) font = ImageFont.truetype(ttfontname, fontsize) textWidth, textHeight = draw.textsize(text, font=font) X_center = X_SIZE / 2 + position_scale_rate * x Y_center = Y_SIZE / 2 + position_scale_rate * y if self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].color == "RED": draw.rectangle((X_center - (textWidth / 2), \ Y_center - (textHeight / 2), \ X_center + (textWidth / 2), \ Y_center + (textHeight / 2)),\ fill=(240, 0, 0), outline=(255, 255, 255) ) if self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].color == "BLUE": draw.rectangle((X_center - (textWidth / 2), \ Y_center - (textHeight / 2), \ X_center + (textWidth / 2), \ Y_center + (textHeight / 2)),\ fill=(0, 0, 240), outline=(255, 255, 255)) if self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].color == "PURPLE": draw.rectangle((X_center - (textWidth / 2), \ Y_center - (textHeight / 2), \ X_center + (textWidth / 2), \ Y_center + (textHeight / 2)),\ fill=(150, 0, 150), outline=(255, 255, 255)) if self.elements_list[DRAW_INDEX].extracted_w_info_dict[ word].color == "NO": draw.rectangle((X_center - (textWidth / 2), \ Y_center - (textHeight / 2), \ X_center + (textWidth / 2), \ Y_center + (textHeight / 2)),\ fill=(50, 50, 50), outline=(255, 255, 255)) text_position_x = X_center - (textWidth / 2) text_position_y = Y_center - (textHeight / 2) font = ImageFont.truetype(ttfontname, fontsize) textWidth, textHeight = draw.textsize(text, font=font) draw.text((text_position_x, text_position_y), text, fill=textRGB, font=font) if i == 0: word_positions_in_pic = np.array([[X_center, Y_center]]) # 別作業するためのDFを作らせてください。↓↓ # tmp_dfの一行 = [word, p_c_x, p_c_y, p_tl_x, p_tl_y, p_tr_x, p_tl_y, p_bl_x, p_bl_y, p_br_x, p_br_y, size, color] ''' p_tl --------- p_tr | | | p_c | <- size (= frequency = importance) | | p_bl ----------p_br ''' tmp_df = pd.DataFrame(\ [[word,\ X_center,\ Y_center,\ X_center - (textWidth / 2),\ Y_center - (textHeight / 2),\ X_center + (textWidth / 2),\ Y_center - (textHeight / 2),\ X_center - (textWidth / 2),\ Y_center + (textHeight / 2),\ X_center + (textWidth / 2),\ Y_center + (textHeight / 2),\ size,\ self.elements_list[DRAW_INDEX].extracted_w_info_dict[word].color\ ]]\ ) tmp_df.columns = [ 'word', 'p_c_x', 'p_c_y', 'p_tl_x', 'p_tl_y', 'p_tr_x', 'p_tr_y', 'p_bl_x', 'p_bl_y', 'p_br_x', 'p_br_y', 'size', 'color' ] if i > 0: a_2d_ex = np.array([[X_center, Y_center]]) word_positions_in_pic = np.append(word_positions_in_pic, a_2d_ex, axis=0) # 別作業するためのDFを作らせてください。↓↓ tmp_df = tmp_df.append({'word' : word,\ 'p_c_x' : X_center,\ 'p_c_y' : Y_center,\ 'p_tl_x' : X_center - (textWidth / 2),\ 'p_tl_y' : Y_center - (textHeight / 2),\ 'p_tr_x' : X_center + (textWidth / 2),\ 'p_tr_y' : Y_center - (textHeight / 2),\ 'p_bl_x' : X_center - (textWidth / 2),\ 'p_bl_y' : Y_center + (textHeight / 2),\ 'p_br_x' : X_center + (textWidth / 2),\ 'p_br_y' : Y_center + (textHeight / 2),\ 'size' : size,\ 'color' : self.elements_list[DRAW_INDEX].extracted_w_info_dict[word].color\ } , ignore_index=True) print(tmp_df) SAVE_PATH = './CSVs/positions_corners_size_csv_out' + '_' + str( DRAW_INDEX) + '.csv' tmp_df.to_csv(SAVE_PATH, index=False) #campus.save('./Images/pillow_imagedraw.jpg', quality=95) ← もう画像を残す必要が無くなったからここはコメントアウト #print(self.elements_list[DRAW_INDEX].word_count_dict) #print(word_positions_in_pic) #ドロネー三角分割 tri = Delaunay(word_positions_in_pic) fig = delaunay_plot_2d(tri)
# observation values are just the x coordinate value times the y coordinate # value divided by 1000. # # We then create two test points (grid 0 & grid 1) at which we want to # estimate a value using natural neighbor interpolation. # # The locations of these observations are then used to generate a Delaunay triangulation. np.random.seed(100) pts = np.random.randint(0, 100, (10, 2)) xp = pts[:, 0] yp = pts[:, 1] zp = (pts[:, 0] * pts[:, 0]) / 1000 tri = Delaunay(pts) delaunay_plot_2d(tri) for i, zval in enumerate(zp): plt.annotate('{} F'.format(zval), xy=(pts[i, 0] + 2, pts[i, 1])) sim_gridx = [30., 60.] sim_gridy = [30., 60.] plt.plot(sim_gridx, sim_gridy, '+', markersize=10) plt.axes().set_aspect('equal', 'datalim') plt.title('Triangulation of observations and test grid cell ' 'natural neighbor interpolation values') members, tri_info = triangles.find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy))) val = nn_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0], tri_info)
# -*- coding: utf-8 -*- """ Super quick Delaunay test """ import numpy as np import matplotlib.pyplot as plt import scipy.spatial as sp # Read Velocity files data = loadtxt('PZFlex2d.csv', delimiter=',', dtype='float32') # Read positional data X = data[:,0] Y = data[:,1] Xv = data[:,2] Yv = data[:,3] points = np.array([data[:,0],data[:,1]]) points = points.T s=10 figure() tri = sp.Delaunay(points) sp.delaunay_plot_2d(tri) figure() vor = sp.Voronoi(points) sp.voronoi_plot_2d(vor)
def force_model(self, DRAW_INDEX): # まず同じ値のものはちょっとずらず for wrec_1 in self.wrec_list: for wrec_2 in self.wrec_list: if wrec_1 == wrec_2: continue if int(wrec_1.p_c[0]) == int(wrec_2.p_c[0]) and int(wrec_1.p_c[1]) == int(wrec_2.p_c[1]): random_vec = np.array([(0.5 - random.random())*25, (0.5 - random.random())*25]) #とりあえず15なだけ wrec_1.p_c = wrec_1.p_c + random_vec print("come") # word_positions_in_pic は wrec_set.wrec_list のINDEX順番と同じ。 for i, wrec in zip( range(len(self.wrec_list)), self.wrec_list): if i == 0: word_positions_in_pic = np.array([[wrec.p_c[0], wrec.p_c[1]]]) if i > 0: a_2d_ex = np.array([[wrec.p_c[0], wrec.p_c[1]]]) word_positions_in_pic = np.append(word_positions_in_pic, a_2d_ex, axis=0) #print(word_positions_in_pic) tri = Delaunay(word_positions_in_pic) fig = delaunay_plot_2d(tri) # fig.savefig('./Images/scipy_matplotlib_delaunay_before.png') print(tri.simplices) for mesh in tri.simplices: if mesh[0] == self.wrec_list[mesh[0]].index_num:# 一応一致しているかを確認 self.wrec_list[mesh[0]].conneced_wrec_dict[mesh[1]] = self.wrec_list[mesh[1]] self.wrec_list[mesh[0]].conneced_wrec_dict[mesh[2]] = self.wrec_list[mesh[2]] self.wrec_list[mesh[1]].conneced_wrec_dict[mesh[0]] = self.wrec_list[mesh[0]] self.wrec_list[mesh[1]].conneced_wrec_dict[mesh[2]] = self.wrec_list[mesh[2]] self.wrec_list[mesh[2]].conneced_wrec_dict[mesh[0]] = self.wrec_list[mesh[0]] self.wrec_list[mesh[2]].conneced_wrec_dict[mesh[1]] = self.wrec_list[mesh[1]] self.wrec_list[mesh[0]].belonged_mesh.append(mesh) self.wrec_list[mesh[1]].belonged_mesh.append(mesh) self.wrec_list[mesh[2]].belonged_mesh.append(mesh) # 力を計算する i = 0 while i < HOW_MANY_MOVES: for wrec in self.wrec_list: wrec.calculate_fs() wrec.calculate_fr() wrec.calculate_all_f() self.move() #ここで、移動後次回のfaは計算ずみ。 i += 1 # word_positions_in_pic は wrec_set.wrec_list のINDEX順番と同じ。 for i, wrec in zip( range(len(self.wrec_list)), self.wrec_list): if i == 0: word_positions_in_pic = np.array([[wrec.p_c[0], wrec.p_c[1]]]) if i > 0: a_2d_ex = np.array([[wrec.p_c[0], wrec.p_c[1]]]) word_positions_in_pic = np.append(word_positions_in_pic, a_2d_ex, axis=0) print(word_positions_in_pic) self.x_max = np.max(word_positions_in_pic, axis = 0)[0] self.y_max = np.max(word_positions_in_pic, axis = 0)[1] self.x_min = np.min(word_positions_in_pic, axis = 0)[0] self.y_min = np.min(word_positions_in_pic, axis = 0)[1] self.word_positions_in_pic = word_positions_in_pic # 描画様にデータをcsvで排出 i = 0 for wrec in self.wrec_list: if i == 0: tmp_df = pd.DataFrame(\ [[wrec.word,\ wrec.p_c[0],\ wrec.p_c[1],\ wrec.p_tl[0],\ wrec.p_tl[1],\ wrec.p_tr[0],\ wrec.p_tr[1],\ wrec.p_bl[0],\ wrec.p_bl[1],\ wrec.p_br[0],\ wrec.p_br[1],\ wrec.size,\ wrec.color\ ]]\ ) tmp_df.columns = ['word', 'p_c_x', 'p_c_y', 'p_tl_x', 'p_tl_y', 'p_tr_x', 'p_tr_y', 'p_bl_x', 'p_bl_y', 'p_br_x', 'p_br_y', 'size', 'color'] if i > 0: tmp_df = tmp_df.append({'word' : wrec.word,\ 'p_c_x' : wrec.p_c[0],\ 'p_c_y' : wrec.p_c[1],\ 'p_tl_x' : wrec.p_tl[0],\ 'p_tl_y' : wrec.p_tl[1],\ 'p_tr_x' : wrec.p_tr[0],\ 'p_tr_y' : wrec.p_tr[1],\ 'p_bl_x' : wrec.p_bl[0],\ 'p_bl_y' : wrec.p_bl[1],\ 'p_br_x' : wrec.p_br[0],\ 'p_br_y' : wrec.p_br[1],\ 'size' : wrec.size,\ 'color' : wrec.color\ } , ignore_index=True) i = i+1 SAVE_PATH = './Bokeh/CSVs/afrer_forced_output_' + str(DRAW_INDEX) + '.csv' tmp_df.to_csv(SAVE_PATH, index=False)
def DelaunayPlot(tri): sp.delaunay_plot_2d(tri)
def d_plot(tri): """delaunay plots, requires new points and simplices See : matplotlib.pyplot.triplot ... for additional options""" # import matplotlib.pyplot as plt delaunay_plot_2d(tri)
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 16:00:31 2020 @author: wegia """ import numpy as np points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]) from scipy.spatial import Voronoi, voronoi_plot_2d vor = Voronoi(points) import matplotlib.pyplot as plt fig = voronoi_plot_2d(vor) plt.show() import numpy as np import matplotlib.pyplot as plt from scipy.spatial import Delaunay, delaunay_plot_2d, tsearch pts = np.random.rand(20, 2) tri = Delaunay(pts) _ = delaunay_plot_2d(tri) loc = np.random.uniform(0.2, 0.8, (5, 2)) s = tsearch(tri, loc) plt.triplot(pts[:, 0], pts[:, 1], tri.simplices[s], 'b-', mask=s == -1) plt.scatter(loc[:, 0], loc[:, 1], c='r', marker='x') plt.show()
m = 90 shape = 'F' # Create mesh and triangulation points, bound, tri = trimesh(shape, n, m, 'basic') print('Number of points in mesh:', len(points)) tri = sp.Delaunay(points) fig, ax = plt.subplots(1) ax.set_aspect('equal') ax.set_title(fr'Procedure-generated Mesh for the {shape}') ax.set_xlabel(r'$x$ coordinate') ax.set_ylabel(r'$y$ coordinate') sp.delaunay_plot_2d(tri, ax=ax) #plt.savefig('images/proc_mesh.png') plt.show() # Solve for flow profile w, v = solve_eigs(points, bound, tri.simplices) print('Some eigenvalues:', (w[:10])) #mns = [[1,1], [2,1], [3,1], [1,2], [4,1], [2,2], [5,1], [3,2], [6,1], [1,3]] # Draw profiles for i in range(10): draw_profile(points, tri, v[:, i], shape, w[i], 'contourf', savefig=True) ''' sol = v[:,i]
# [195 359] # [ 9 211] # [277 242]] print(type(pts)) # <class 'numpy.ndarray'> print(pts.shape) # (6, 2) tri = Delaunay(pts) print(type(tri)) # <class 'scipy.spatial.qhull.Delaunay'> fig = delaunay_plot_2d(tri) fig.savefig('data/dst/scipy_matplotlib_delaunay.png') plt.close() # ![data/dst/scipy_matplotlib_delaunay.png](data/dst/scipy_matplotlib_delaunay.png) print(tri.points) # [[172. 47.] # [117. 192.] # [323. 251.] # [195. 359.] # [ 9. 211.] # [277. 242.]] print(tri.points == pts) # [[ True True]
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None): if opts == None: opts = plot_opts() # set labels for plots if out_label is None: out_label = 'Output' if vertices.shape[1] != 2: raise Exception('Zonotope vertices should be 2d.') if design is not None: if design.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if y is not None: if y.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if (y is not None and f is None) or (y is None and f is not None): raise Exception('You need both y and f to plot.') if y is not None and f is not None: if y.shape[0] != f.shape[0]: raise Exception('Lengths of y and f are not the same.') # get the xlim and ylim xmin, xmax = np.amin(vertices), np.amax(vertices) # make the Polygon patch for the zonotope ch = ConvexHull(vertices) # make the Delaunay triangulation if design is not None: points = np.vstack((design, vertices)) dtri = Delaunay(points) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111) convex_hull_plot_2d(ch, ax=ax) if design is not None: fig = delaunay_plot_2d(dtri, ax=ax) for l in fig.axes[0].get_children(): if type(l) is Line2D: l.set_color('0.75') if y is not None: plt.scatter(y[:,0], y[:,1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f)) plt.axes().set_aspect('equal') plt.title(out_label) plt.colorbar() plt.axis([1.1*xmin,1.1*xmax,1.1*xmin,1.1*xmax]) plt.xlabel('Active variable 1') plt.ylabel('Active variable 2') plt.show() if opts['savefigs']: figname = 'figs/zonotope_2d_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None): """A utility for plotting (m,2) zonotopes with designs and quadrature rules. Parameters ---------- vertices : ndarray M-by-2 matrix that contains the vertices that define the zonotope design : ndarray, optional N-by-2 matrix that contains a design-of-experiments on the zonotope. The plot will contain the Delaunay triangulation of the points in `design` and `vertices`. (default None) y : ndarray, optional K-by-2 matrix that contains points to be plotted inside the zonotope. If `y` is given, then `f` must be given, too. (default None) f: ndarray, optional K-by-1 matrix that contains a color value for the associated points in `y`. This is useful for plotting function values or quadrature rules with the zonotope. If `f` is given, then `y` must be given, too. (default None) out_label : str, optional a label for the quantity of interest (default None) opts : dict, optional a dictionary with some plot options (default None) Notes ----- This function makes use of the scipy.spatial routines for plotting the zonotopes. """ if opts == None: opts = plot_opts() # set labels for plots if out_label is None: out_label = 'Output' if vertices.shape[1] != 2: raise Exception('Zonotope vertices should be 2d.') if design is not None: if design.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if y is not None: if y.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if (y is not None and f is None) or (y is None and f is not None): raise Exception('You need both y and f to plot.') if y is not None and f is not None: if y.shape[0] != f.shape[0]: raise Exception('Lengths of y and f are not the same.') # get the xlim and ylim xmin, xmax = np.amin(vertices), np.amax(vertices) # make the Polygon patch for the zonotope ch = ConvexHull(vertices) # make the Delaunay triangulation if design is not None: points = np.vstack((design, vertices)) dtri = Delaunay(points) fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) fig0 = convex_hull_plot_2d(ch, ax=ax) for l in fig0.axes[0].get_children(): if type(l) is Line2D: l.set_linewidth(3) if design is not None: fig1 = delaunay_plot_2d(dtri, ax=ax) for l in fig1.axes[0].get_children(): if type(l) is Line2D: et_color('0.75') if y is not None: plt.scatter(y[:, 0], y[:, 1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f)) plt.axes().set_aspect('equal') plt.title(out_label) plt.colorbar() plt.axis([1.1 * xmin, 1.1 * xmax, 1.1 * xmin, 1.1 * xmax]) plt.xlabel('Active variable 1') plt.ylabel('Active variable 2') show_plot(plt) if opts['savefigs']: figname = 'figs/zonotope_2d_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)