def test_resample(): mesh = vtki.Sphere(center=(4.5, 4.5, 4.5), radius=4.5) data_to_probe = examples.load_uniform() result = mesh.sample(data_to_probe) name = 'Spatial Point Data' assert name in result.scalar_names assert isinstance(result, type(mesh))
def test_extract_largest(): mesh = sphere + vtki.Sphere(0.1, theta_resolution=5, phi_resolution=5) largest = mesh.extract_largest() assert largest.n_faces == sphere.n_faces mesh.extract_largest(inplace=True) assert mesh.n_faces == sphere.n_faces
def test_vtk_tetrahedralize(): sphere = vtki.Sphere(theta_resolution=10, phi_resolution=10) tet = tetgen.TetGen(sphere) tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5) grid = tet.grid assert grid.n_cells assert grid.n_points
def test_multi_renderers(): plotter = vtki.Plotter(shape=(2, 2), off_screen=OFF_SCREEN) loc = (0, 0) plotter.add_text('Render Window 0', loc=loc, font_size=30) sphere = vtki.Sphere() plotter.add_mesh(sphere, loc=loc, scalars=sphere.points[:, 2]) plotter.add_scalar_bar('Z', vertical=True) loc = (0, 1) plotter.add_text('Render Window 1', loc=loc, font_size=30) plotter.add_mesh(vtki.Cube(), loc=loc, show_edges=True) loc = (1, 0) plotter.add_text('Render Window 2', loc=loc, font_size=30) plotter.add_mesh(vtki.Arrow(), color='y', loc=loc, show_edges=True) plotter.subplot(1, 1) plotter.add_text('Render Window 3', loc=loc, font_size=30) plotter.add_mesh(vtki.Cone(), color='g', loc=loc, show_edges=True, backface_culling=True) plotter.add_bounding_box(render_lines_as_tubes=True, line_width=5) plotter.show_bounds(all_edges=True) plotter.update_bounds_axes() plotter.plot()
def test_background_plotter_export_vtkjs(qtbot, tmpdir): plotter = vtki.BackgroundPlotter(show=False, title='Testing Window') plotter.add_mesh(vtki.Sphere()) filename = str(tmpdir.mkdir("tmpdir").join('tmp')) dlg = plotter._qt_export_vtkjs(show=False) dlg.selectFile(filename) dlg.accept() plotter.close() assert os.path.isfile(filename + '.vtkjs')
def test_screenshot(): plotter = vtki.Plotter(off_screen=True) plotter.add_mesh(vtki.Sphere()) img = plotter.screenshot(transparent_background=True) assert np.any(img) img_again = plotter.screenshot() assert np.any(img_again) # checking if plotter closes ref = proxy(plotter) plotter.close() try: ref except: raise Exception('Plotter did not close')
def test_glyph(): for i, dataset in enumerate(datasets): result = dataset.glyph() assert result is not None assert isinstance(result, vtki.PolyData) # Test different options for glyph filter sphere = vtki.Sphere(radius=3.14) # make cool swirly pattern vectors = np.vstack((np.sin(sphere.points[:, 0]), np.cos(sphere.points[:, 1]), np.cos(sphere.points[:, 2]))).T # add and scale sphere.vectors = vectors * 0.3 sphere.point_arrays['foo'] = np.random.rand(sphere.n_points) sphere.point_arrays['arr'] = np.ones(sphere.n_points) result = sphere.glyph(scale='arr') result = sphere.glyph(scale='arr', orient='Normals', factor=0.1)
def test_background_plotting_camera(qtbot): plotter = vtki.BackgroundPlotter(show=False, title='Testing Window') plotter.add_mesh(vtki.Sphere()) cpos = [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)] plotter.camera_position = cpos plotter.save_camera_position() plotter.camera_position = [(0.0, 0.0, 3.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)] # load existing position plotter.saved_camera_menu.actions()[0].trigger() assert plotter.camera_position == cpos plotter.clear_camera_positions() assert not len(plotter.saved_camera_menu.actions()) plotter.close()
def test_arrows(): sphere = vtki.Sphere(radius=3.14) # make cool swirly pattern vectors = np.vstack((np.sin(sphere.points[:, 0]), np.cos(sphere.points[:, 1]), np.cos(sphere.points[:, 2]))).T # add and scale assert sphere.active_vectors is None sphere.vectors = vectors * 0.3 assert np.allclose(sphere.active_vectors, vectors * 0.3) assert np.allclose(sphere.vectors, vectors * 0.3) assert sphere.active_vectors_info[1] == '_vectors' arrows = sphere.arrows assert isinstance(arrows, vtki.PolyData) assert np.any(arrows.points) sphere.set_active_vectors('_vectors') sphere.active_vectors_name == '_vectors'
def test_background_plotting_axes_scale(qtbot): sphere = vtki.Sphere() plotter = vtki.BackgroundPlotter(show=False, title='Testing Window') plotter.add_mesh(sphere) assert np.any(plotter.mesh.points) dlg = plotter.scale_axes_dialog(show=False) value = 2.0 dlg.x_slider_group.value = value assert plotter.scale[0] == value dlg.x_slider_group.spinbox.setValue(-1) assert dlg.x_slider_group.value == 0 dlg.x_slider_group.spinbox.setValue(1000.0) assert dlg.x_slider_group.value < 100 plotter._last_update_time = 0.0 plotter.update_app_icon() assert plotter.quit() is None
def test_multi_block_append(): """This puts all of the example data objects into a a MultiBlock container""" multi = vtki.MultiBlock() # Add examples multi.append(ex.load_ant()) multi.append(ex.load_sphere()) multi.append(ex.load_uniform()) multi.append(ex.load_airplane()) multi.append(ex.load_rectilinear()) # Now check everything assert multi.n_blocks == 5 assert multi.bounds is not None assert isinstance(multi[0], vtki.PolyData) assert isinstance(multi[1], vtki.PolyData) assert isinstance(multi[2], vtki.UniformGrid) assert isinstance(multi[3], vtki.PolyData) assert isinstance(multi[4], vtki.RectilinearGrid) # Now overwrite a block multi[4] = vtki.Sphere() assert isinstance(multi[4], vtki.PolyData) multi[4] = vtk.vtkUnstructuredGrid() assert isinstance(multi[4], vtki.UnstructuredGrid)
def functional_tet_example(): sphere = vtki.Sphere(theta_resolution=10, phi_resolution=10) tet = tetgen.TetGen(sphere) tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5) grid = tet.grid assert grid.n_cells assert grid.n_points cells = grid.cells.reshape(-1, 5)[:, 1:] cell_center = grid.points[cells].mean(1) # extract cells below the 0 xy plane mask = cell_center[:, 2] < 0 cell_ind = mask.nonzero()[0] subgrid = grid.extract_cells(cell_ind) # plot this subgrid.plot(scalars=subgrid.quality, stitle='quality', cmap='bwr', flip_scalars=True) # advanced plotting plotter = vtki.Plotter() plotter.set_background('w') plotter.add_mesh(subgrid, 'lightgrey', lighting=True) plotter.add_mesh(grid, 'r', 'wireframe') plotter.add_legend([[' Input Mesh ', 'r'], [' Tesselated Mesh ', 'black']]) plotter.show() plotter = vtki.Plotter() plotter.set_background('w') plotter.add_mesh(grid, 'r', 'wireframe') plotter.plot(auto_close=False, interactive_update=True) for i in range(500): single_cell = grid.extract_cells([i]) plotter.add_mesh(single_cell) plotter.update() plotter.close()
""" Create a MP4 Movie ~~~~~~~~~~~~~~~~~~ Create an animated MP4 movie of a rendering scene """ import vtki import numpy as np filename = 'sphere-shrinking.mp4' mesh = vtki.Sphere() mesh.cell_arrays['data'] = np.random.random(mesh.n_cells) plotter = vtki.Plotter() # Open a movie file plotter.open_movie(filename) # Add initial mesh plotter.add_mesh(mesh, scalars='data', clim=[0, 1]) # Add outline for shrinking reference plotter.add_mesh(mesh.outline_corners()) # Render and do NOT close plotter.plot(auto_close=False) # Run through each frame plotter.write_frame() # write initial data # Update scalars on each frame
def test_background_plotting_orbit(qtbot): plotter = vtki.BackgroundPlotter(show=False, title='Testing Window') plotter.add_mesh(vtki.Sphere()) # perfrom the orbit: plotter.orbit_on_path(bkg=False, step=0.0) plotter.close()
def test_axes(): plotter = vtki.Plotter(off_screen=True) plotter.add_axes() plotter.add_mesh(vtki.Sphere()) plotter.plot()
from vtki import examples from vtki.plotting import running_xserver NO_PLOTTING = not running_xserver() try: if os.environ['ALLOW_PLOTTING'] == 'True': NO_PLOTTING = False except KeyError: pass if __name__ != '__main__': OFF_SCREEN = 'pytest' in sys.modules else: OFF_SCREEN = False sphere = vtki.Sphere() sphere_b = vtki.Sphere(1.0) sphere_c = vtki.Sphere(2.0) @pytest.mark.skipif(NO_PLOTTING, reason="Requires X11") def test_plot(tmpdir): try: filename = str(tmpdir.mkdir("tmpdir").join('tmp.png')) except: filename = '/tmp/tmp.png' scalars = np.arange(sphere.n_points) cpos, img = vtki.plot(sphere, off_screen=OFF_SCREEN, full_screen=True,
def test_sphere(): surf = vtki.Sphere() assert np.any(surf.points) assert np.any(surf.faces)
(-0.036117608696067414, 0.07352368982670517, 0.996639245352271)] p.show(auto_close=False) # p.export_vtkjs(gdc19.EXPORT_PATH.format('figure-05')) p.screenshot('figure-05.png') p.close() ############################################################################### # Figure 6 # ++++++++ p = vtki.Plotter() fig_1(p) loc = proposed.points[0] # add_well_traj_proposed(p) loc[-1] = 1.8e3 s = vtki.Sphere(radius=40, center=loc) p.add_mesh(s, label='Proposed Well', color=WELL_COLOR) p.camera_position = [(335111.21558935504, 4262955.412897479, 10111.108956611326), (335111.21558935504, 4262955.412897479, 150.0), (0.0, 1.0, 0.0)] p.show_grid() p.add_legend(bcolor=legend_color, border=True, ) cpos = p.show(auto_close=False) # p.export_vtkjs(gdc19.EXPORT_PATH.format('figure-06')) p.screenshot('figure-06.png') p.close() cpos
Geometric Objects ~~~~~~~~~~~~~~~~~ The "Hello, world!" of VTK """ import vtki ################################################################################ # This runs through several of the available geomoetric objects available in VTK # which ``vtki`` provides simple conveinance methods for generating. # # Let's run through creating a few geometric objects! cyl = vtki.Cylinder() arrow = vtki.Arrow() sphere = vtki.Sphere() plane = vtki.Plane() line = vtki.Line() box = vtki.Box() cone = vtki.Cone() poly = vtki.Polygon() disc = vtki.Disc() ################################################################################ # Now let's plot them all in one window p = vtki.Plotter(shape=(3, 3)) # Top row p.subplot(0,0) p.add_mesh(cyl, color='tan', show_edges=True) p.subplot(0,1)
""" Ray Tracing ~~~~~~~~~~~ Single line segment ray tracing for PolyData objects. """ # Use built-in sphere and test against a single ray import vtki # Create source to ray trace sphere = vtki.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 = vtki.Line(start, stop) intersection = vtki.PolyData(points) # Render the result p = vtki.Plotter() p.add_mesh(sphere, show_edges=True, opacity=0.5, color='w', lighting=False,
~~~~~~~~~~~~~~~~~~~~ Resample one mesh's point/cell arrays onto another meshes nodes. """ ############################################################################### # This example will resample a volumetric mesh's scalar data onto the surface # of a sphere contained in that volume. # sphinx_gallery_thumbnail_number = 1 import vtki from vtki import examples import numpy as np ############################################################################### # Querry a grids points onto a sphere mesh = vtki.Sphere(center=(4.5, 4.5, 4.5), radius=4.5) data_to_probe = examples.load_uniform() ############################################################################### # Plot the two datasets p = vtki.Plotter() p.add_mesh(mesh, color=True) p.add_mesh(data_to_probe, opacity=0.5) p.show() ############################################################################### # Run the algorithm and plot the result result = mesh.sample(data_to_probe) # Plot result name = 'Spatial Point Data'
import os from math import pi import pytest import numpy as np import vtki from vtki import examples from vtki.plotting import running_xserver radius = 0.5 sphere = vtki.Sphere(radius, theta_resolution=10, phi_resolution=10) sphere_shifted = vtki.Sphere(center=[0.5, 0.5, 0.5], theta_resolution=10, phi_resolution=10) dense_sphere = vtki.Sphere(radius, theta_resolution=100, phi_resolution=100) try: test_path = os.path.dirname(os.path.abspath(__file__)) test_data_path = os.path.join(test_path, 'test_data') except: test_data_path = '/home/alex/afrl/python/source/vtki/tests/test_data' stl_test_file = os.path.join(test_data_path, 'sphere.stl') ply_test_file = os.path.join(test_data_path, 'sphere.ply') vtk_test_file = os.path.join(test_data_path, 'sphere.vtk') test_files = [stl_test_file, ply_test_file, vtk_test_file]
# Make a geometric obhect to use as the glyph geom = vtki.Arrow() # This could be any dataset # Perform the glyph glyphs = grid.glyph(orient='vec', scale='mag', factor=0.8, geom=geom) # plot using the plotting class p = vtki.Plotter() p.add_mesh(glyphs) p.show() ################################################################################ # Another approach is to load the vectors directly to the grid object and then # access the :attr:`vtki.Common.arrows` property. sphere = vtki.Sphere(radius=3.14) # make cool swirly pattern vectors = np.vstack((np.sin(sphere.points[:, 0]), np.cos(sphere.points[:, 1]), np.cos(sphere.points[:, 2]))).T # add and scale sphere.vectors = vectors * 0.3 # plot just the arrows sphere.arrows.plot() ################################################################################ # plot the arrows and the sphere p = vtki.Plotter()
def test_load_arrays(): sphere = vtki.Sphere() v = sphere.points f = sphere.faces.reshape(-1, 4)[:, 1:] tet = tetgen.TetGen(v, f)
def add_sphere(self): sphere = vtki.Sphere() self.vtk_widget.add_mesh(sphere) self.vtk_widget.reset_camera()
# # We can now plot this filtered dataset along side an outline of the original # dataset p = vtki.Plotter() p.add_mesh(outline, color='k') p.add_mesh(threshed) p.camera_position = [-2, 5, 3] p.show() ################################################################################ # What about other filters? Let's collect a few filter results and compare them: contours = dataset.contour() slices = dataset.slice_orthogonal() glyphs = dataset.glyph(factor=1e-3, geom=vtki.Sphere()) p = vtki.Plotter(shape=(2, 2)) # Show the theshold p.add_mesh(outline, color='k') p.add_mesh(threshed, show_scalar_bar=False) p.camera_position = [-2, 5, 3] # Show the contour p.subplot(0, 1) p.add_mesh(outline, color='k') p.add_mesh(contours, show_scalar_bar=False) p.camera_position = [-2, 5, 3] # Show the slices p.subplot(1, 0) p.add_mesh(outline, color='k') p.add_mesh(slices, show_scalar_bar=False)
""" Clearing a Mesh or the Entire Plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This example demonstrates how to remove elements from a scene. """ # sphinx_gallery_thumbnail_number = 3 import vtki plotter = vtki.Plotter() actor = plotter.add_mesh(vtki.Sphere()) plotter.remove_actor(actor) plotter.show() ################################################################################ # Clearing the entire plotting window: plotter = vtki.Plotter() plotter.add_mesh(vtki.Sphere()) plotter.add_mesh(vtki.Plane()) plotter.clear() # clears all actors plotter.show() ################################################################################ # Or you can give any actor a ``name`` when adding it and if an actor is added # with that same name at a later time, it will replace the previous actor: plotter = vtki.Plotter()
def test_background_plotting(qtbot): sphere = vtki.Sphere() plotter = vtki.BackgroundPlotter(show=False) plotter.add_mesh(sphere) assert np.any(plotter.mesh.points) assert plotter.close()
def test_get_cell_scalar_fail(): sphere = vtki.Sphere() with pytest.raises(RuntimeError): sphere._cell_scalar(name=None)
def test_camera_position(): plotter = vtki.Plotter(off_screen=OFF_SCREEN) plotter.add_mesh(vtki.Sphere()) plotter.show() assert isinstance(plotter.camera_position, list)