def _connect_cells(self, pdi, pdo, log_time=False): """Internal helper to perfrom the connection""" # NOTE: Type map is specified in vtkCellType.h cell_type = self.__cell_type if log_time: start_time = datetime.now() # Get the Points over the NumPy interface pdi = pyvista.wrap(pdi) points = np.copy( pdi.points) # New NumPy array of poins so we dont destroy input if self.__unique: # Remove repeated points indexes = np.unique(points, return_index=True, axis=0)[1] points = np.array(points[sorted(indexes)]) def _find_min_path(points): try: # sklearn's KDTree is faster: use it if available from sklearn.neighbors import KDTree as Tree except ImportError: from scipy.spatial import cKDTree as Tree _compute_dist = lambda pt0, pt1: np.linalg.norm(pt0 - pt1) ind, min_dist = None, np.inf tree = Tree(points) for pt in points: cur_ind = tree.query([pt], k=len(points))[1].ravel() dist = 0.0 for i in range(len(cur_ind) - 1): dist += _compute_dist(points[cur_ind[i]], points[cur_ind[i + 1]]) if dist < min_dist: ind = cur_ind min_dist = dist return ind.ravel() if self.__usenbr: ind = _find_min_path(points) else: ind = np.arange(len(points), dtype=int) if self.__keep_vertices: poly = pyvista.PolyData(np.copy(points)) else: poly = pyvista.PolyData() poly.points = np.copy(points) if cell_type == vtk.VTK_LINE: lines = np.c_[np.full(len(ind) - 1, 2), ind[0:-1], ind[1:]] if self.__close_loop: app = np.append( lines, [ [2, ind[-1], ind[0]], ], axis=0, ) lines = app poly.lines = lines elif cell_type == vtk.VTK_POLY_LINE: cells = vtk.vtkCellArray() cell = vtk.vtkPolyLine() if self.__close_loop: cell.GetPointIds().SetNumberOfIds(len(ind) + 1) else: cell.GetPointIds().SetNumberOfIds(len(ind)) for i in ind: cell.GetPointIds().SetId(i, ind[i]) if self.__close_loop: cell.GetPointIds().SetId(i + 1, ind[0]) cells.InsertNextCell(cell) poly.SetLines(cells) else: raise _helpers.PVGeoError( 'Cell type ({}) not supported'.format(cell_type)) for key, val in pdi.point_arrays.items(): poly.point_arrays[key] = val pdo.DeepCopy(poly) if log_time: print("exectuted in {}".format(datetime.now() - start_time)) return pdo
def test_angle(): rotate_target() system.update() eng.ray_trace(2) ray_drawer.rays = eng.finished_rays ray_drawer.draw() def whole_distribution(): system.update() ray_drawer.rays = system.sources ray_drawer.draw() whole_distribution() points_only_mesh = pv.PolyData( np.zeros_like(sphere.points, dtype=np.float64)) pv_plot.add_mesh(points_only_mesh) def points_only(): ray_drawer.rays = None ray_drawer.draw() pv_plot.remove_actor(target_actor) sphere.update() points_only_mesh.points = sphere.points.numpy() pv_plot.add_key_event("r", test_angle) pv_plot.add_key_event("w", whole_distribution) pv_plot.add_key_event("p", points_only) pv_plot.show()
def test_init(): mesh = pyvista.PolyData() assert not mesh.n_points assert not mesh.n_cells
figWidth = 6.4 # hist figure width figHeight = 4.8 # hist figure height caseDir = '6mpa' surfaceDir = 'postProcessing/surfaces/0.00063' expDir = 'CT_data' pics= np.array([304,354,404,454,504]) for var in pics: img = plt.imread('%s/%s/CT_data%s.tif' % (wdir, expDir, var)) img = img.flatten() img = img/65535.0 img = np.ma.masked_equal(img,0) rho = vtki.PolyData('%s/%s/%s/rho_x%s.vtk' % (wdir,caseDir,surfaceDir,var)).point_arrays['rho'] rhog = vtki.PolyData('%s/%s/%s/rhog_x%s.vtk' % (wdir,caseDir,surfaceDir,var)).point_arrays['rhog'] alphaFrac = vtki.PolyData('%s/%s/%s/alphaFrac_x%s.vtk' % (wdir,caseDir,surfaceDir,var)).point_arrays['alphaFrac'] y = vtki.PolyData('%s/%s/%s/y_x%s.vtk' % (wdir,caseDir,surfaceDir,var)).point_arrays['y'] lvf = (1-alphaFrac)*(1-y*(rho/rhog)) fig = plt.figure(figsize=[figWidth,figHeight]) fig.suptitle('Histogram at slice %s' % var) fig.add_subplot(1,2,1) plt.xlabel("Pixel value / Intensity (i)") plt.ylabel("Number of pixels") plt.title('Experimental') hist, bins, ignored = plt.hist(img,bins=nBinsExp) fig.add_subplot(1,2,2) plt.xlabel("LVF") plt.xlim(0,1)
def _clear_g_path_event_watcher(): self.picked_geodesic = pyvista.PolyData() self.remove_actor('_picked_path') self._last_picked_idx = None return
def plot_topography(self, topography=None, scalars=None, contours=True, clear=True, **kwargs): """ Args: topography: scalars: clear: **kwargs: """ rgb = False if clear is True and 'topography' in self.surface_actors and self.plotter_type != 'notebook': self.p._scalar_bar_slot_lookup['height'] = None self.p.remove_actor(self.surface_actors['topography']) self.p.remove_actor(self.surface_actors["topography_cont"]) if not topography: try: topography = self.model._grid.topography.values except AttributeError: raise AttributeError( "Unable to plot topography: Given geomodel instance " "does not contain topography grid.") polydata = pv.PolyData(topography) if scalars is None and self.model.solutions.geological_map is not None: scalars = 'geomap' elif scalars is None: scalars = 'topography' if scalars == "geomap": colors_hex = self._get_color_lot(is_faults=False, is_basement=True, index='id') colors_rgb_ = colors_hex.apply( lambda val: list(mcolors.hex2color(val))) colors_rgb = pd.DataFrame(colors_rgb_.to_list(), index=colors_hex.index) * 255 sel = np.round( self.model.solutions.geological_map[0]).astype(int)[0] scalars_val = numpy_to_vtk(colors_rgb.loc[sel], array_type=3) cm = mcolors.ListedColormap( list(self._get_color_lot(is_faults=True, is_basement=True))) rgb = True elif scalars == "topography": scalars_val = topography[:, 2] cm = 'terrain' elif type(scalars) is np.ndarray: scalars_val = scalars cm = 'terrain' else: raise AttributeError("Parameter scalars needs to be either \ 'geomap', 'topography' or a np.ndarray with scalar values" ) polydata.delaunay_2d(inplace=True) polydata['id'] = scalars_val polydata['height'] = topography[:, 2] if scalars != 'geomap': show_scalar_bar = True scalars = 'height' else: show_scalar_bar = False scalars = 'id' sbo = self.scalar_bar_options sbo['position_y'] = .35 topography_actor = self.p.add_mesh(polydata, scalars=scalars, cmap=cm, rgb=rgb, show_scalar_bar=show_scalar_bar, scalar_bar_args=sbo, **kwargs) if scalars == 'geomap': self.set_scalar_bar() if contours is True: contours = polydata.contour(scalars='height') contours_actor = self.p.add_mesh(contours, color="white", line_width=3) self.surface_poly['topography'] = polydata self.surface_poly['topography_cont'] = contours self.surface_actors["topography"] = topography_actor self.surface_actors["topography_cont"] = contours_actor return topography_actor
def p_knots(knots, cp, p=None, weight=None, show=False, resolution=20, point=True, line=True, **kwargs): from pygeoiga.engine.NURB_engine import curve_point, surface_point if p is None: p = pyvista.Plotter(notebook=False) if isinstance(knots, list) or isinstance(knots, tuple): knots = np.asarray(knots, dtype=object) if cp.shape[-1] == 2: new_cp = np.zeros((cp.shape[0], cp.shape[1], 3)) new_cp[..., :cp.shape[-1]] = cp cp = new_cp if "color" not in kwargs: kwargs["color"] = "green" point_size = kwargs.pop("point_size", 15) line_width = kwargs.pop("line_width", 4) if knots.shape[0] == 1: knots = knots[0] degree = len(np.where(knots == 0.)[0]) - 1 if weight is None: weight = np.ones(cp.shape[0]) else: weight = weight[..., -1] points = np.linspace(knots[0], knots[-1], resolution) if line: pos = [] for u in points: pos.append(curve_point(u, degree, knots, cp, weight)) pos = np.asarray(pos) spline = pyvista.Spline(pos, resolution**2) p.add_mesh(spline, line_width=line_width, **kwargs) if point: pos = [] for u in knots: pos.append(curve_point(u, degree, knots, cp, weight)) pos = np.asarray(pos) ptn = pyvista.PolyData(pos) p.add_mesh(ptn, point_size=point_size, **kwargs) else: degree1 = len(np.where(np.asarray(knots[0]) == 0.)[0]) - 1 degree2 = len(np.where(np.asarray(knots[1]) == 0.)[0]) - 1 if weight is None: weight = np.ones((cp.shape[0], cp.shape[1], 1)) knot1 = np.asarray(knots[0]) knot2 = np.asarray(knots[1]) points1 = np.linspace(knot1[0], knot1[-1], resolution) points2 = np.linspace(knot2[0], knot2[-1], resolution) if line: for u in knot1: positions_xi = [] for v in points1: positions_xi.append( surface_point(u, v, degree1, degree2, knot1, knot2, cp, weight)) positions_xi = np.asarray(positions_xi) spline_xi = pyvista.Spline(positions_xi, resolution**2) p.add_mesh(spline_xi, line_width=line_width, **kwargs) for v in knot2: positions_eta = [] for u in points2: positions_eta.append( surface_point(u, v, degree1, degree2, knot1, knot2, cp, weight)) positions_eta = np.asarray(positions_eta) spline_eta = pyvista.Spline(positions_eta, resolution**2) p.add_mesh(spline_eta, line_width=line_width, **kwargs) if point: positions = [] for u in knot1: for v in knot2: positions.append( surface_point(u, v, degree1, degree2, knot1, knot2, cp, weight)) positions = np.asarray(positions) ptn = pyvista.PolyData(positions) p.add_mesh(ptn, point_size=point_size, **kwargs) if show: p_show(p) return p
def tri_to_pv(tri_mesh): faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3) pv_mesh = pv.PolyData(tri_mesh.vertices, faces) return pv_mesh
import pyvista as pv import sympy as sp from sympy import Matrix, lambdify import numpy as np from PyQt5 import Qt, QtWidgets from PyQt5.QtWidgets import QMessageBox from pyvistaqt import QtInteractor import sys, os, time import trimesh # initiate stored mesh mesh = pv.PolyData() class MainWindow(Qt.QMainWindow): def __init__(self, parent=None, show=True): Qt.QMainWindow.__init__(self, parent) # create the frame self.frame = Qt.QFrame() vlayout = Qt.QVBoxLayout() # add the pyvista interactor object self.plotter = QtInteractor(self.frame) vlayout.addWidget(self.plotter.interactor) self.frame.setLayout(vlayout) self.setCentralWidget(self.frame) # simple menu mainMenu = self.menuBar()
def toPolyData(verts, faces): nFaces = np.array([len(vs) for vs in faces]) faces = np.hstack([nFaces.reshape(nFaces.shape[0], 1), faces]) mesh = pv.PolyData(verts, faces) return mesh
def numpy_to_pyvista(v, f=None): if f is None: return pv.PolyData(v) else: return pv.PolyData(v, np.concatenate((np.full((f.shape[0], 1), 3), f), 1))
import pyvista as pv # Create source to ray trace sphere = pv.Sphere(radius=0.85) # Define line segment start = [0, 0, 0] stop = [0.25, 1, 0.5] # Perfrom ray trace points, ind = sphere.ray_trace(start, stop) # Create geometry to represent ray trace ray = pv.Line(start, stop) intersection = pv.PolyData(points) # Render the result p = pv.Plotter() p.add_mesh(sphere, show_edges=True, opacity=0.5, color="w", lighting=False, label="Test Mesh") p.add_mesh(ray, color="blue", line_width=5, label="Ray Segment") p.add_mesh(intersection, color="maroon", point_size=10, label="Intersection Points") p.add_legend()
[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]) knot11 = np.array([0, 0, 0, 0, 1, 1, 1, 1]) knot22=np.array([0,0,0,0.3,0.5,0.7,1,1,1]) model2= gempyExplicit.NURBS_Surface(3, 2, knot11, knot22, points_gempy2, weighttt, 50, 50, "auto")[0] re_points=np.reshape(points_gempy2.ravel(),(24,3)) #model3 = gempyExplicit.NURBS_Surface(3, 2, knot11, knot22, re_points, weighttt, 50, 50, "auto") print(model2) cloud2 = pyvista.PolyData(model2) #%% #cloud2.points.shape model2.shape #%% def update_surface(point, i): re_points[i] = point temp= re_points to_model = np.reshape(temp.ravel(),(4,6,3)) model_p = gempyExplicit.NURBS_Surface(3,2, knot11, knot22, to_model, weighttt, 50, 50, "auto") cloud2.points = model_p return #%% surf2 = cloud2.delaunay_3d() p = pyvista.Plotter()
"angle_start": next(angle_start_iter), "angle_end": next(angle_end_iter) } # build the plotter plot = pv.Plotter() plot.add_axes() plot.camera_position = [(0, 0, 5), (0, 0, 0), (0, 1, 0)] points, faces = mt.circular_mesh( mesh_params["radius"], mesh_params["target_edge_size"], starting_radius=mesh_params["starting_radius"], theta_start=mesh_params["angle_start"], theta_end=mesh_params["angle_end"]) mesh = pv.PolyData(points, faces) vg = boundaries.FromVectorVG((1, 0, 0)) boundary = boundaries.ManualTriangleBoundary(mesh=mesh) drawer = drawing.TriangleDrawer(plot, draw_norm_arrows=True, norm_arrow_visibility=True, norm_arrow_length=.2) drawer.surface = boundary def update(mesh, mesh_params): mesh.points, mesh.faces = mt.circular_mesh( mesh_params["radius"], mesh_params["target_edge_size"],
def _calculate_faults( self, fault_tolerance: float = 1.0e-05 ) -> Optional[Dict[str, List[int]]]: """ Calculates fault definitions using the following approach: 1) Loop through all faults 2) Perform a triangulation of all points belonging to a fault plane and store the triangles 3) For each connection, find all triangles in its bounding box, perform ray tracing using the Möller-Trumbore intersection algorithm. 4) If an intersection is found, identify the grid blocks that are associated with the intersection. Args: fault_tolerance: minimum distance between corners of a triangle. This value should be set as low as possible to ensure a high resolution fault plane generation. However, this might lead to a very slow fault tracing process therefore one might want to increase the tolerance. Always check that the resulting lower resolution fault plane still is what you expected. Returns: Listing of tuples of FAULTS entries with zero-offset i-coordinates, or None if no faults are present. """ dict_fault_keyword: Dict[str, List[int]] = {} if self._fault_planes is not None: fault_names = self._fault_planes["NAME"].unique().tolist() if not fault_names: return None print("Performing fault ray tracing...", end=" ", flush=True) # Gather all triangles for all faults and keep track of fault names all_triangles_fault_names: List = [] all_triangles = np.empty(shape=[0, 9]) for fault_name in fault_names: data = self._fault_planes.loc[self._fault_planes["NAME"] == fault_name][["X", "Y", "Z"]].values cloud = pv.PolyData(data) surf = cloud.delaunay_2d(tol=fault_tolerance) # surf.plot(show_edges=True) vertices = surf.points[surf.faces.reshape(-1, 4)[:, 1:4].ravel()] triangles = np.array(vertices).reshape(-1, 9) all_triangles_fault_names.extend( repeat(fault_name, np.shape(triangles)[0])) all_triangles = np.append(all_triangles, triangles, axis=0) dict_fault_keyword[fault_name] = [] # Loop through all connections and select all triangles inside of the bounding box of the connection # Perform ray tracing on all resulting triangles. for index, row in self._df_entity_connections.iterrows(): bx1, bx2 = sorted([row["xstart"], row["xend"]]) by1, by2 = sorted([row["ystart"], row["yend"]]) bz1, bz2 = sorted([row["zstart"], row["zend"]]) corner1 = np.array([bx1, by1, bz1]) corner2 = np.array([bx2, by2, bz2]) vertex1_in_box = np.all( np.logical_and(corner1 <= all_triangles[:, 0:3], all_triangles[:, 0:3] <= corner2), axis=1, ) vertex2_in_box = np.all( np.logical_and(corner1 <= all_triangles[:, 3:6], all_triangles[:, 3:6] <= corner2), axis=1, ) vertex3_in_box = np.all( np.logical_and(corner1 <= all_triangles[:, 6:9], all_triangles[:, 6:9] <= corner2), axis=1, ) triangle_in_box: np.ndarray = np.any( # type: ignore np.column_stack( (vertex1_in_box, vertex2_in_box, vertex3_in_box)), axis=1, ) triangles_in_bounding_box = all_triangles[triangle_in_box] fault_names_in_bounding_box = list( compress(all_triangles_fault_names, triangle_in_box)) # Loop through all triangles inside of the bounding box and perform ray tracing cells_in_fault = [] for (triangle, fault_name) in list( zip(triangles_in_bounding_box, fault_names_in_bounding_box)): distance = moller_trumbore( row["xstart"], row["ystart"], row["zstart"], row["xend"], row["yend"], row["zend"], *triangle, ) if distance: indices = self._grid.index[self.active_mask( index)].tolist() tube_cell_index = min( max(0, int(distance * len(indices)) - 1), len(indices) - 2) cell_i_index = indices[tube_cell_index] cells_in_fault.append(cell_i_index) if len(cells_in_fault) > 0: dict_fault_keyword[fault_name].extend(cells_in_fault) # Remove empty and double entries for fault_name in fault_names: if not dict_fault_keyword[fault_name]: dict_fault_keyword.pop(fault_name) else: dict_fault_keyword[fault_name] = list( set(dict_fault_keyword[fault_name])) print("done.") return dict_fault_keyword
def max_cube_ray(self, value): """ add a maximally inscribed cube within the opened mesh (via ray tracing) """ global ranges, Vol_centroid global face_center, max_cube, max_normal, max_cube_vol # global max_cube_V, max_cube_F global max_cube_start, max_cube_end, max_cube_run global top_rays, top_ints, bottom_rays, bottom_ints # bypass error try: top_rays, top_ints, bottom_rays, bottom_ints, max_cube, r_num except NameError: top_rays = None top_ints = None bottom_rays = None bottom_ints = None max_cube = None r_num = 0 print(r_num) print(max_cube) # remove old rays if (r_num != 0) and (r_num == int(value[0])): return elif (r_num != 0) and (max_cube != None): self.plotter.remove_actor(max_cube) for i in range(0, r_num): self.plotter.remove_actor(top_rays[i]) self.plotter.remove_actor(top_ints[i]) self.plotter.remove_actor(bottom_rays[i]) self.plotter.remove_actor(bottom_ints[i]) # track starting time max_cube_start = time.time() # find mesh vertices V = np.array(mesh.points) # find the max and min of x,y,z axes of mesh ranges = mesh.bounds # show centroid Vol_centroid = np.array( [0, 0, 0]) # overwrite centroid with origin at principle axes self.plotter.add_mesh(pv.PolyData(Vol_centroid), color='r', point_size=20.0, render_points_as_spheres=True) # find the nearest possible cube vertex from top rays & mesh intersection top_vert, top_rays, top_ints = self.cube_center_ray( Vol_centroid, 'z', value) top = self.furthest_pt(top_vert, Vol_centroid) # find the nearest possible cube vertex from bottom rays & mesh intersection bottom_vert, bottom_rays, bottom_ints = self.cube_center_ray( Vol_centroid, '-z', value) bottom = self.furthest_pt(bottom_vert, Vol_centroid) # find the nearest possible cube vertex between the two if top[0] < bottom[0]: p = top[1] V = top[2] else: p = bottom[1] V = bottom[2] # create and show max cube max_cube_V, max_cube_F, max_cube_vol = self.create_cube( V[p, :], Vol_centroid, np.array([0, 0, Vol_centroid[2]])) max_cube = self.plotter.add_mesh(pv.PolyData(max_cube_V, max_cube_F), show_edges=True, line_width=3, color="g", opacity=0.6) # find & show max cube face centers cell_center = pv.PolyData(max_cube_V, max_cube_F).cell_centers() face_center = np.array(cell_center.points) #self.plotter.add_mesh(cell_center, color="r", point_size=8, render_points_as_spheres=True) # find max cube face normals max_normal = pv.PolyData(max_cube_V, max_cube_F).cell_normals # max cube volume max_cube_vol = float(format(max_cube_vol, ".5f")) print("Max Cube Volume:", max_cube_vol) # track ending time & duration max_cube_end = time.time() max_cube_run = max_cube_end - max_cube_start return
def plot_surface_points(self, surfaces: Union[str, Iterable[str]] = 'all', surface_points: pd.DataFrame = None, clear: bool = True, colors=None, render_points_as_spheres=True, point_size=10, **kwargs): # Selecting the surfaces to plot """ Args: surfaces: surface_points (pd.DataFrame): clear (bool): colors: render_points_as_spheres: point_size: **kwargs: """ if surface_points is None: surface_points = self._select_surfaces_data( self.model._surface_points.df, surfaces) if clear is True: if self.plotter_type != 'notebook': if 'id' not in self.p._scalar_bar_slot_lookup: self.p._scalar_bar_slot_lookup['id'] = None self.p.clear_sphere_widgets() self.surface_points_widgets = {} try: self.p.remove_actor(self.surface_points_actor) except KeyError: pass if self.live_updating is True: sphere_widgets = self.create_sphere_widgets( surface_points, colors, **kwargs) self.surface_points_widgets.update( dict(zip(surface_points.index, sphere_widgets))) r = self.surface_points_widgets else: poly = pv.PolyData(surface_points[["X", "Y", "Z"]].values) poly['id'] = surface_points['id'] self.surface_points_mesh = poly cmap = mcolors.ListedColormap( list(self._get_color_lot(is_faults=True, is_basement=True))) self.surface_points_actor = self.p.add_mesh( poly, cmap=cmap, scalars='id', render_points_as_spheres=render_points_as_spheres, point_size=point_size, show_scalar_bar=False) self.set_scalar_bar() r = self.surface_points_actor self.set_bounds() return r
def make_pyvista_mesh(self): triangles = np.zeros((self.element_dict["triangles"].shape[0],4)) +3 triangles [:,1:4] = self.element_dict["triangles"] triangles = np.array(triangles,dtype=np.int) self.pyvista_mesh = pv.PolyData(self.vertices,triangles)
def test_voxelize(): mesh = pyvista.PolyData(ex.load_uniform().points) vox = pyvista.voxelize(mesh, 0.5) assert vox.n_cells
def wrap(dataset): """Wrap any given VTK data object to its appropriate pyvista data object. Other formats that are supported include: * 2D :class:`numpy.ndarray` of XYZ vertices * 3D :class:`numpy.ndarray` representing a volume. Values will be scalars. * 3D :class:`trimesh.Trimesh` mesh. * 3D :class:`meshio` mesh. Parameters ---------- dataset : :class:`numpy.ndarray`, :class:`trimesh.Trimesh`, or VTK object Dataset to wrap. Returns ------- wrapped_dataset : pyvista class The `pyvista` wrapped dataset. Examples -------- Wrap a numpy array representing a random point cloud. >>> import numpy as np >>> import pyvista >>> points = np.random.random((10, 3)) >>> cloud = pyvista.wrap(points) >>> cloud # doctest:+SKIP PolyData (0x7fc52db83d70) N Cells: 10 N Points: 10 X Bounds: 1.123e-01, 7.457e-01 Y Bounds: 1.009e-01, 9.877e-01 Z Bounds: 2.346e-03, 9.640e-01 N Arrays: 0 Wrap a Trimesh object. >>> import trimesh >>> import pyvista >>> points = [[0, 0, 0], [0, 0, 1], [0, 1, 0]] >>> faces = [[0, 1, 2]] >>> tmesh = trimesh.Trimesh(points, faces=faces, process=False) >>> mesh = pyvista.wrap(tmesh) >>> mesh # doctest:+SKIP PolyData (0x7fc55ff27ad0) N Cells: 1 N Points: 3 X Bounds: 0.000e+00, 0.000e+00 Y Bounds: 0.000e+00, 1.000e+00 Z Bounds: 0.000e+00, 1.000e+00 N Arrays: 0 Wrap a VTK object. >>> import pyvista >>> import vtk >>> points = vtk.vtkPoints() >>> p = [1.0, 2.0, 3.0] >>> vertices = vtk.vtkCellArray() >>> pid = points.InsertNextPoint(p) >>> _ = vertices.InsertNextCell(1) >>> _ = vertices.InsertCellPoint(pid) >>> point = vtk.vtkPolyData() >>> _ = point.SetPoints(points) >>> _ = point.SetVerts(vertices) >>> mesh = pyvista.wrap(point) >>> mesh # doctest:+SKIP PolyData (0x7fc55ff27ad0) N Cells: 1 N Points: 3 X Bounds: 0.000e+00, 0.000e+00 Y Bounds: 0.000e+00, 1.000e+00 Z Bounds: 0.000e+00, 1.000e+00 N Arrays: 0 """ # Return if None if dataset is None: return # Check if dataset is a numpy array. We do this first since # pyvista_ndarray contains a VTK type that we don't want to # directly wrap. if isinstance(dataset, (np.ndarray, pyvista.pyvista_ndarray)): if dataset.ndim == 1 and dataset.shape[0] == 3: return pyvista.PolyData(dataset) if dataset.ndim > 1 and dataset.ndim < 3 and dataset.shape[1] == 3: return pyvista.PolyData(dataset) elif dataset.ndim == 3: mesh = pyvista.UniformGrid(dataset.shape) mesh['values'] = dataset.ravel(order='F') mesh.active_scalars_name = 'values' return mesh else: raise NotImplementedError( 'NumPy array could not be wrapped pyvista.') wrappers = { 'vtkExplicitStructuredGrid': pyvista.ExplicitStructuredGrid, 'vtkUnstructuredGrid': pyvista.UnstructuredGrid, 'vtkRectilinearGrid': pyvista.RectilinearGrid, 'vtkStructuredGrid': pyvista.StructuredGrid, 'vtkPolyData': pyvista.PolyData, 'vtkImageData': pyvista.UniformGrid, 'vtkStructuredPoints': pyvista.UniformGrid, 'vtkMultiBlockDataSet': pyvista.MultiBlock, 'vtkTable': pyvista.Table, # 'vtkParametricSpline': pyvista.Spline, } # Check if a dataset is a VTK type if hasattr(dataset, 'GetClassName'): key = dataset.GetClassName() try: return wrappers[key](dataset) except KeyError: logging.warning( f'VTK data type ({key}) is not currently supported by pyvista.' ) return # wrap meshio if is_meshio_mesh(dataset): return from_meshio(dataset) # wrap trimesh if dataset.__class__.__name__ == 'Trimesh': # trimesh doesn't pad faces n_face = dataset.faces.shape[0] faces = np.empty((n_face, 4), dataset.faces.dtype) faces[:, 1:] = dataset.faces faces[:, 0] = 3 return pyvista.PolyData(np.asarray(dataset.vertices), faces) # otherwise, flag tell the user we can't wrap this object raise NotImplementedError( f'Unable to wrap ({type(dataset)}) into a pyvista type.')
def test_string_arrays(): poly = pyvista.PolyData(np.random.rand(10, 3)) arr = np.array(['foo{}'.format(i) for i in range(10)]) poly['foo'] = arr back = poly['foo'] assert len(back) == 10
def load_ant(): """Load ply ant mesh.""" return pyvista.PolyData(antfile)
def enable_geodesic_picking(self, callback=None, show_message=True, font_size=18, color='pink', point_size=10, line_width=5, tolerance=0.025, show_path=True, **kwargs): """Enable picking at geodesic paths. This is a convenience method for ``enable_point_picking`` to keep track of the picked points and create a geodesic path using those points. The geodesic path is saved to the ``.picked_geodesic`` attribute of this plotter Parameters ---------- callback : callable When given, calls this function after a pick is made. The entire picked, geodesic path is passed as the only parameter to this function. show_path : bool Show the picked path interactively show_message : bool, str Show the message about how to use the point picking tool. If this is a string, that will be the message shown. font_size : int Sets the size of the message. point_size : int, optional Size of picked points if ``show_path`` is ``True``. Default 10. color : str The color of the selected mesh is shown. line_width : float, optional Thickness of path representation if ``show_path`` is ``True``. Default 5. tolerance : float Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. (Rendering window size is measured across diagonal.) kwargs : optional All remaining keyword arguments are used to control how the picked path is intereactively displayed """ kwargs.setdefault('pickable', False) self.picked_geodesic = pyvista.PolyData() self._last_picked_idx = None def _the_callback(mesh, idx): if mesh is None: return point = mesh.points[idx] if self._last_picked_idx is None: self.picked_geodesic = pyvista.PolyData(point) else: surface = mesh.extract_surface().triangulate() locator = _vtk.vtkPointLocator() locator.SetDataSet(surface) locator.BuildLocator() start_idx = locator.FindClosestPoint(mesh.points[self._last_picked_idx]) end_idx = locator.FindClosestPoint(point) self.picked_geodesic = self.picked_geodesic + surface.geodesic(start_idx, end_idx) self._last_picked_idx = idx if show_path: self.add_mesh(self.picked_geodesic, color=color, name='_picked_path', line_width=line_width, point_size=point_size, reset_camera=False, **kwargs) if hasattr(callback, '__call__'): try_callback(callback, self.picked_geodesic) return def _clear_g_path_event_watcher(): self.picked_geodesic = pyvista.PolyData() self.remove_actor('_picked_path') self._last_picked_idx = None return self.add_key_event('c', _clear_g_path_event_watcher) if show_message is True: show_message = "Press P to pick under the mouse\nPress C to clear" return self.enable_point_picking(callback=_the_callback, use_mesh=True, font_size=font_size, show_message=show_message, tolerance=tolerance, show_point=False)
def load_airplane(): """Load ply airplane mesh.""" return pyvista.PolyData(planefile)
t = t -1 print(v.shape, t.shape) print(type(v), type(t)) #print(t[0]) #print(t[0][0]) #print(t[66228]) #print(v[0]) print(v.mean(axis=0) ) import pyvista as pv #surf = pv.PolyData(v ) cloud = pv.PolyData(v ) surf = cloud.delaunay_2d() surf.plot(show_edges=True,cpos=[-1, 4, 5], cmap="viridis", scalars=v, show_bounds=True) # plot each face with a different color #surf.plot(scalars=v, cpos=[-1, 4, 5], cmap="viridis") #grid = pv.StructuredGrid(v) #grid.plot(cpos=[-1, 4, 5], cmap="viridis") #surf.show(screenshot='airplane.png') #t2 = np.hstack((t)) #faces=np.ones(( len(t), 4)*3) #faces[:,1:] = t tri_index = t
def load_sphere(): """Load sphere ply mesh.""" return pyvista.PolyData(spherefile)
def test_init_as_points_from_list(): points = [[0, 0, 0], [0, 1, 0], [0, 0, 1]] mesh = pyvista.PolyData(points) assert np.allclose(mesh.points, points)
def load_globe(): """Load a globe source.""" globe = pyvista.PolyData(globefile) globe.textures['2k_earth_daymap'] = load_globe_texture() return globe
def test_init_from_pdata(sphere): mesh = pyvista.PolyData(sphere, deep=True) assert mesh.n_points assert mesh.n_cells mesh.points[0] += 1 assert not np.allclose(sphere.points[0], mesh.points[0])
def read(filename, attrs=None, file_format=None): """Read any VTK file. It will figure out what reader to use then wrap the VTK object for use in PyVista. Parameters ---------- filename : str The string path to the file to read. If a list of files is given, a :class:`pyvista.MultiBlock` dataset is returned with each file being a seperate block in the dataset. attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value. file_format : str, optional Format of file to read with meshio. """ if isinstance(filename, (list, tuple)): multi = pyvista.MultiBlock() for each in filename: if isinstance(each, str): name = os.path.basename(each) else: name = None multi[-1, name] = read(each) return multi filename = os.path.abspath(os.path.expanduser(filename)) if not os.path.isfile(filename): raise IOError('File ({}) not found'.format(filename)) ext = get_ext(filename) # Read file using meshio.read if file_format is present if file_format: return read_meshio(filename, file_format) # From the extension, decide which reader to use if attrs is not None: reader = get_reader(filename) return standard_reader_routine(reader, filename, attrs=attrs) elif ext in '.vti': # ImageData return pyvista.UniformGrid(filename) elif ext in '.vtr': # RectilinearGrid return pyvista.RectilinearGrid(filename) elif ext in '.vtu': # UnstructuredGrid return pyvista.UnstructuredGrid(filename) elif ext in ['.ply', '.obj', '.stl']: # PolyData return pyvista.PolyData(filename) elif ext in '.vts': # StructuredGrid return pyvista.StructuredGrid(filename) elif ext in ['.vtm', '.vtmb']: return pyvista.MultiBlock(filename) elif ext in ['.e', '.exo']: return read_exodus(filename) elif ext in ['.vtk']: # Attempt to use the legacy reader... return read_legacy(filename) else: # Attempt find a reader in the readers mapping try: reader = get_reader(filename) return standard_reader_routine(reader, filename) except KeyError: # Attempt read with meshio try: from meshio._exceptions import ReadError try: return read_meshio(filename) except ReadError: pass except SyntaxError: # https://github.com/pyvista/pyvista/pull/495 pass raise IOError( "This file was not able to be automatically read by pyvista.")