Example #1
0
def test_multi_block_set_get_ers():
    """This puts all of the example data objects into a a MultiBlock container"""
    multi = MultiBlock()
    # Set the number of blocks
    multi.n_blocks = 6
    assert multi.GetNumberOfBlocks() == 6  # Check that VTK side registered it
    assert multi.n_blocks == 6  # Check pyvista side registered it
    # Add data to the MultiBlock
    data = ex.load_rectilinear()
    multi[1, 'rect'] = data
    # Make sure number of blocks is constant
    assert multi.n_blocks == 6
    # Check content
    assert isinstance(multi[1], RectilinearGrid)
    for i in [0, 2, 3, 4, 5]:
        assert multi[i] is None
    # Check the bounds
    assert multi.bounds == list(data.bounds)
    multi[5] = ex.load_uniform()
    multi.set_block_name(5, 'uni')
    multi.set_block_name(5, None)  # Make sure it doesn't get overwritten
    assert isinstance(multi.get(5), UniformGrid)
    # Test get by name
    assert isinstance(multi['uni'], UniformGrid)
    assert isinstance(multi['rect'], RectilinearGrid)
    # Test the del operator
    del multi[0]
    assert multi.n_blocks == 5
    # Make sure the rect grid was moved up
    assert isinstance(multi[0], RectilinearGrid)
    assert multi.get_block_name(0) == 'rect'
    assert multi.get_block_name(2) == None
    # test del by name
    del multi['uni']
    assert multi.n_blocks == 4
    # test the pop operator
    pop = multi.pop(0)
    assert isinstance(pop, RectilinearGrid)
    assert multi.n_blocks == 3
    assert multi.get_block_name(10) is None
    with pytest.raises(KeyError):
        _ = multi.get_index_by_name('foo')
    # allow Sequence but not Iterable in setitem
    with pytest.raises(TypeError):
        multi[{1, 'foo'}] = data
Example #2
0
def test_clip_box():
    for i, dataset in enumerate(DATASETS):
        clp = dataset.clip_box(invert=True)
        assert clp is not None
        assert isinstance(clp, pyvista.UnstructuredGrid)
    dataset = examples.load_airplane()
    # test length 3 bounds
    result = dataset.clip_box(bounds=(900, 900, 200), invert=False)
    dataset = examples.load_uniform()
    result = dataset.clip_box(bounds=0.5)
    with pytest.raises(AssertionError):
        dataset.clip_box(bounds=(
            5,
            6,
        ))
    # Now test composite data structures
    output = COMPOSITE.clip_box(invert=False)
    assert output.n_blocks == COMPOSITE.n_blocks
Example #3
0
def test_threshold_percent():
    percents = [25, 50, [18.0, 85.0], [19.0, 80.0], 0.70]
    inverts = [False, True, False, True, False]
    # Only test data sets that have arrays
    for i, dataset in enumerate(DATASETS[0:3]):
        thresh = dataset.threshold_percent(percent=percents[i],
                                           invert=inverts[i])
        assert thresh is not None
        assert isinstance(thresh, pyvista.UnstructuredGrid)
    dataset = examples.load_uniform()
    result = dataset.threshold_percent(0.75, scalars='Spatial Cell Data')
    with pytest.raises(ValueError):
        result = dataset.threshold_percent(20000)
    with pytest.raises(ValueError):
        result = dataset.threshold_percent(0.0)
    # allow Sequence but not Iterable
    with pytest.raises(TypeError):
        dataset.threshold_percent({18.0, 85.0})
Example #4
0
def test_image_properties():
    mesh = examples.load_uniform()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.show(auto_close=False)  # DO NOT close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.show()  # close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()
Example #5
0
def test_multi_block_copy():
    multi = pyvista.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_globe())
    # Now check everything
    newobj = multi.copy()
    assert multi.n_blocks == 5 == newobj.n_blocks
    assert id(multi[0]) != id(newobj[0])
    assert id(multi[-1]) != id(newobj[-1])
    # Now check shallow
    newobj = multi.copy(deep=False)
    assert multi.n_blocks == 5 == newobj.n_blocks
    assert id(multi[0]) == id(newobj[0])
    assert id(multi[-1]) == id(newobj[-1])
    return
Example #6
0
def test_camera():
    plotter = pyvista.Plotter()
    plotter.add_mesh(sphere)
    plotter.view_isometric()
    plotter.reset_camera()
    plotter.view_xy()
    plotter.view_xz()
    plotter.view_yz()
    plotter.add_mesh(examples.load_uniform(), reset_camera=True, culling=True)
    plotter.view_xy(True)
    plotter.view_xz(True)
    plotter.view_yz(True)
    plotter.show(before_close_callback=verify_cache_image)
    plotter.camera_position = None

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.camera.zoom(5)
    plotter.camera.up = 0, 0, 10
    plotter.show()
