def plot_approach_angles(x, y, tris, under_wheels, body_lines, approach_lines, track_points, track_outline, wheel_geom): """ Plot approach angles and a bounding box around the vehicle. """ plt.subplot2grid((3, 2), (0, 0)) plt.subplot(1, 1, 1) rcParams['figure.figsize'] = 50, 50 plt.gca().set_aspect('equal') plt.gca().grid(True) ## Plot body of the vehicle triangulation = Triangulation(x, y, tris) plt.triplot(triangulation, linewidth=0.5, alpha=0.7) ## Plot wheels if wheel_geom: wheel_triangulation = Triangulation(wheel_geom["z"], wheel_geom["y"], wheel_geom["tris"]) plt.triplot(wheel_triangulation, linewidth=0.5, alpha=0.7) ## Plot Tracks if track_outline != 0: plot_tracks(track_points, track_outline) ## plot under_wheel lines for line in under_wheels: plt.plot(line[0], line[1], "m", linewidth=4, alpha=0.2) ## plot approach_lines for a_line in approach_lines: plt.plot(a_line[0], a_line[1], "g", linewidth=4, alpha=0.2) ## plot body lines for b_line in body_lines: plt.plot(b_line[0], b_line[1], "r", linewidth=4, alpha=0.2) plt.suptitle("Approach angles", horizontalalignment='right', verticalalignment='top') img_file_name = "Approach_angles.png" current_dir = os.getcwd() logging.info( "Plotting approach angles: writing image to file {} in {}.".format( img_file_name, current_dir)) plt.savefig(img_file_name, dpi=100) logging.info("Finished plotting approach angles") plt.clf()
def multiview(data, suptitle='', figsize=(15, 10), **kwds): cs = cortex vtx = cs.vertices tri = cs.triangles rm = cs.region_mapping x, y, z = vtx.T lh_tri = tri[(rm[tri] < 38).any(axis=1)] lh_vtx = vtx[rm < 38] lh_x, lh_y, lh_z = lh_vtx.T lh_tx, lh_ty, lh_tz = lh_vtx[lh_tri].mean(axis=1).T rh_tri = tri[(rm[tri] >= 38).any(axis=1)] rh_vtx = vtx[rm < 38] rh_x, rh_y, rh_z = rh_vtx.T rh_tx, rh_ty, rh_tz = vtx[rh_tri].mean(axis=1).T tx, ty, tz = vtx[tri].mean(axis=1).T views = { 'lh-lateral': Triangulation(-x, z, lh_tri[argsort(lh_ty)[::-1]]), 'lh-medial': Triangulation(x, z, lh_tri[argsort(lh_ty)]), 'rh-medial': Triangulation(-x, z, rh_tri[argsort(rh_ty)[::-1]]), 'rh-lateral': Triangulation(x, z, rh_tri[argsort(rh_ty)]), 'both-superior': Triangulation(y, x, tri[argsort(tz)]), } def plotview(i, j, k, viewkey, z=None, zlim=None, zthresh=None, suptitle='', shaded=True, cmap=plt.cm.coolwarm, viewlabel=False): v = views[viewkey] ax = subplot(i, j, k) if z is None: z = rand(v.x.shape[0]) if not viewlabel: axis('off') kwargs = {'shading': 'gouraud'} if shaded else {'edgecolors': 'k', 'linewidth': 0.1} if zthresh: z = z.copy() * (abs(z) > zthresh) tc = ax.tripcolor(v, z, cmap=cmap, **kwargs) if zlim: tc.set_clim(vmin=-zlim, vmax=zlim) ax.set_aspect('equal') if suptitle: ax.set_title(suptitle, fontsize=24) if viewlabel: xlabel(viewkey) figure(figsize=figsize) plotview(2, 3, 1, 'lh-lateral', data, **kwds) plotview(2, 3, 4, 'lh-medial', data, **kwds) plotview(2, 3, 3, 'rh-lateral', data, **kwds) plotview(2, 3, 6, 'rh-medial', data, **kwds) plotview(1, 3, 2, 'both-superior', data, suptitle=suptitle, **kwds) subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0, hspace=0)
def mesh_tri(grid_file): ncmesh = Dataset(grid_file,'r') lon_mesh = np.rad2deg(ncmesh.variables['lonCell'][:])-360.0 #lon_mesh = np.rad2deg(np.mod(ncmesh.variables['lonCell'][:] + np.pi, 2.0*np.pi) - np.pi) lat_mesh = np.rad2deg(ncmesh.variables['latCell'][:]) nEdgesOnCell = ncmesh.variables['nEdgesOnCell'][:] cellsOnCell = ncmesh.variables['cellsOnCell'][:,:] # Triangulate cells triangles = Triangulation(lon_mesh,lat_mesh) # Compute triangulation mask (needs to be vectorized) mask = np.array(np.zeros((triangles.triangles.shape[0],)),dtype=bool) ntri = triangles.neighbors.shape[0] for i in range(ntri): k = 0 for j in range(3): n = triangles.triangles[i,j] if nEdgesOnCell[n] != np.where(cellsOnCell[n,:] != 0)[0].size: # Mask triangles k = k +1 # containing if k == 3: # 3 boundary mask[i] = True # cells triangles.set_mask(mask) return triangles
def PlotPoly(self): for i in range(0,len(self.poly)): if i < len(self.poly)-1: X = np.vstack((self.poly[i],self.poly[i+1])) else: X = self.poly[i] X = np.vstack((X[:,0],X[:,1],X[:,3])).T hull = ConvexHull(X,qhull_options=self.qhull_options) x,y,z=X.T tri = Triangulation(x, y, triangles=hull.simplices) triangle_vertices = np.array([np.array([[x[T[0]], y[T[0]], z[T[0]]], [x[T[1]], y[T[1]], z[T[1]]], [x[T[2]], y[T[2]], z[T[2]]]]) for T in tri.triangles]) self.tri = tri tri = Poly3DCollection(triangle_vertices) if i == len(self.poly)-1: tri.set_color(self.COLOR_REACHABLE_SET_LAST) tri.set_edgecolor(self.rs_last_edge_color) #self.image.scatter(x,y,z, 'ok', color=np.array((0,0,1.0,0.1)),s=30) else: color_cur = copy.copy(self.COLOR_REACHABLE_SET_LAST) color_cur[3] = color_cur[3]/2.0 tri.set_color(color_cur) tri.set_edgecolor('None') self.image.add_collection3d(tri)
def make_graph_triangulation(self): x = [self.p[i].x for i in range(self.n_nodes)] y = [self.p[i].y for i in range(self.n_nodes)] self.T = Triangulation(x, y) self.G = nx.Graph() self.G.add_edges_from(self.T.edges) self.boundary_check2(list(self.G.nodes()))
def ploteigenvectors(kle, filename): mesh = kle.mesh l = kle.l v = kle.v #plot eigenvectors eigvec = True if eigvec: eign = [0,2,4,6,9,11,17,19] from matplotlib.tri import Triangulation #vmin = np.min(v[:,eign]) #vmax = np.max(v[:,eign]) pts = kle.mesh.coordinates() tri = Triangulation(pts[:,0], pts[:,1], triangles = mesh.cells()) fig, axes = plt.subplots(nrows = 2, ncols = 4) for ax, i in zip(axes.flat,eign): im = ax.tripcolor(tri, v[:,i].flatten(), shading = 'gouraud', cmap = plt.cm.rainbow) # vmin = vmin, vmax = vmax, ax.set_xticks([]) ax.set_yticks([]) fig.suptitle('Eigenvectors of KLE', fontsize = 20) #fig.subplots_adjust(right = 0.8) #cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) #fig.colorbar(im, cax = cbar_ax) plt.savefig('figs/' + filename + '.png') plt.show() return
def plot_trisurf(data, out=None, ax=None, angles=None): if ax is None: fig = plt.figure() ax = fig.gca(projection='3d') Xs, Ys = np.meshgrid(data.coords[data.dims[0]].values, data.coords[data.dims[1]].values) triang = Triangulation(Xs.ravel(), Ys.ravel()) mask = np.any(np.isnan(data.transpose().values.ravel()[triang.triangles]), axis=1) triang.set_mask(mask) values = data.copy(deep=True).transpose().values values[np.isnan(values)] = 0 ax.plot_trisurf(triang, values.ravel(), antialiased=True, cmap=cm.coolwarm, linewidth=0) if angles is not None: ax.view_init(*angles) #plt.show() return ax
def sample_mesh(sample, param=100): """Provides sample meshes. Parameters ---------- sample : int Integer, giving the sample mesh to be considered. Possibilities: param : Parameters to the sample meshes. Possibilities: Returns ------- nodes : ndarray 2D numpy array with 2 columns, each row corresponding to a vertex, and the two columns giving the Cartesian coordinates of the vertices. cells : ndarray Cell-vertex connectivity in a 2D numpy array, in which each row corresponds to a cell and the columns are the vertices of the cells. It is assumed that all the cells have the same number of vertices. """ if sample == 1: n_vertex = param a, b, c, d = (-1, 1, 1, 2) x_vertices = (b - a) * np.random.rand(n_vertex) + a y_vertices = (d - c) * np.random.rand(n_vertex) + c vertices = np.stack((x_vertices, y_vertices), axis=1) cells = Triangulation(x_vertices, y_vertices).triangles elif sample == 2: vertices = np.array([[]]) cells = np.array([[]]) else: raise ValueError('Sample not available.') return vertices, cells
def plot(self, mpl_ax, levels=50, lw=0.3, mesh_alpha=0, mesh_lw=0.2): """ Plot the function on a matplotlib axes. Call .compute() first to calculate the stream function """ if self._triangulation is None: from matplotlib.tri import Triangulation coords = self.mesh.coordinates() triangles = [] for cell in df.cells(self.mesh): cell_vertices = cell.entities(0) triangles.append(cell_vertices) self._triangulation = Triangulation(coords[:, 0], coords[:, 1], triangles) if mesh_alpha > 0: mpl_ax.triplot(self._triangulation, color='#000000', alpha=mesh_alpha, lw=mesh_lw) Z = self.psi.compute_vertex_values() if all(Z == 0): return mpl_ax.tricontour( self._triangulation, Z, levels, colors='#0000AA', linewidths=lw, linestyles='solid', )
def plot(self, variable, show=False, index=None): if index is None: self.animation( variable, # show=True, save='/home/jreniel/pyschism/examples/example_1/test.gif', vmin=0, vmax=3, # start_frame=200, # end_frame=300, ) else: var = self.nc[variable] ugrid = UGrid.from_nc_dataset(self.nc) x = ugrid.nodes[:, 0] y = ugrid.nodes[:, 1] triangulation = Triangulation(x, y, ugrid.faces[:, :3]) triangulation.set_mask(self.nc['wetdry_elem'][index]) plt.tricontourf(triangulation, var[index, :], levels=256, cmap='jet') plt.gca().axis('scaled') if show: plt.show()
def delunaySurface(R, θ, φ): # surface x = np.ravel(R * np.sin(θ) * np.cos(φ)) y = np.ravel(R * np.sin(θ) * np.sin(φ)) z = np.ravel(R * np.cos(θ)) # delunay triangulation return x, y, z, Triangulation(np.ravel(θ), np.ravel(φ))
def getMesh2D(self, points: List[aecPoint]) -> mesh2D: """ Constructs a compact 2D mesh representation of a horizontal surface as a list of unique points and triangle indices. Returns None on failure. """ try: bndPoints = [point.xyz for point in points] boundary = shapely.polygon.orient(shapely.Polygon(bndPoints)) xPoints = [point.x for point in points] yPoints = [point.y for point in points] meshD = Triangulation(xPoints, yPoints) triangles = meshD.triangles indices = [] for item in triangles: triPoints = \ [ points[item[0]].xyz, points[item[1]].xyz, points[item[2]].xyz, ] triangle = shapely.polygon.orient(shapely.Polygon(triPoints)) tstPoint = triangle.representative_point() if boundary.contains(tstPoint): indices.append( tuple([int(element) for element in list(item)])) mesh = self.mesh2D mesh.vertices = [pnt.xyz for pnt in points] mesh.indices = indices return mesh except Exception: traceback.print_exc() return None
def plot_dp(storm, datafile1, datafile2=None): #Single file netCDF reading ncf=datafile1 nco=netCDF4.Dataset(ncf) #Get fields to plot lon=nco.variables['longitude'][:] lat=nco.variables['latitude'][:] timeindays=nco.variables['time'][:] dp=nco.variables['dp'][:] triangles=nco.variables['tri'][:,:] reflon=np.linspace(lon.min(),lon.max(),1000) reflat=np.linspace(lat.min(),lat.max(),1000) #reflon=np.linspace(-80.40, -74.75, 1000) #reflat=np.linspace(32.50, 36.60, 1000) #reflon=np.linspace(-75.70, -71.05, 1000) #reflat=np.linspace(38.50, 41.40, 1000) reflon,reflat=np.meshgrid(reflon,reflat) plt.figure(figsize = [6.4, 3.8]) flatness=0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles=triangles-1 # Correct indices for Python's zero-base tri=Triangulation(lon,lat,triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeindays)): plt.clf() ax = plt.axes(projection=ccrs.Mercator()) dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind]) dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S') dstr = dstr[0:8]+' '+dstr[8:17] print('Plotting '+dstr) par=np.double(dp[ind,:]) tli=LinearTriInterpolator(tri,par) par_interp=tli(reflon,reflat) plt.pcolormesh(reflon,reflat,par_interp,vmin=0.0,vmax=360.0,shading='flat',cmap=plt.cm.jet, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) coast = cfeature.GSHHSFeature(scale='high',edgecolor='black',facecolor='none',linewidth=0.25) ax.add_feature(coast) plt.xticks(fontsize=9) plt.yticks(fontsize=9) figtitle = storm.capitalize()+': Peak Dir (deg): '+dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S') dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14] filenm = 'nsem_'+storm+'_dp_'+dtlabel+'.png' plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.1) del(par) del(par_interp)
def _buildtrig_workaround( self, x, y ): ''' Workaround implemented as qhull fails when called from within QGIS python in ubuntu 17.10, QGIS 3.1 :-( ''' import os import sys import subprocess import tempfile tfh,tfname=tempfile.mkstemp('.npy','tmp_contour_generator') tfh2,tfname2=tempfile.mkstemp('.npy','tmp_contour_generator') os.close(tfh) os.close(tfh2) trig=None try: np.save(tfname,np.vstack((x,y))) pydir=os.path.dirname(os.path.abspath(os.path.realpath(__file__))) pyscript=os.path.join(pydir,'buildtrig_qhull_workaround.py') python=sys.executable result=subprocess.call([python,pyscript,tfname,tfname2]) triangles=np.load(tfname2) trig=Triangulation(x,y,triangles) finally: os.remove(tfname) os.remove(tfname2) return trig
def add_plot(self, axes): points = self.points cells = self.cells tri = Triangulation(points[:, 0], points[:, 1], cells) axes.triplot(tri, 'ko-') axes.set_axis_off() axes.set_aspect('equal')
def visualize_mobius_strip(): theta = np.linspace(0, 2 * np.pi, 30) w = np.linspace(-0.25, 0.25, 8) w, theta = np.meshgrid(w, theta) phi = 0.5 * theta # radius in x-y plane r = 1 + w * np.cos(phi) x = np.ravel(r * np.cos(theta)) y = np.ravel(r * np.sin(theta)) z = np.ravel(w * np.sin(phi)) # triangulate in the underlying parametrization from matplotlib.tri import Triangulation tri = Triangulation(np.ravel(w), np.ravel(theta)) ax = plt.axes(projection='3d') ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap='viridis', linewidths=0.2) ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ax.set_zlim(-1, 1) plt.show()
def show_solution(axes, mesh, u): points = mesh.points cells = mesh.cells tri = Triangulation(points[:, 0], points[:, 1], cells) axes.set_aspect('equal') axes.tricontourf(tri, u) return
def add_unstructured_field(self, x=None, y=None, connectivity=None, tri=None, values=None, transform=None, levels=31, **kwargs): if transform is None: transform = ccrs.PlateCarree() has_xyc = x is not None and y is not None and connectivity is not None has_tri = tri is not None msg = 'either x, y, connectivity or tri arguments must be provided' assert (has_tri and not has_xyc) or (has_xyc and not has_tri), msg assert values is not None, 'values must be provided' kwargs.setdefault('zorder', 2) if not has_tri: tri = Triangulation(x, y, connectivity) p = self.ax.tricontourf(tri, values, levels, transform=transform, **kwargs) return p
def get_edges_slf(ikle, meshx, meshy, showbar=True): """ Returns the list of edges of the mesh @param ikle (np.array) Connectivity table @param meshx (np.array) X coordinates of the mesh points @param meshy (np.array) Y coordinates of the mesh points @param showbar (boolean) If True display a progress bar @returns (list) The list of edges """ try: from matplotlib.tri import Triangulation edges = Triangulation(meshx, meshy, ikle).get_cpp_triangulation()\ .get_edges() except ImportError: edges = [] ibar = 0 if showbar: pbar = ProgressBar(maxval=len(ikle)).start() for elem in ikle: ibar += 1 if showbar: pbar.update(ibar) if [elem[0], elem[1]] not in edges: edges.append([elem[1], elem[0]]) if [elem[1], elem[2]] not in edges: edges.append([elem[2], elem[1]]) if [elem[2], elem[0]] not in edges: edges.append([elem[0], elem[2]]) if showbar: pbar.finish() return edges
def plot_mesh_object(mesh, centers=[[0, 0, 0]]): fig = plt.figure(figsize=(10, 8)) ax = fig.gca(projection='3d') centers = np.array(centers) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) vertices = mesh.assemble() X = vertices[:, :, 0].flatten() Y = vertices[:, :, 1].flatten() Z = vertices[:, :, 2].flatten() triangles = [[3 * ii, 3 * ii + 1, 3 * ii + 2] for ii in range(len(X) / 3)] triang = Triangulation(X, Y, triangles) ax.plot_trisurf(triang, Z, color="white", edgecolor="black", shade=True, alpha=1.0) plt.show()
def select_pairs_delaunay(date_list, tbase_list, pbase_list, norm=True, date12_format='YYMMDD-YYMMDD'): """Select Pairs using Delaunay Triangulation based on temporal/perpendicular baselines Inputs: date_list : list of date in YYMMDD/YYYYMMDD format pbase_list : list of float, perpendicular spatial baseline norm : normalize temporal baseline to perpendicular baseline Key points 1. Define a ratio between perpendicular and temporal baseline axis units (Pepe and Lanari, 2006, TGRS). 2. Pairs with too large perpendicular / temporal baseline or Doppler centroid difference should be removed after this, using a threshold, to avoid strong decorrelations (Zebker and Villasenor, 1992, TGRS). Reference: Pepe, A., and R. Lanari (2006), On the extension of the minimum cost flow algorithm for phase unwrapping of multitemporal differential SAR interferograms, IEEE TGRS, 44(9), 2374-2383. Zebker, H. A., and J. Villasenor (1992), Decorrelation in interferometric radar echoes, IEEE TGRS, 30(5), 950-959. """ # Get temporal baseline in days date6_list = yymmdd(date_list) date8_list = yyyymmdd(date_list) #tbase_list = date_list2tbase(date8_list)[0] # Normalization (Pepe and Lanari, 2006, TGRS) if norm: temp2perp_scale = (max(pbase_list)-min(pbase_list)) / (max(tbase_list)-min(tbase_list)) tbase_list = [tbase*temp2perp_scale for tbase in tbase_list] # Generate Delaunay Triangulation date12_idx_list = Triangulation(tbase_list, pbase_list).edges.tolist() date12_idx_list = [sorted(idx) for idx in sorted(date12_idx_list)] # Convert index into date12 date12_list = [date6_list[idx[0]]+'-'+date6_list[idx[1]] for idx in date12_idx_list] if date12_format == 'YYYYMMDD_YYYYMMDD': date12_list = yyyymmdd_date12(date12_list) return date12_list
def put_edge2(mesh): tri = Triangulation( mesh.vert2['coord'][:, 0], mesh.vert2['coord'][:, 1], mesh.tria3['index']) mesh.edge2 = np.array( [(edge, 0) for edge in tri.edges], dtype=jigsaw_msh_t.EDGE2_t)
def triangulation(grid, level=0): if grid.dimGrid != 2: raise Exception( "Grid must be 2-dimensional for use as matplotlib triangulation.") from matplotlib.tri import Triangulation x, triangles = grid.tesselate(level) return Triangulation(x[:, 0], x[:, 1], triangles)
def _processMesh(self, debug=False): # Generate triangulation print("Processing mesh", self.name) _v = self._v x, y, z = _v[:, 0], _v[:, 1], _v[:, 2] if debug: print(self._info) # Transform to a graph g = nx.Graph() if self.has_surface: _surface = trimesh.Trimesh(vertices=self._v, faces=self._tri) triang = Triangulation(x, y, triangles=self._tri) self._plt_tri = triang self._elev = z _ad = trimesh.graph.face_adjacency(mesh=_surface, return_edges=False) self._adj = _ad _nodes = [] for i, f in enumerate(self._tri): loop = np.asarray([_v[f[0]], _v[f[1]], _v[f[2]]]) _c = np.mean(np.asarray(loop), axis=0) _nodes.append((i, {"vertices": loop, "centroid": _c})) g.add_nodes_from(_nodes) g.add_edges_from(_ad) return g
def plot_trisurfs(ax, verts, faces, change_lims=False, color="darkcyan", zoom=1.5, n_meshes=1, alpha=1.0): """ """ trisurfs = [] for n in range(n_meshes): points = verts[n].cpu().detach().numpy() faces = faces[n].cpu().detach().numpy() X, Y, Z = np.rollaxis(points, -1) tri = Triangulation(X, Y, triangles=faces).triangles trisurf_shade = ax.plot_trisurf(X, Y, Z, triangles=tri, alpha=alpha, color=color, shade=True) # shade entire mesh trisurfs += [trisurf_shade] if change_lims: equal_3d_axes(ax, X, Y, Z, zoom=zoom) return trisurfs
def get_neighbours_slf(ikle, meshx, meshy, showbar=True): """ Return a list containing for each element the list of elements that are neighbours to that element @param ikle (np.array) Connectivity table @param meshx (np.array) X coordinates of the mesh points @param meshy (np.array) Y coordinates of the mesh points @param showbar (boolean) If True display a progress bar @returns (list) The list of neighbours @param """ try: from matplotlib.tri import Triangulation neighbours = Triangulation(meshx, meshy, ikle).get_cpp_triangulation()\ .get_neighbors() except ImportError: insiders = {} bounders = {} ibar = 0 if showbar: pbar = ProgressBar(maxval=(3 * len(ikle))).start() for elem, i in zip(ikle, range(len(ikle))): n_k = bounders.keys() for k in [0, 1, 2]: ibar += 1 if showbar: pbar.update(ibar) if (elem[k], elem[(k + 1) % 3]) not in n_k: bounders.update({(elem[(k + 1) % 3], elem[k]): i}) else: j = bounders[(elem[k], elem[(k + 1) % 3])] insiders.update({(elem[k], elem[(k + 1) % 3]): [i, j]}) del bounders[(elem[k], elem[(k + 1) % 3])] ibar = 0 neighbours = -np.ones((len(ikle), 3), dtype=np.int) for elem, i in zip(ikle, range(len(ikle))): for k in [0, 1, 2]: ibar += 1 if showbar: pbar.update(ibar) if (elem[k], elem[(k + 1) % 3]) in insiders: elem_a, elem_b = insiders[(elem[k], elem[(k + 1) % 3])] if elem_a == i: neighbours[i][k] = elem_b if elem_b == i: neighbours[i][k] = elem_a if (elem[(k + 1) % 3], elem[k]) in insiders: elem_a, elem_b = insiders[(elem[(k + 1) % 3], elem[k])] if elem_a == i: neighbours[i][k] = elem_b if elem_b == i: neighbours[i][k] = elem_a if showbar: pbar.finish() return neighbours
def update_frame(self, n_frame=0): if n_frame + 1 > self.n_frames: return None self.plot.remove() X, Y, Z = zip(*self.vertex_data[n_frame]) tri = Triangulation(X, Y, triangles=self.face_data[n_frame]) self.plot = self.ax.plot_trisurf(X, Y, Z, triangles=tri.triangles, color="gray", **self.trisurf_kwargs)
def mesh_to_tri(mesh): """ mesh is a jigsawpy.jigsaw_msh_t() instance. """ return Triangulation( mesh.vert2['coord'][:, 0], mesh.vert2['coord'][:, 1], mesh.tria3['index'])
def mpl_tri(self): try: return self.__mpl_tri except AttributeError: pass mpl_tri = Triangulation(self.x, self.y) self.__mpl_tri = mpl_tri return self.__mpl_tri
def create_cylinder(m, n, filename='cylinder', plot_pyplot=False, create_dat=True): if m < 4: raise ValueError('4 is min dimension') u = linspace(-1, 1, m + 1, endpoint=True) v = linspace(-1, 1, n, endpoint=True) u, v = meshgrid(u, v) delaunuy = Triangulation(u.flatten(), v.flatten()) COORDS = zeros((m * n + n, 3)) #rad = 2 * np.pi / m #angles = [i * rad for i in range(m)] angles = np.logspace(-1, np.log2(2 * np.pi), num=m, base=2.0) coss = [cos(r) for r in angles] sins = [sin(r) for r in angles] coss.append(coss[0]) sins.append(sins[0]) z = np.linspace(0, 1, num=n, endpoint=True) for j in range(n): for i in range(m + 1): COORDS[i + j * (m + 1), 0] = coss[i % n] COORDS[i + j * (m + 1), 1] = sins[i % n] COORDS[i + j * (m + 1), 2] = z[j] x = COORDS[:, 0] y = COORDS[:, 1] z = COORDS[:, 2] assert len(x) == m * n + n mgrid = Grid() mgrid.set_nodes_and_faces(x, y, z, delaunuy.triangles) set_faces(mgrid, mgrid.Nodes, mgrid.Faces) mgrid.init_adjacent_faces_list_for_border_nodes() if plot_pyplot: fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_trisurf(x, y, z, triangles=delaunuy.triangles) plt.show() if create_dat: if not filename.endswith('.dat'): filename += '.dat' writer.write_tecplot(mgrid, filename) assert len(mgrid.Edges) < 3 * len(mgrid.Nodes) - 3, 'Wrong number of edges' assert len(mgrid.Faces) < 2 * len(mgrid.Nodes) - 2, 'Wrong number of faces' return mgrid