def end_pick_helper(picker, event_id): # Merge the selection into a single mesh picked = self_().picked_cells if isinstance(picked, pyvista.MultiBlock): if picked.n_blocks > 0: picked = picked.combine() else: picked = pyvista.UnstructuredGrid() # Check if valid is_valid_selection = picked.n_cells > 0 if show and is_valid_selection: # Use try in case selection is empty self_().add_mesh(picked, name='_cell_picking_selection', style=style, color=color, line_width=line_width, pickable=False, reset_camera=False, **kwargs) # render here prior to running the callback self_().render() elif not is_valid_selection: self.remove_actor('_cell_picking_selection') self_().picked_cells = None if callback is not None: try_callback(callback, self_().picked_cells) # TODO: Deactivate selection tool return
def test_init_from_arrays(): offset = np.array([0, 9], np.int8) cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15]) cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON], np.int32) cell1 = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]) cell2 = np.array([[0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 1, 2], [0, 0, 3], [1, 0, 3], [1, 1, 3], [0, 1, 3]]) points = np.vstack((cell1, cell2)).astype(np.int32) grid = pyvista.UnstructuredGrid(offset, cells, cell_type, points) assert grid.n_cells == 2 assert np.allclose(grid.offset, offset)
def test_grid_extract_selection_points(): grid = pyvista.UnstructuredGrid(sgrid) sub_grid = grid.extract_selection_points([0]) assert sub_grid.n_cells == 1 sub_grid = grid.extract_selection_points(range(100)) assert sub_grid.n_cells > 1
def grid(self): """ Returns a :class:`pyvista.UnstructuredGrid` """ if not hasattr(self, 'node'): raise Exception('Run Tetrahedralize first') if hasattr(self, '_grid') and not self._updated: return self._grid buf = np.empty((self.elem.shape[0], 1), np.int64) cell_type = np.empty(self.elem.shape[0], dtype='uint8') if self.elem.shape[1] == 4: # linear buf[:] = 4 cell_type[:] = 10 elif self.elem.shape[1] == 10: # quadradic buf[:] = 10 cell_type[:] = 24 else: raise Exception('Invalid element array shape %s' % str(self.elem.shape)) offset = np.cumsum(buf + 1) - (buf[0] + 1) cells = np.hstack((buf, self.elem)) self._grid = pv.UnstructuredGrid(offset, cells, cell_type, self.node) self._updated = False return self._grid
def get_vtk(self): """ Get the pyvista Object https://docs.pyvista.org/examples/00-load/create-unstructured-surface.html#sphx-glr-examples-00-load-create-unstructured-surface-py """ #Identify the cell data connections offset = np.arange(0,9*self.n,step=9) points = np.zeros((self.n*8,3)) #Cells for k in range(self.nz): for j in range(self.ny): for i in range(self.nx): c_idx = self.get_cell_id(i,j,k) #cells_array[c_idx,:] = self.get_vertices_id(i,j,k, order='VTK') ind_from = 8*c_idx ind_to = 8*(c_idx+1) points[ind_from:ind_to,:] = self.get_vertices_coords(i,j,k, order = 'VTK') # Make a vector of shape self.n, make 2D and append to cell array then flatten C order cell_array = np.arange(self.n*8).reshape((self.n,8)) cells = np.append(np.full(self.n,8).reshape((self.n,1)),cell_array,1).flatten() # cell type array. Contains the cell type of each cell cell_type = np.array([vtk.VTK_HEXAHEDRON]*self.n) grid = pv.UnstructuredGrid(offset, cells, cell_type, points) if self.spatial_data is not None: for i in self.spatial_data.items(): grid.cell_arrays[i[0]] = i[1] return grid
def meshplot(self, filename): self.get_data(filename) grid = pv.UnstructuredGrid(self.offset, self.cells, self.cell_type, self.points) for i in range(len(self.data) - 3): grid.point_arrays[self.name[i]] = self.property[i] return grid, self.name
def plot_streamlines(): # Plotting streamlines # ==================== # In this section we illustrate how to visualize streamlines in 3D mesh = create_unit_cube(MPI.COMM_WORLD, 4, 4, 4, CellType.hexahedron) V = VectorFunctionSpace(mesh, ("Discontinuous Lagrange", 2)) u = Function(V, dtype=np.float64) u.interpolate(lambda x: np.vstack((-(x[1] - 0.5), x[0] - 0.5, np.zeros(x.shape[1])))) cells, types, x = plot.create_vtk_mesh(V) num_dofs = x.shape[0] values = np.zeros((num_dofs, 3), dtype=np.float64) values[:, :mesh.geometry.dim] = u.x.array.reshape(num_dofs, V.dofmap.index_map_bs) # Create a point cloud of glyphs grid = pyvista.UnstructuredGrid(cells, types, x) grid["vectors"] = values grid.set_active_vectors("vectors") glyphs = grid.glyph(orient="vectors", factor=0.1) streamlines = grid.streamlines(vectors="vectors", return_source=False, source_radius=1, n_points=150) # Create Create plotter plotter = pyvista.Plotter() plotter.add_text("Streamlines.", position="upper_edge", font_size=20, color="black") plotter.add_mesh(grid, style="wireframe") plotter.add_mesh(glyphs) plotter.add_mesh(streamlines.tube(radius=0.001)) plotter.view_xy() if pyvista.OFF_SCREEN: plotter.screenshot(f"streamlines_{MPI.COMM_WORLD.rank}.png", transparent_background=transparent, window_size=[figsize, figsize]) else: plotter.show()
def show_visible_gamut(colorspace, observer, max_Y1, show_grid=True, h=4.0e-2): import pyvista as pv import vtk points, cells = _get_visible_gamut_mesh(observer, max_Y1, h=h) xyz100 = XYY(1).to_xyz100(points.T) xyz100[xyz100 < 0] = 0.0 points = colorspace.from_xyz100(xyz100).T cells = np.column_stack( [np.full(cells.shape[0], cells.shape[1], dtype=cells.dtype), cells]) # each cell is a VTK_HEXAHEDRON celltypes = np.full(len(cells), vtk.VTK_TETRA) grid = pv.UnstructuredGrid(cells.ravel(), celltypes, points) # grid.plot() p = pv.Plotter() p.add_mesh(grid) if show_grid: p.show_grid( xlabel=colorspace.labels[0], ylabel=colorspace.labels[1], zlabel=colorspace.labels[2], ) p.show()
def jmesh_to_vtk(infile, outfile, infile_dict, outfile_dict, reduce=False, scaling=1.0): if infile.endswith(".jmsh"): jmesh = jd.load(infile) meshElem = jmesh["MeshElem"] points = jmesh["MeshVertex3"] * scaling elif infile.endswith(".mat"): mat_contents = scipy.io.loadmat(infile) points = mat_contents["node"] * scaling meshElem = mat_contents["elem"] subdomains = meshElem[:, 4] if reduce: subdomains[subdomains == infile_dict["other"]] = 10 subdomains[subdomains == infile_dict["scalp"]] = 10 subdomains[subdomains == infile_dict["skull"]] = 10 subdomains[subdomains == infile_dict["CSF"]] = outfile_dict["fluid_id"] subdomains[subdomains == infile_dict["WM"]] = outfile_dict["porous_id"] subdomains[subdomains == infile_dict["GM"]] = outfile_dict["porous_id"] n = meshElem.shape[0] p = 4 # number of points per cell for TETRA c = np.insert(meshElem[:, :4] - 1, 0, p, axis=1) cell_type = np.repeat(vtk.VTK_TETRA, n) offset = np.arange(start=0, stop=n * (p + 1), step=p + 1) grid = pv.UnstructuredGrid(offset, c, cell_type, points) grid.cell_arrays["subdomains"] = subdomains.flatten() if reduce: grid = grid.threshold(5, scalars="subdomains", invert=True) pv.save_meshio(outfile, grid)
def beam_example(off_screen=False, notebook=None): # Load module and example file hexfile = hexbeamfile # Load Grid grid = pyvista.UnstructuredGrid(hexfile) # Create fiticious displacements as a function of Z location d = grid.points[:, 2]**3 / 250 grid.points[:, 1] += d # Camera position cpos = [(11.915126303095157, 6.11392754955802, 3.6124956735471914), (0.0, 0.375, 2.0), (-0.42546442225230097, 0.9024244135964158, -0.06789847673314177)] try: import matplotlib cmap = 'bwr' except ImportError: cmap = None # plot this displaced beam plotter = pyvista.Plotter(off_screen=off_screen, notebook=notebook) plotter.add_mesh(grid, scalars=d, stitle='Y Displacement', rng=[-d.max(), d.max()], cmap=cmap) plotter.camera_position = cpos plotter.add_text('Static Beam Example') cpos = plotter.show(auto_close=False) # store camera position # plotter.TakeScreenShot('beam.png') plotter.close()
def test_extract_surface(): # create a single quadratic hexahedral cell lin_pts = np.array([[-1, -1, -1], # node 0 [ 1, -1, -1], # node 1 [ 1, 1, -1], # node 2 [-1, 1, -1], # node 3 [-1, -1, 1], # node 4 [ 1, -1, 1], # node 5 [ 1, 1, 1], # node 6 [-1, 1, 1]], np.double) # node 7 quad_pts = np.array([ (lin_pts[1] + lin_pts[0])/2, # between point 0 and 1 (lin_pts[1] + lin_pts[2])/2, # between point 1 and 2 (lin_pts[2] + lin_pts[3])/2, # and so on... (lin_pts[3] + lin_pts[0])/2, (lin_pts[4] + lin_pts[5])/2, (lin_pts[5] + lin_pts[6])/2, (lin_pts[6] + lin_pts[7])/2, (lin_pts[7] + lin_pts[4])/2, (lin_pts[0] + lin_pts[4])/2, (lin_pts[1] + lin_pts[5])/2, (lin_pts[2] + lin_pts[6])/2, (lin_pts[3] + lin_pts[7])/2]) # introduce a minor variation to the location of the mid-side points quad_pts += np.random.random(quad_pts.shape)*0.25 pts = np.vstack((lin_pts, quad_pts)) cells = np.hstack((20, np.arange(20))).astype(np.int64, copy=False) celltypes = np.array([VTK_QUADRATIC_HEXAHEDRON]) if pyvista._vtk.VTK9: grid = pyvista.UnstructuredGrid(cells, celltypes, pts) else: grid = pyvista.UnstructuredGrid(np.array([0]), cells, celltypes, pts) # expect each face to be divided 6 times since it has a midside node surf = grid.extract_surface() assert surf.n_faces == 36 # expect each face to be divided several more times than the linear extraction surf_subdivided = grid.extract_surface(nonlinear_subdivision=5) assert surf_subdivided.n_faces > surf.n_faces # No subdivision, expect one face per cell surf_no_subdivide = grid.extract_surface(nonlinear_subdivision=0) assert surf_no_subdivide.n_faces == 6
def plot_grid(self, filename='Data/Results/dome.vtu', lighting=False, property='PORO', show_edges=True, specular=0.0, specular_power=0.0, show_scalar_bar=True, cmap='viridis'): r""" Plot the grid with PyVista. Parameters ---------- filename : string, default is 'Data/Results/dome.vtu' String holding the path to VTU file. lighting : boolean, default is False Enable or disable view direction lighting. property : string, default is 'PORO' String holding the name of property that will be plotted. show_edges : boolean, default is True Shows the edges of a mesh. Does not apply to a wireframe representation. specular : float, default is 0.0 The specular lighting coefficient. specular_power : float, default is 0.0 The specular power. Between 0.0 and 128.0. show_scalar_bar : boolean, default is True If False, a scalar bar will not be added to the scene. cmap : string, default is 'viridis' Name of the Matplotlib colormap to us when mapping the 'scalars'. See available Matplotlib colormaps. Notes ----- https://www.pyvista.org/ """ import matplotlib.pyplot as plt import pyvista as pv # Check if file exists and can be open misc.file_open_exception(filename) # Check if grid is already defined if self._grid_type == 'corner-point': misc.check_corner_point_grid(self._cart_dims, self._coord, self._zcorn) else: misc.check_cartesian_grid(self._cart_dims, self._dx, self._dy, self._dz, self._tops) # Set theme pv.set_plot_theme("document") # Color map cmap = plt.cm.get_cmap(cmap, 5) # Mesh to be plotted mesh = pv.UnstructuredGrid(misc.get_path(filename)) # Remove ghost cells if they are present in the mesh if 'ACTNUM' in mesh.array_names: ghosts = np.argwhere(mesh["ACTNUM"] < 1) mesh.remove_cells(ghosts) # Plot the grid mesh.plot(lighting=lighting, specular=specular, specular_power=specular_power, show_edges=show_edges, scalars=property, show_scalar_bar=show_scalar_bar, cmap=cmap)
def plot_scalar(): # We start by creating a unit square mesh and interpolating a function # into a first order Lagrange space msh = create_unit_square(MPI.COMM_WORLD, 12, 12, cell_type=CellType.quadrilateral) V = FunctionSpace(msh, ("Lagrange", 1)) u = Function(V, dtype=np.float64) u.interpolate(lambda x: np.sin(np.pi * x[0]) * np.sin(2 * x[1] * np.pi)) # As we want to visualize the function u, we have to create a grid to # attached the dof values to We do this by creating a topology and # geometry based on the function space V cells, types, x = plot.create_vtk_mesh(V) grid = pyvista.UnstructuredGrid(cells, types, x) grid.point_data["u"] = u.x.array # We set the function "u" as the active scalar for the mesh, and warp # the mesh in z-direction by its values grid.set_active_scalars("u") warped = grid.warp_by_scalar() # We create a plotting window consisting of to plots, one of the scalar # values, and one where the mesh is warped by these values subplotter = pyvista.Plotter(shape=(1, 2)) subplotter.subplot(0, 0) subplotter.add_text("Scalar countour field", font_size=14, color="black", position="upper_edge") subplotter.add_mesh(grid, show_edges=True, show_scalar_bar=True) subplotter.view_xy() subplotter.subplot(0, 1) subplotter.add_text("Warped function", position="upper_edge", font_size=14, color="black") sargs = dict(height=0.8, width=0.1, vertical=True, position_x=0.05, position_y=0.05, fmt="%1.2e", title_font_size=40, color="black", label_font_size=25) subplotter.set_position([-3, 2.6, 0.3]) subplotter.set_focus([3, -1, -0.15]) subplotter.set_viewup([0, 0, 1]) subplotter.add_mesh(warped, show_edges=True, scalar_bar_args=sargs) if pyvista.OFF_SCREEN: subplotter.screenshot("2D_function_warp.png", transparent_background=transparent, window_size=[figsize, figsize]) else: subplotter.show()
def to_pyvista(tin, *arg, **kw): meshdata = to_meshdata(tin, *arg, **kw) m = pyvista.UnstructuredGrid(meshdata["cells"], meshdata["celltypes"], meshdata["points"]) for col in meshdata["point_arrays"].columns: if meshdata["point_arrays"][col].dtype == object: continue m.point_arrays[col] = meshdata["point_arrays"][col] return m
def read_meshio(filename, file_format=None): """Read any mesh file using meshio.""" import meshio from meshio.vtk._vtk import ( meshio_to_vtk_type, vtk_type_to_numnodes, ) # Make sure relative paths will work filename = os.path.abspath(os.path.expanduser(str(filename))) # Read mesh file mesh = meshio.read(filename, file_format) # Extract cells from meshio.Mesh object offset = [] cells = [] cell_type = [] cell_data = {} next_offset = 0 for k, v in mesh.cells.items(): vtk_type = meshio_to_vtk_type[k] numnodes = vtk_type_to_numnodes[vtk_type] offset += [next_offset + i * (numnodes + 1) for i in range(len(v))] cells.append(np.hstack((np.full((len(v), 1), numnodes), v)).ravel()) cell_type += [vtk_type] * len(v) next_offset = offset[-1] + numnodes + 1 # Extract cell data if k in mesh.cell_data.keys(): for kk, vv in mesh.cell_data[k].items(): if kk in cell_data: cell_data[kk] = np.concatenate( (cell_data[kk], np.array(vv, np.float64))) else: cell_data[kk] = np.array(vv, np.float64) # Create pyvista.UnstructuredGrid object points = mesh.points if points.shape[1] == 2: points = np.hstack((points, np.zeros((len(points), 1)))) grid = pyvista.UnstructuredGrid( np.array(offset), np.concatenate(cells), np.array(cell_type), np.array(points, np.float64), ) # Set point data grid.point_arrays.update( {k: np.array(v, np.float64) for k, v in mesh.point_data.items()}) # Set cell data grid.cell_arrays.update(cell_data) return grid
def converged(iteration, time_step=opt.compared_time, variable='U', method='L2', reference = False): ''' Check if the results for the given variable at given time_step differ less then the chosen tolerance. The norm used for this can be set to 'L2' or 'Maximum'. ''' convergence = False #Keydict of time to VTK file. Necessary, since folder names and timesteps still missmatch time_to_vtk = {'0': 0, '5': 250, '10': 500, '15': 750, '20': 1000, '25': 1250, '30': 750, '35': 1000, '40': 1250, '45': 1500, '50': 1750, '55': 1500, '60': 1750, '65': 2000, '70': 2250, '75': 2500, '80': 2000, '85': 2250, '90': 2500, '95': 2750, '100': 3000} #setting folder and path variables: time_slice = m.ceil(time_step*opt.num_time_slices/opt.t_end) dir = os.getcwd() previous_path = dir + '/' + opt.name_folders + str(time_slice) + '_' + str(iteration-1) + '/VTK' current_path = dir + '/' + opt.name_folders + str(time_slice) + '_' + str(iteration) + '/VTK' #load vtk files from previous iteration as pyvista objects os.chdir(previous_path) for files in os.listdir(previous_path): if files.endswith(str(time_to_vtk[str(time_step)]) + ".vtk"): previous_data = vtki.UnstructuredGrid(previous_path+'/'+files) #load vtk files from current iteration as pyvista objects os.chdir(current_path) for files in os.listdir(current_path): if files.endswith(str(time_to_vtk[str(time_step)]) + ".vtk"): current_data = vtki.UnstructuredGrid(current_path+'/'+files) diff = current_data.cell_arrays[variable] - previous_data.cell_arrays[variable] #calculation of norms according to 'method' if method is 'L2': diff_norm = np.linalg.norm(diff) if method is 'Maximum': diff_norm = np.amax(abs(diff)) #check convergence: if diff_norm <= opt.tolerance: convergence = True os.chdir(dir) return(convergence,diff_norm)
def plot_gif(self, sim_property, filename, dt=0.5, t=20, **kwargs): print('Generating gif, please wait...') var = self.getvar(sim_property).to_numpy() pv.UnstructuredGrid(self.assembly.export_vtk()) # if not cmap: cmap = plt.cm.get_cmap("viridis", 5) grid = pv.UnstructuredGrid(self.assembly.export_vtk()) grid.cell_arrays[sim_property] = var grid.set_active_scalar(sim_property) plotter = pv.Plotter() plotter.open_gif(filename) plotter.add_mesh( grid, scalars=sim_property, stitle=sim_property, # rng=[var.min(), var.max()], lighting=False, texture=True, show_edges=True, **kwargs) plotter.add_axes() plotter.view_isometric() t_c = 0 plotter.write_frame() while t_c < t: var = self.getvar(sim_property).to_numpy() grid.cell_arrays[sim_property] = var #this is not some critical task, good enough t_c = t_c + dt time.sleep(dt) plotter.write_frame() plotter.close() print('Done.')
def test_init_from_numpy_arrays(): offset = np.array([0, 9]) cells = [ [8, 0, 1, 2, 3, 4, 5, 6, 7], [8, 8, 9, 10, 11, 12, 13, 14, 15] ] cells = np.array(cells).ravel() cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON]) cell1 = np.array( [ [0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1], ] ) cell2 = np.array( [ [0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 1, 2], [0, 0, 3], [1, 0, 3], [1, 1, 3], [0, 1, 3], ] ) points = np.vstack((cell1, cell2)) if VTK9: grid = pyvista.UnstructuredGrid(cells, cell_type, points) else: grid = pyvista.UnstructuredGrid(offset, cells, cell_type, points) assert grid.number_of_points == 16 assert grid.number_of_cells == 2
def test_xmlunstructuredgridreader(tmpdir): tmpfile = tmpdir.join("temp.vtu") mesh = pyvista.UnstructuredGrid() mesh.save(tmpfile.strpath) reader = pyvista.get_reader(tmpfile.strpath) assert reader.filename == tmpfile.strpath new_mesh = reader.read() assert isinstance(new_mesh, pyvista.UnstructuredGrid) assert new_mesh.n_points == mesh.n_points assert new_mesh.n_cells == mesh.n_cells
def to_pyvista(tri, **kw): meshdata = to_meshdata(tri, **kw) m = pyvista.UnstructuredGrid(meshdata["cells"], meshdata["celltypes"], meshdata["points"]) for col, dtype in meshdata["point_arrays"].dtypes.items(): if dtype != float: continue m.point_arrays[col] = meshdata["point_arrays"][col] for col, dtype in meshdata["cell_arrays"].dtypes.items(): if dtype != float: continue m.cell_arrays[col] = meshdata["cell_arrays"][col] return m
def plotter_rigiddiaphram(p,TCLFile,NodeCoord): offset = np.array([0, 0]) rigiddia_info=rigiddiaphram_info(TCLFile) print(rigiddia_info) if (rigiddia_info.size > 0): cells = frame_cell(rigiddia_info, node(TCLFile)) print(cells) cell_type = (cell_type_frame(rigiddia_info)) grid = pv.UnstructuredGrid(offset, cells, cell_type, NodeCoord) p.add_mesh(grid, lighting=False, color='gold', show_edges=True, line_width=0.5)
def test_write_non_ansys_grid(tmpdir): grid = pv.UnstructuredGrid(pyvista_examples.hexbeamfile) del grid.point_arrays['sample_point_scalars'] del grid.cell_arrays['sample_cell_scalars'] try: archive_file = str(tmpdir.mkdir("tmpdir").join('tmp.cdb')) except: archive_file = '/tmp/nblock.cdb' pyansys.save_as_archive(archive_file, grid)
def test_init_from_arrays(specify_offset): offset, cells, cell_type, points = create_hex_example() if VTK9: grid = pyvista.UnstructuredGrid(cells, cell_type, points, deep=False) else: if specify_offset: grid = pyvista.UnstructuredGrid(offset, cells, cell_type, points, deep=False) else: grid = pyvista.UnstructuredGrid(cells, cell_type, points, deep=False) assert np.allclose(grid.offset, offset) assert grid.n_cells == 2 assert np.allclose(cells, grid.cells) if VTK9: assert np.allclose(grid.cell_connectivity, np.arange(16)) else: with pytest.raises(AttributeError): grid.cell_connectivity
def to_pyvista_tetra(tetra_mesh: TetraMesh): """Create pyvista.UnstructuredGrid""" vertices = tetra_mesh.data.vertex tets = tetra_mesh.data.cells cells = np.c_[np.full(len(tets), 4), tets] import vtk ctypes = np.array([ vtk.VTK_TETRA, ], np.int32) mesh = pv.UnstructuredGrid(cells, ctypes, vertices) mesh.cell_arrays.update(tetra_mesh.data.attributes_to_dict) return mesh
def meshplot(self, filename): type = self.get_data(filename) if (type == 1): grid = pv.UnstructuredGrid(self.offset, self.cells, self.cell_type, self.points) grid.slice() for i in range(len(self.data) - 3): grid.point_arrays[self.name[i]] = self.property[i] return grid, self.name, type elif (type == 0): return 0, 0, type
def test_save(extension, binary, tmpdir): filename = str(tmpdir.mkdir("tmpdir").join('tmp.%s' % extension)) beam.save(filename, binary) grid = pyvista.UnstructuredGrid(filename) assert grid.cells.shape == beam.cells.shape assert grid.points.shape == beam.points.shape grid = pyvista.read(filename) assert grid.cells.shape == beam.cells.shape assert grid.points.shape == beam.points.shape assert isinstance(grid, pyvista.UnstructuredGrid)
def get_pyvista_unstructured_grid(self): try: import pyvista as pv except: raise ImportError('failed to import PyVista') try: import vtk as vtk except: raise ImportError('failed to import vtk') return pv.UnstructuredGrid({vtk.VTK_TRIANGLE: self.F}, self.V)
def test_rotate_should_match_vtk_rotation(angle, axis, grid): trans = vtk.vtkTransform() getattr(trans, f'Rotate{axis.upper()}')(angle) trans.Update() trans_filter = vtk.vtkTransformFilter() trans_filter.SetTransform(trans) trans_filter.SetInputData(grid) trans_filter.Update() grid_a = pyvista.UnstructuredGrid(trans_filter.GetOutput()) grid_b = grid.copy() getattr(grid_b, f'rotate_{axis}')(angle) assert np.allclose(grid_a.points, grid_b.points, equal_nan=True)
def test_pathlib_read_write(tmpdir, hexbeam): path = pathlib.Path(str(tmpdir.mkdir("tmpdir").join('tmp.vtk'))) assert not path.is_file() hexbeam.save(path) assert path.is_file() grid = pyvista.UnstructuredGrid(path) assert grid.cells.shape == hexbeam.cells.shape assert grid.points.shape == hexbeam.points.shape grid = pyvista.read(path) assert grid.cells.shape == hexbeam.cells.shape assert grid.points.shape == hexbeam.points.shape assert isinstance(grid, pyvista.UnstructuredGrid)
def read(filename, attrs=None): """Read any VTK file. It will figure out what reader to use then wrap the VTK object for use in PyVista. Parameters ---------- 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. """ 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) # 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: pass raise IOError( "This file was not able to be automatically read by pyvista.")