Example #7
0
def test_select_enclosed_points():
    mesh = examples.load_uniform()
    surf = pyvista.Sphere(center=mesh.center, radius=mesh.length / 2.)
    result = mesh.select_enclosed_points(surf)
    assert isinstance(result, type(mesh))
    assert 'SelectedPoints' in result.array_names
    assert result.n_arrays == mesh.n_arrays + 1
    # Now check non-closed surface
    mesh = pyvista.ParametricEllipsoid(
        0.2,
        0.7,
        0.7,
    )
    surf = mesh.copy()
    surf.rotate_x(90)
    result = mesh.select_enclosed_points(surf, check_surface=False)
    assert isinstance(result, type(mesh))
    assert 'SelectedPoints' in result.array_names
    assert result.n_arrays == mesh.n_arrays + 1
    with pytest.raises(RuntimeError):
        result = mesh.select_enclosed_points(surf, check_surface=True)
Example #8
0
def test_multi_block_append():
    """This puts all of the example data objects into a a MultiBlock container"""
    multi = pyvista.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], pyvista.PolyData)
    assert isinstance(multi[1], pyvista.PolyData)
    assert isinstance(multi[2], pyvista.UniformGrid)
    assert isinstance(multi[3], pyvista.PolyData)
    assert isinstance(multi[4], pyvista.RectilinearGrid)
    # Now overwrite a block
    multi[4] = pyvista.Sphere()
    assert isinstance(multi[4], pyvista.PolyData)
    multi[4] = vtk.vtkUnstructuredGrid()
    assert isinstance(multi[4], pyvista.UnstructuredGrid)
def test_clip_box():
    for i, dataset in enumerate(DATASETS):
        clp = dataset.clip_box(invert=True)
        assert clp is not None
        assert isinstance(clp, pyvista.UnstructuredGrid)
    dataset = examples.load_airplane()
    # test length 3 bounds
    result = dataset.clip_box(bounds=(900, 900, 200), invert=False)
    dataset = examples.load_uniform()
    result = dataset.clip_box(bounds=0.5)
    assert result.n_cells
    with pytest.raises(AssertionError):
        dataset.clip_box(bounds=(5, 6,))
    # Test with a poly data box
    mesh = examples.load_airplane()
    box = pyvista.Cube(center=(0.9e3, 0.2e3, mesh.center[2]),
                       x_length=500, y_length=500, z_length=500)
    box.rotate_z(33)
    result = mesh.clip_box(box, invert=False)
    assert result.n_cells
    result = mesh.clip_box(box, invert=True)
    assert result.n_cells
Example #10
0
def test_opacity_by_array():
    mesh = examples.load_uniform()
    opac = mesh['Spatial Point Data'] / mesh['Spatial Point Data'].max()
    # Test with opacity array
    mesh['opac'] = opac
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(
        mesh,
        scalars='Spatial Point Data',
        opacity='opac',
    )
    p.show()
    # Test with uncertainty array (transparency)
    mesh['unc'] = opac
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh,
               scalars='Spatial Point Data',
               opacity='unc',
               use_transparency=True)
    p.show()
    # Test using mismatched arrays
    with pytest.raises(ValueError):
        p = pyvista.Plotter(off_screen=OFF_SCREEN)
        p.add_mesh(
            mesh,
            scalars='Spatial Cell Data',
            opacity='unc',
        )
        p.show()
    # Test with user defined transfer function
    opacities = [0, 0.2, 0.9, 0.2, 0.1]
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(
        mesh,
        scalars='Spatial Point Data',
        opacity=opacities,
    )
    p.show()
def test_slice_along_line():
    model = examples.load_uniform()
    n = 5
    x = y = z = np.linspace(model.bounds[0], model.bounds[1], num=n)
    points = np.c_[x,y,z]
    spline = pyvista.Spline(points, n)
    slc = model.slice_along_line(spline)
    assert slc.n_points > 0
    slc = model.slice_along_line(spline, contour=True)
    assert slc.n_points > 0
    # Now check a simple line
    a = [model.bounds[0], model.bounds[2], model.bounds[4]]
    b = [model.bounds[1], model.bounds[3], model.bounds[5]]
    line = pyvista.Line(a, b, resolution=10)
    slc = model.slice_along_line(line)
    assert slc.n_points > 0
    # Now check a bad input
    a = [model.bounds[0], model.bounds[2], model.bounds[4]]
    b = [model.bounds[1], model.bounds[2], model.bounds[5]]
    line2 = pyvista.Line(a, b, resolution=10)
    line = line2.cast_to_unstructured_grid().merge(line.cast_to_unstructured_grid())
    with pytest.raises(AssertionError):
        slc = model.slice_along_line(line)
