Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import numpy as np
import pytest
import vtk
import pyvista
from pyvista import examples
from pyvista.plotting import system_supports_plotting
beam = pyvista.UnstructuredGrid(examples.hexbeamfile)
# create structured grid
x = np.arange(-10, 10, 2)
y = np.arange(-10, 10, 2)
z = np.arange(-10, 10, 2)
x, y, z = np.meshgrid(x, y, z)
sgrid = pyvista.StructuredGrid(x, y, z)
try:
test_path = os.path.dirname(os.path.abspath(__file__))
test_data_path = os.path.join(test_path, 'test_data')
except:
test_path = '/home/alex/afrl/python/source/pyvista/tests'
def test_volume():
assert beam.volume > 0.0
@pytest.mark.skipif(not system_supports_plotting(), reason="Requires system to support plotting")
def test_struct_example():
# create and plot structured grid
grid = examples.load_structured()
def test_quality_struct():
x = np.arange(-10, 10, 5)
y = np.arange(-10, 10, 5)
z = np.arange(-10, 10, 5)
x, y, z = np.meshgrid(x, y, z)
grid = pv.StructuredGrid(x, y, z)
qual = pyansys.quality(grid)
assert (qual == 1).all()
def test_project_points_to_plane():
# Define a simple Gaussian surface
n = 20
x = np.linspace(-200,200, num=n) + np.random.uniform(-5, 5, size=n)
y = np.linspace(-200,200, num=n) + np.random.uniform(-5, 5, size=n)
xx, yy = np.meshgrid(x, y)
A, b = 100, 100
zz = A*np.exp(-0.5*((xx/b)**2. + (yy/b)**2.))
poly = pyvista.StructuredGrid(xx, yy, zz).extract_geometry()
poly['elev'] = zz.ravel(order='f')
# Test the filter
projected = poly.project_points_to_plane(origin=poly.center, normal=(0,0,1))
assert np.allclose(projected.points[:,-1], poly.center[-1])
projected = poly.project_points_to_plane(normal=(0,1,1))
assert projected.n_points
def test_creatingagifmovie(tmpdir, off_screen=True):
if tmpdir:
filename = str(tmpdir.mkdir("tmpdir").join('wave.gif'))
else:
filename = '/tmp/wave.gif'
x = np.arange(-10, 10, 0.25)
y = np.arange(-10, 10, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
# Create and structured surface
grid = pyvista.StructuredGrid(x, y, z)
# Make copy of points
pts = grid.points.copy()
# Start a plotter object and set the scalars to the Z height
plotter = pyvista.Plotter(off_screen=off_screen)
plotter.add_mesh(grid, scalars=z.ravel())
plotter.show(auto_close=False)
# Open a gif
plotter.open_gif(filename)
# Update Z and write a frame for each updated position
nframe = 5
for phase in np.linspace(0, 2*np.pi, nframe + 1)[:nframe]:
z = np.sin(r + phase)
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkStructuredGrid())
multi = pyvista.MultiBlock(multi)
assert isinstance(multi, pyvista.MultiBlock)
assert multi.n_blocks == 2
assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid)
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkStructuredGrid())
multi = pyvista.MultiBlock(multi, deep=True)
assert isinstance(multi, pyvista.MultiBlock)
assert multi.n_blocks == 2
assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid)
# Test nested structure
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkImageData())
nested = vtk.vtkMultiBlockDataSet()
nested.SetBlock(0, vtk.vtkUnstructuredGrid())
nested.SetBlock(1, vtk.vtkStructuredGrid())
multi.SetBlock(2, nested)
# Wrap the nested structure
multi = pyvista.MultiBlock(multi)
assert isinstance(multi, pyvista.MultiBlock)
assert multi.n_blocks == 3
assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
assert isinstance(multi.GetBlock(1), pyvista.UniformGrid)
assert isinstance(multi.GetBlock(2), pyvista.MultiBlock)
def test_load_structured_bad_filename():
with pytest.raises(Exception):
pyvista.StructuredGrid('not a file')
filename = os.path.join(test_path, 'test_grid.py')
with pytest.raises(Exception):
grid = pyvista.StructuredGrid(filename)
# Duplicate the first point to close loop
X = np.append(X, X[0])
Y = np.append(Y, Y[0])
# Make all the nodes in the grid
xx = np.array([X] * z_resolution).ravel()
yy = np.array([Y] * z_resolution).ravel()
dz = height / z_resolution
zz = np.empty(yy.size)
zz = np.full((X.size, z_resolution), dz)
zz *= np.arange(z_resolution)
zz = zz.ravel(order='f')
# Create the grid
grid = pyvista.StructuredGrid()
grid.points = np.c_[xx, yy, zz]
grid.dimensions = [nr, theta_resolution+1, z_resolution]
# Orient properly in user direction
vx = np.array([0., 0., 1.])
if not np.allclose(vx, direction):
direction /= np.linalg.norm(direction)
vx -= vx.dot(direction) * direction
vx /= np.linalg.norm(vx)
vy = np.cross(direction, vx)
rmtx = np.array([vx, vy, direction])
grid.points = grid.points.dot(rmtx)
# Translate to given center
grid.points -= np.array(grid.center)
grid.points += np.array(center)
def to_pyvista(self):
try:
import pyvista as pv
import vtk
except:
raise PyVistaImportError()
mesh = pv.StructuredGrid(*self.meshgrid)
mesh.point_arrays.update(self.point_data_dict)
mesh.cell_arrays.update(self.cell_data_dict)
return mesh
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
def load_structured():
""" Loads a simple StructuredGrid """
x = np.arange(-10, 10, 0.25)
y = np.arange(-10, 10, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
return pyvista.StructuredGrid(x, y, z)