def test_plot(tmpdir): filename = os.path.join(pyvista.USER_DATA_PATH, 'tmp.png') scalars = np.arange(sphere.n_points) cpos, img = pyvista.plot(sphere, off_screen=OFF_SCREEN, full_screen=True, text='this is a sphere', show_bounds=True, color='r', style='wireframe', line_width=10, scalars=scalars, flip_scalars=True, cmap='bwr', interpolate_before_map=True, screenshot=filename, return_img=True) assert isinstance(cpos, pyvista.CameraPosition) assert isinstance(img, np.ndarray) assert os.path.isfile(filename) os.remove(filename) filename = os.path.join(pyvista.USER_DATA_PATH, 'foo') cpos = pyvista.plot(sphere, off_screen=OFF_SCREEN, screenshot=filename) filename = filename + ".png" # Ensure it added a PNG extension by default assert os.path.isfile(filename) # remove file os.remove(filename)
def test_plot(tmpdir): tmp_dir = tmpdir.mkdir("tmpdir2") filename = str(tmp_dir.join('tmp.png')) scalars = np.arange(sphere.n_points) cpos, img = pyvista.plot(sphere, off_screen=OFF_SCREEN, full_screen=True, text='this is a sphere', show_bounds=True, color='r', style='wireframe', line_width=10, scalars=scalars, flip_scalars=True, cmap='bwr', interpolate_before_map=True, screenshot=filename, return_img=True) assert isinstance(cpos, pyvista.CameraPosition) assert isinstance(img, np.ndarray) assert os.path.isfile(filename) filename = pathlib.Path(str(tmp_dir.join('tmp2.png'))) cpos = pyvista.plot(sphere, off_screen=OFF_SCREEN, screenshot=filename) # Ensure it added a PNG extension by default assert filename.with_suffix(".png").is_file() # test invalid extension with pytest.raises(ValueError): filename = pathlib.Path(str(tmp_dir.join('tmp3.foo'))) pyvista.plot(sphere, off_screen=OFF_SCREEN, screenshot=filename)
def test_volume_rendering(): # Really just making sure no errors are thrown vol = examples.load_uniform() vol.plot(off_screen=OFF_SCREEN, volume=True, opacity='linear') plotter = pyvista.Plotter(off_screen=OFF_SCREEN) plotter.add_volume(vol, opacity='sigmoid', cmap='jet', n_colors=15) plotter.show() # Now test MultiBlock rendering data = pyvista.MultiBlock( dict( a=examples.load_uniform(), b=examples.load_uniform(), c=examples.load_uniform(), d=examples.load_uniform(), )) data['a'].rename_array('Spatial Point Data', 'a') data['b'].rename_array('Spatial Point Data', 'b') data['c'].rename_array('Spatial Point Data', 'c') data['d'].rename_array('Spatial Point Data', 'd') data.plot( off_screen=OFF_SCREEN, volume=True, multi_colors=True, ) # Check that NumPy arrays work arr = vol["Spatial Point Data"].reshape(vol.dimensions) pyvista.plot(arr, off_screen=OFF_SCREEN, volume=True, opacity='linear')
def test_plot_pyvista_ndarray(sphere): # verify we can plot pyvista_ndarray pyvista.plot(sphere.points) plotter = pyvista.Plotter() plotter.add_points(sphere.points) plotter.add_points(sphere.points + 1) plotter.show()
def test_plot_list(): pyvista.plot([sphere, sphere_b], off_screen=OFF_SCREEN, style='points') pyvista.plot([sphere, sphere_b, sphere_c], off_screen=OFF_SCREEN, style='wireframe')
def test_fail_plot_table(): """Make sure tables cannot be plotted""" table = pyvista.Table(np.random.rand(50, 3)) with pytest.raises(TypeError): pyvista.plot(table) with pytest.raises(TypeError): plotter = pyvista.Plotter(off_screen=OFF_SCREEN) plotter.add_mesh(table)
def plot_3D(self, topography=True, notebook=True, **kwargs): if topography and self.mask is not None: new_block = self.block_model.copy() * self.mask new_block[np.where(new_block == 0)] = np.nan else: new_block = self.block_model.copy() cmap_type = kwargs.pop('cmap', 'YlOrRd') pyvista.plot(new_block, notebook=notebook, cmap=cmap_type, **kwargs)
def plot_pyvista(self, **kwargs): """Wrapper for `pyvista.plot`. Parameters ---------- **kwargs Extra keyword arguments passed to `pyvista.plot` """ pv.plot(self.to_meshio(), **kwargs)
def test_bad_keyword_arguments(): """Make sure bad keyword arguments raise an error""" mesh = examples.load_uniform() with pytest.raises(TypeError): pyvista.plot(mesh, foo=5, off_screen=OFF_SCREEN) with pytest.raises(TypeError): pyvista.plot(mesh, scalar=mesh.active_scalars_name, off_screen=OFF_SCREEN) with pytest.raises(TypeError): plotter = pyvista.Plotter(off_screen=OFF_SCREEN) plotter.add_mesh(mesh, scalar=mesh.active_scalars_name) plotter.show() with pytest.raises(TypeError): plotter = pyvista.Plotter(off_screen=OFF_SCREEN) plotter.add_mesh(mesh, foo="bad") plotter.show()
This allows for the "best of both worlds" programming special to Python due to its modularity. If there's some limitation of pyvista (or trimesh), then you can adapt your scripts to use the best features of more than one module. """ import pyvista as pv ############################################################################### # Wrap a point cloud composed of random points from numpy import numpy as np points = np.random.random((30, 3)) cloud = pv.wrap(points) pv.plot(cloud, scalars=points[:, 2], render_points_as_spheres=True, point_size=50, opacity=points[:, 0], cpos='xz') ############################################################################### # Wrap an instance of Trimesh import trimesh points = [[0, 0, 0], [0, 0, 1], [0, 1, 0]] faces = [[0, 1, 2]] tmesh = trimesh.Trimesh(points, faces=faces, process=False) mesh = pv.wrap(tmesh) print(mesh) ############################################################################### # Wrap an instance of vtk.vtkPolyData
"""Quickly quickly check if VTK off screen plotting works.""" import pyvista import sys from pyvista.plotting import system_supports_plotting print('system_supports_plotting', system_supports_plotting()) pyvista.OFF_SCREEN = True sphere = pyvista.Sphere() pyvista.plot(sphere)
def test_plot_invalid_style(): with pytest.raises(Exception): pyvista.plot(sphere, style='not a style')
(599088.1433822059, 3982089.287834022, -11965.14728669936), (0.3738545892415734, 0.244312810377319, 0.8947312427698892), ] p.show() ############################################################################### contours = voi.contour(np.arange(5, 55, 5)) contours ############################################################################### contours.plot(cmap="nipy_spectral", opacity=0.15) ############################################################################### roi = [*voi.bounds[0:4], *aoi.bounds[4:6]] aoi_clipped = aoi.clip_box(roi, invert=False) pv.plot([aoi, pv.Box(roi).outline()], cpos="xy") ############################################################################### p = pv.Plotter(window_size=np.array([1024, 768]) * 2) # Add all the data we want to see p.add_mesh(contours, cmap="nipy_spectral", opacity=0.15) p.add_mesh(gebco_a, color="#ff0000") p.add_mesh(gebco_b, color="#ff0000") p.add_mesh(aoi_clipped, cmap="coolwarm", opacity=0.7) # Add a title p.add_text("Vent and Magma Chambers\nDamavand Volcano, Alborz") # A nice perspective p.camera_position = [
while (t < T): t += dt r = solver.solve(u) print(f"Step {int(t/dt)}: num iterations: {r[0]}") u.vector.copy(result=u0.vector) file.write_function(u.sub(0), t) # Update the plot window if have_pyvista: p.add_text(f"time: {t:.2e}", font_size=12, name="timelabel") grid.point_arrays["u"] = u.sub(0).compute_point_values().real p.app.processEvents() file.close() # Within the time stepping loop, the nonlinear problem is solved by # calling :py:func:`solver.solve(problem,u.vector)<dolfinx.cpp.NewtonSolver.solve>`, # with the new solution vector returned in :py:func:`u.vector<dolfinx.cpp.Function.vector>`. # The solution vector associated with ``u`` is copied to ``u0`` at the # end of each time step, and the ``c`` component of the solution # (the first component of ``u``) is then written to file. # Update ghost entries and plot if have_pyvista: u.x.scatter_forward() grid.point_arrays["u"] = u.sub(0).compute_point_values().real screenshot = None if pv.OFF_SCREEN: screenshot = "u.png" pv.plot(grid, show_edges=True, screenshot=screenshot)
import pyvista as pv import numpy as np from pyvista import examples nx = 20 ny = 15 nz = 5 origin = (-(nx - 1) * 0.1 / 2, -(ny - 1) * 0.1 / 2, -(nz - 1) * 0.1 / 2) mesh = pv.UniformGrid((nx, ny, nz), (.1, .1, .1), origin) x = mesh.points[:, 0] y = mesh.points[:, 1] z = mesh.points[:, 2] vectors = np.empty((mesh.n_points, 3)) vectors[:, 0] = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z) vectors[:, 1] = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z) vectors[:, 2] = (np.sqrt(3.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) * np.sin(np.pi * z)) mesh['vectors'] = vectors ############################################################################### stream, src = mesh.streamlines('vectors', return_source=True, terminal_speed=0.0, n_points=200, source_radius=0.1) ############################################################################### cpos = [(1.2, 1.2, 1.2), (-0.0, -0.0, -0.0), (0.0, 0.0, 1.0)] # mesh.plot(screenshot="test1.png") pv.plot(stream, cpos=cpos)
"""Quickly check if VTK off screen plotting works.""" import pyvista from pyvista.plotting import system_supports_plotting print("system_supports_plotting", system_supports_plotting()) pyvista.OFF_SCREEN = True pyvista.plot(pyvista.Sphere())
def test_plot_invalid_style(): with pytest.raises(ValueError): pyvista.plot(sphere, style='not a style')
def plot_element_result(self, rnum, result_type, item_index, in_element_coord_sys=False, **kwargs): """Plot an element result. Parameters ---------- rnum : int Result number. result_type : str Element data type to retrieve. - EMS: misc. data - ENF: nodal forces - ENS: nodal stresses - ENG: volume and energies - EGR: nodal gradients - EEL: elastic strains - EPL: plastic strains - ECR: creep strains - ETH: thermal strains - EUL: euler angles - EFX: nodal fluxes - ELF: local forces - EMN: misc. non-sum values - ECD: element current densities - ENL: nodal nonlinear data - EHC: calculated heat generations - EPT: element temperatures - ESF: element surface stresses - EDI: diffusion strains - ETB: ETABLE items - ECT: contact data - EXY: integration point locations - EBA: back stresses - ESV: state variables - MNL: material nonlinear record item_index : int Index of the data item for each node within the element. in_element_coord_sys : bool, optional Returns the results in the element coordinate system. Default False and will return the results in the global coordinate system. Returns ------- nnum : np.ndarray ANSYS node numbers result : np.ndarray Array of result data Examples -------- # >>> rst.plot_element_result( """ # check result exists result_type = result_type.upper() if not self.available_results[result_type]: raise ValueError('Result %s is not available in this result file' % result_type) if result_type not in ELEMENT_INDEX_TABLE_KEYS: raise ValueError('Result "%s" is not an element result' % result_type) bsurfs = [] for result in self._results: bsurf = result._extract_surface_element_result( rnum, result_type, item_index, in_element_coord_sys) bsurfs.append(bsurf) desc = self.available_results.description[result_type].capitalize() kwargs.setdefault('stitle', desc) return pv.plot(bsurfs, scalars='_scalars', **kwargs)
import numpy as np import pyvista # make a uniform 3d point field x = np.linspace(0, 10, 10) # 10 points uniformly spread y = np.linspace(0, 1, 2) # 2 points uniformly spread z = np.linspace(0, 1, 2) # 2 points uniformly spread # create a mesh xx, yy, zz = np.meshgrid(x, y, z) centers = np.vstack((xx.ravel(), yy.ravel(), zz.ravel())).T # make a bunch of spheres spheres = [pyvista.Sphere(center=center) for center in centers] # let's define array d which will contain count values # for each point of the grid. Now array d is filled with random # integer values d = np.random.randint(low=1, high=100, size=842) # plot it with smooth shading because we can pyvista.plot(spheres, smooth_shading=True, scalars=d)
def test_plot_list(): pyvista.plot([sphere, sphere_b, sphere_c], style='wireframe', before_close_callback=verify_cache_image)