Example #12
0
def test_elevation():
    dataset = examples.load_uniform()
    # Test default params
    elev = dataset.elevation()
    assert 'Elevation' in elev.array_names
    assert 'Elevation' == elev.active_scalars_name
    assert elev.get_data_range() == (dataset.bounds[4], dataset.bounds[5])
    # test vector args
    c = list(dataset.center)
    t = list(c)  # cast so it does not point to `c`
    t[2] = dataset.bounds[-1]
    elev = dataset.elevation(low_point=c, high_point=t)
    assert 'Elevation' in elev.array_names
    assert 'Elevation' == elev.active_scalars_name
    assert elev.get_data_range() == (dataset.center[2], dataset.bounds[5])
    # Test not setting active
    elev = dataset.elevation(set_active=False)
    assert 'Elevation' in elev.array_names
    assert 'Elevation' != elev.active_scalars_name
    # Set use a range by scalar name
    elev = dataset.elevation(scalar_range='Spatial Point Data')
    assert 'Elevation' in elev.array_names
    assert 'Elevation' == elev.active_scalars_name
    assert dataset.get_data_range('Spatial Point Data') == (
        elev.get_data_range('Elevation'))
    # Set use a user defined range
    elev = dataset.elevation(scalar_range=[1.0, 100.0])
    assert 'Elevation' in elev.array_names
    assert 'Elevation' == elev.active_scalars_name
    assert elev.get_data_range('Elevation') == (1.0, 100.0)
    # test errors
    with pytest.raises(TypeError):
        elev = dataset.elevation(scalar_range=0.5)
    with pytest.raises(ValueError):
        elev = dataset.elevation(scalar_range=[1, 2, 3])
    with pytest.raises(TypeError):
        elev = dataset.elevation(scalar_range={1, 2})
Example #13
0
def test_image_properties():
    mesh = examples.load_uniform()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.show(auto_close=False)  # DO NOT close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.store_image = True
    assert p.store_image is True
    p.show()  # close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()

    # gh-920
    rr = np.array([[-0.5, -0.5, 0], [-0.5, 0.5, 1], [0.5, 0.5, 0],
                   [0.5, -0.5, 1]])
    tris = np.array([[3, 0, 2, 1], [3, 2, 0, 3]])
    mesh = pyvista.PolyData(rr, tris)
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, color=True)
    p.renderer.camera_position = (0., 0., 1.)
    p.renderer.ResetCamera()
    p.enable_parallel_projection()
    assert p.renderer.camera_set
    p.show(interactive=False, auto_close=False)
    img = p.get_image_depth(fill_value=0.)
    rng = np.ptp(img)
    assert 0.3 < rng < 0.4, rng  # 0.3313504 in testing
    p.close()
Example #14
0
def test_elevation():
    dataset = examples.load_uniform()
    # Test default params
    elev = dataset.elevation()
    assert 'Elevation' in elev.scalar_names
    assert 'Elevation' == elev.active_scalar_name
    assert elev.get_data_range() == (dataset.bounds[4], dataset.bounds[5])
    # test vector args
    c = list(dataset.center)
    t = list(c)  # cast so it doesnt point to `c`
    t[2] = dataset.bounds[-1]
    elev = dataset.elevation(low_point=c, high_point=t)
    assert 'Elevation' in elev.scalar_names
    assert 'Elevation' == elev.active_scalar_name
    assert elev.get_data_range() == (dataset.center[2], dataset.bounds[5])
    # Test not setting active
    elev = dataset.elevation(set_active=False)
    assert 'Elevation' in elev.scalar_names
    assert 'Elevation' != elev.active_scalar_name
    # Set use a range by scalar name
    elev = dataset.elevation(scalar_range='Spatial Point Data')
    assert 'Elevation' in elev.scalar_names
    assert 'Elevation' == elev.active_scalar_name
    assert dataset.get_data_range('Spatial Point Data') == (
        elev.get_data_range('Elevation'))
    # Set use a user defined range
    elev = dataset.elevation(scalar_range=[1.0, 100.0])
    assert 'Elevation' in elev.scalar_names
    assert 'Elevation' == elev.active_scalar_name
    assert elev.get_data_range('Elevation') == (1.0, 100.0)
    # test errors
    with pytest.raises(RuntimeError):
        elev = dataset.elevation(scalar_range=0.5)
    # Now test composite data structures
    output = COMPOSITE.elevation()
    assert output.n_blocks == COMPOSITE.n_blocks
def test_multi_block_list_index():
    multi = pyvista.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_globe())
    # Now check everything
    indices = [0, 3, 4]
    sub = multi[indices]
    assert len(sub) == len(indices)
    for i, j in enumerate(indices):
        assert id(sub[i]) == id(multi[j])
        assert sub.get_block_name(i) == multi.get_block_name(j)
    # check list of key names
    multi = pyvista.MultiBlock()
    multi["foo"] = pyvista.Sphere()
    multi["goo"] = pyvista.Box()
    multi["soo"] = pyvista.Cone()
    indices = ["goo", "foo"]
    sub = multi[indices]
    assert len(sub) == len(indices)
    assert isinstance(sub["foo"], pyvista.PolyData)
Example #16
0
def test_point_data_to_cell_data():
    data = examples.load_uniform()
    foo = data.point_data_to_cell_data()
    assert foo.n_arrays == 2
    assert len(foo.point_arrays.keys()) == 0
    _ = data.ptc()
Example #17
0
import os
import sys
import platform

import numpy as np
import pytest

import pyvista
from pyvista import examples

DATASETS = [
    examples.load_uniform(),  # UniformGrid
    examples.load_rectilinear(),  # RectilinearGrid
    examples.load_hexbeam(),  # UnstructuredGrid
    examples.load_airplane(),  # PolyData
    examples.load_structured(),  # StructuredGrid
]
normals = ['x', 'y', '-z', (1, 1, 1), (3.3, 5.4, 0.8)]

COMPOSITE = pyvista.MultiBlock(DATASETS, deep=True)

skip_py2_nobind = pytest.mark.skipif(
    int(sys.version[0]) < 3, reason="Python 2 doesn't support binding methods")

skip_windows = pytest.mark.skipif(os.name == 'nt',
                                  reason="Flaky Windows tests")
skip_mac = pytest.mark.skipif(platform.system() == 'Darwin',
                              reason="Flaky Mac tests")


@pytest.fixture(scope='module')
Example #18
0
def test_smooth():
    data = examples.load_uniform()
    vol = data.threshold_percent(30)
    surf = vol.extract_geometry()
    smooth = surf.smooth()
    assert np.any(smooth.points)
Example #19
0
def test_cast_uniform_to_structured():
    grid = examples.load_uniform()
    structured = grid.cast_to_structured_grid()
    assert structured.n_points == grid.n_points
    assert structured.n_arrays == grid.n_arrays
    assert structured.bounds == grid.bounds
Example #20
0
def test_warp_by_scalar():
    data = examples.load_uniform()
    warped = data.warp_by_scalar()
    assert data.n_points == warped.n_points
Example #21
0
import pathlib

import numpy as np
import pytest

import pyvista
from pyvista import examples

beam = pyvista.UnstructuredGrid(examples.hexbeamfile)
airplane = examples.load_airplane().cast_to_unstructured_grid()
uniform = examples.load_uniform().cast_to_unstructured_grid()


@pytest.mark.parametrize("mesh_in", [beam, airplane, uniform])
def test_meshio(mesh_in, tmpdir):
    # Save and read reference mesh using meshio
    filename = tmpdir.mkdir("tmpdir").join("test_mesh.vtk")
    pyvista.save_meshio(filename, mesh_in)
    mesh = pyvista.read_meshio(filename)

    # Assert mesh is still the same
    assert np.allclose(mesh_in.points, mesh.points)
    if (mesh_in.celltypes == 11).all():
        cells = mesh_in.cells.reshape((mesh_in.n_cells, 9))[:,[0,1,2,4,3,5,6,8,7]].ravel()
        assert np.allclose(cells, mesh.cells)
    else:
        assert np.allclose(mesh_in.cells, mesh.cells)
    for k, v in mesh_in.point_arrays.items():
        assert np.allclose(v, mesh.point_arrays[k.replace(" ", "_")])
    for k, v in mesh_in.cell_arrays.items():
        assert np.allclose(v, mesh.cell_arrays[k.replace(" ", "_")])
Example #22
0
import pyvista as pv
from pyvista import examples

################################################################################
# Suppose you extract a volumetric subset of a dataset that has roughly defined
# edges. Perhaps you'd like a smooth representation of that model region. This
# can be achieved by extracting the bounding surface of the volume and applying
# a :func:`pyvista.PolyData.smooth` filter.
#
# The below code snippet loads a sample roughly edged volumetric dataset:

# Vector to view rough edges
cpos = [-2, 5, 3]

# Load dataset
data = examples.load_uniform()
# Extract a rugged volume
vol = data.threshold_percent(30, invert=1)
vol.plot(show_edges=True, cpos=cpos)

################################################################################
# Extract the outer surface of the volume using the
# :func:`pyvista.DataSetFilters.extract_geometry` filter and then apply the
# smoothing filter:

# Get the out surface as PolyData
surf = vol.extract_geometry()
# Smooth the surface
smooth = surf.smooth()
smooth.plot(show_edges=True, cpos=cpos)
Example #23
0
"""
Rotate Points
~~~~~~~~~~~~~

This example will demonstrate how to rotate points in a `vtkPolyData` object around some origin on the XY plane.

THis example demos :class:`PVGeo.filters.RotatePoints`

"""
from pyvista import examples
from PVGeo.filters import RotatePoints

###############################################################################
# Get :class:`pyvista.PolyData` sample input to rotate
mesh = examples.load_uniform().cell_centers()
mesh.plot()

###############################################################################
# Use the filter:
rotated = RotatePoints(angle=33.3).apply(mesh)
rotated.plot()
Example #24
0
def test_triangulate():
    data = examples.load_uniform()
    tri = data.triangulate()
    assert isinstance(tri, pyvista.UnstructuredGrid)
    assert np.any(tri.cells)
Example #25
0
def test_delaunay_3d():
    data = examples.load_uniform().threshold_percent(30)
    result = data.delaunay_3d()
    assert np.any(result.points)
Example #26
0
def test_cast_uniform_to_rectilinear():
    grid = examples.load_uniform()
    rectilinear = grid.cast_to_rectilinear_grid()
    assert rectilinear.n_points == grid.n_points
    assert rectilinear.n_arrays == grid.n_arrays
    assert rectilinear.bounds == grid.bounds
Example #27
0
def test_decimate_boundary():
    mesh = examples.load_uniform()
    boundary = mesh.decimate_boundary()
    assert boundary.n_points
Example #28
0
# use directly on the object. These filters include the following
# (see :ref:`filters_ref` for a complete list):
#
# * ``slice``: creates a single slice through the input dataset on a user defined plane
# * ``slice_orthogonal``: creates a ``MultiBlock`` dataset of three orthogonal slices
# * ``slice_along_axis``: creates a ``MultiBlock`` dataset of many slices along a specified axis
# * ``threshold``: Thresholds a dataset by a single value or range of values
# * ``threshold_percent``: Threshold by percentages of the scalar range
# * ``clip``: Clips the dataset by a user defined plane
# * ``outline_corners``: Outlines the corners of the data extent
# * ``extract_geometry``: Extract surface geometry
#
# To use these filters, call the method of your choice directly on your data
# object:

dataset = examples.load_uniform()
dataset.set_active_scalar('Spatial Point Data')

# Apply a threshold over a data range
threshed = dataset.threshold([100, 500])

outline = dataset.outline()

################################################################################
# And now there is a thresholded version of the input dataset in the new
# ``threshed`` object. To learn more about what keyword arguments are available to
# alter how filters are executed, print the docstring for any filter attached to
# PyVista objects with either ``help(dataset.threshold)`` or using ``shift+tab``
# in an IPython environment.
#
# We can now plot this filtered dataset along side an outline of the original
Example #29
0
def uniform():
    return examples.load_uniform()
Example #30
0
sphere = pv.Sphere()
plotter.add_mesh(sphere, scalars=sphere.points[:, 2])
plotter.add_scalar_bar("Z")
# plotter.add_axes()
plotter.add_axes(interactive=True)

plotter.subplot(1, 1)
plotter.add_text("Render Window 3", font_size=30)
plotter.add_mesh(pv.Cone(), color="g", show_edges=True)
plotter.show_bounds(all_edges=True)

# Display the window
plotter.show()

###############################################################################

plotter = pv.Plotter(shape=(1, 2))

# Note that the (0, 0) location is active by default
# load and plot an airplane on the left half of the screen
plotter.add_text("Airplane Example\n", font_size=30)
plotter.add_mesh(examples.load_airplane(), show_edges=False)

# load and plot the uniform data example on the right-hand side
plotter.subplot(0, 1)
plotter.add_text("Uniform Data Example\n", font_size=30)
plotter.add_mesh(examples.load_uniform(), show_edges=True)

# Display the window
plotter.show()