PointBased Grids¶
Structured and unstructured grids are designed to manage cells whereas a
polydata object manage surfaces. The vtk.UnstructuredGrid
is derived class
from vtk.vtkUnstructuredGrid
designed to make creation, array access, and
plotting more straightforward than using the vtk object. The same goes with a
vtk.StructuredGrid
.
Unstructured Grid Creation¶
See Creating an Unstructured Surface for an example on how to create an unstructured grid from NumPy arrays.
Empty Object¶
An unstructured grid can be initialized with:
import pyvista as pv
grid = pv.UnstructuredGrid()
This creates an empty grid, and is not useful until points and cells are added
to it. VTK points and cells can be added with SetPoints
and SetCells
,
but the inputs to these need to be vtk.vtkCellArray
and vtk.vtkPoints
objects, which need to be populated with values. Grid creation is simplified
by initializing the grid directly from numpy arrays as in the following section.
Loading from File¶
Unstructured grids can be loaded from a vtk file.
import pyvista as pv
from pyvista import examples
grid = pv.UnstructuredGrid(examples.hexbeamfile)
Structured Grid Creation¶
Empty Object¶
A structured grid can be initialized with:
import pyvista as pv
grid = pv.StructuredGrid()
This creates an empty grid, and is not useful until points are added to it.
Creating from Numpy Arrays¶
A structured grid can be created directly from numpy arrays. This is useful when creating a grid from scratch or copying it from another format.
Also see Creating a Structured Surface for an example on creating a structured grid from NumPy arrays.
import pyvista as pv
import numpy as np
x = np.arange(10, 10, 0.25)
y = np.arange(10, 10, 0.25)
z = np.arange(10, 10, 0.25)
x, y, z = np.meshgrid(x, y, z)
# create the unstructured grid directly from the numpy arrays and plot
grid = pv.StructuredGrid(x, y, z)
grid.plot(show_edges=True, screenshot='structured_cube.png')
Loading from File¶
Structured grids can be loaded from a vtk
file.
grid = pv.StructuredGrid(filename)
Plotting Grids¶
This example shows how you can load an unstructured grid from a vtk
file and
create a plot and gif movie by updating the plotting object.
# Load module and example file
import pyvista as pv
from pyvista import examples
import numpy as np
# Load example beam grid
grid = pv.UnstructuredGrid(examples.hexbeamfile)
# Create fictitious displacements as a function of Z location
d = np.zeros_like(grid.points)
d[:, 1] = grid.points[:, 2]**3/250
# Displace original grid
grid.points += d
A simple plot can be created by using:
grid.plot(scalars=d[:, 1], stitle='Y Displacement')
A more complex plot can be created using:
# Store Camera position. This can be obtained manually by getting the
# output of grid.plot()
# it's hardcoded in this example
cpos = [(11.915126303095157, 6.11392754955802, 3.6124956735471914),
(0.0, 0.375, 2.0),
(0.42546442225230097, 0.9024244135964158, 0.06789847673314177)]
# plot this displaced beam
plotter = pv.Plotter()
plotter.add_mesh(grid, scalars=d[:, 1], stitle='Y Displacement',
rng=[d.max(), d.max()])
plotter.add_axes()
plotter.camera_position = cpos
plotter.show(screenshot='beam.png')
You can animate the motion of the beam by updating the positions and scalars of the grid copied to the plotting object. First you have to setup the plotting object:
plotter = pv.Plotter()
plotter.add_mesh(grid, scalars=d[:, 1], stitle='Y Displacement',
show_edges=True, rng=[d.max(), d.max()],
interpolate_before_map=True)
plotter.add_axes()
plotter.camera_position = cpos
You then open the render window by plotting before opening movie file. Set auto_close to False so the plotter does not close automatically. Disabling interactive means the plot will automatically continue without waiting for the user to exit the window.
plotter.show(interactive=False, auto_close=False, window_size=[800, 600])
# open movie file. A mp4 file can be written instead. Requires moviepy
plotter.open_gif('beam.gif') # or beam.mp4
# Modify position of the beam cyclically
pts = grid.points.copy() # unmodified points
for phase in np.linspace(0, 2*np.pi, 20):
plotter.update_coordinates(pts + d*np.cos(phase))
plotter.update_scalars(d[:, 1]*np.cos(phase))
plotter.write_frame()
# Close the movie and plot
plotter.close()
You can also render the beam as as a wireframe object:
# Animate plot as a wireframe
plotter = pv.Plotter()
plotter.add_mesh(grid, scalars=d[:, 1], stitle='Y Displacement', show_edges=True,
rng=[d.max(), d.max()], interpolate_before_map=True,
style='wireframe')
plotter.add_axes()
plotter.camera_position = cpos
plotter.show(interactive=False, auto_close=False, window_size=[800, 600])
#plotter.OpenMovie('beam.mp4')
plotter.open_gif('beam_wireframe.gif')
for phase in np.linspace(0, 2*np.pi, 20):
plotter.update_coordinates(grid.points + d*np.cos(phase), render=False)
plotter.update_scalars(d[:, 1]*np.cos(phase), render=False)
plotter.render()
plotter.write_frame()
plotter.close()
Adding Labels to a Plot¶
Labels can be added to a plot using the add_point_labels
function within the
Plotter
object. The following example loads the included example beam,
generates a plotting class, and subselects points along the yz plane and
labels their coordinates. add_point_labels
requires that the number of
labels matches the number of points, and that labels is a list containing one
entry per point. The code automatically converts each item in the list to a
string.
# Load module and example file
import pyvista as pv
from pyvista import examples
# Load example beam file
grid = pv.UnstructuredGrid(examples.hexbeamfile)
# Create plotting class and add the unstructured grid
plotter = pv.Plotter()
plotter.add_mesh(grid, show_edges=True, color='tan')
# Add labels to points on the yz plane (where x == 0)
points = grid.points
mask = points[:, 0] == 0
plotter.add_point_labels(points[mask], points[mask].tolist())
plotter.camera_position = [
(1.4643015810492384, 1.5603923627830638, 3.16318236536270),
(0.05268120500967251, 0.639442034364944, 1.204095304165153),
(0.2364061044392675, 0.9369426029156169, 0.25739213784721)]
plotter.show(screenshot='labels0.png')
This example is similar and shows how labels can be combined with a scalar bar to show the exact value of certain points.
# Label the Z position
values = grid.points[:, 2]
# Create plotting class and add the unstructured grid
plotter = pv.Plotter(notebook=False)
# color mesh according to z value
plotter.add_mesh(grid, scalars=values, stitle='Z Position', show_edges=True)
# Add labels to points on the yz plane (where x == 0)
mask = grid.points[:, 0] == 0
plotter.add_point_labels(points[mask], values[mask].tolist(), font_size=24)
# add some text to the plot
plotter.add_text('Example showing plot labels')
plotter.view_vector((6, 3, 4), (0.,1., 0.))
plotter.show(screenshot='labels1.png')
pv.Unstructured Grid Class Methods¶
The following is a description of the methods available to a
pv.UnstructuredGrid
object. It inherits all methods from the original
vtk
object, vtk.vtkUnstructuredGrid.
Attributes
Return a pointer to the cells as a numpy object. 

Get the cell types array. 

Get Cell Locations Array. 
Methods

Return a copy of the unstructured grid containing only linear cells. 

Write an unstructured grid to disk. 

class
pyvista.
UnstructuredGrid
(*args, **kwargs)¶ Bases:
vtkCommonDataModelPython.vtkUnstructuredGrid
,pyvista.core.pointset.PointGrid
,pyvista.core.filters.UnstructuredGridFilters
Extends the functionality of a vtk.vtkUnstructuredGrid object.
Can be initialized by the following:
Creating an empty grid
From a vtk.vtkPolyData object
From cell, offset, and node arrays
From a file
Examples
>>> import pyvista >>> from pyvista import examples >>> import vtk
>>> # Create an empty grid >>> grid = pyvista.UnstructuredGrid()
>>> # Copy a vtkUnstructuredGrid >>> vtkgrid = vtk.vtkUnstructuredGrid() >>> grid = pyvista.UnstructuredGrid(vtkgrid) # Initialize from a vtkUnstructuredGrid
>>> # from arrays >>> #grid = pyvista.UnstructuredGrid(offset, cells, cell_type, nodes, deep=True)
>>> # From a string filename >>> grid = pyvista.UnstructuredGrid(examples.hexbeamfile)

property
cells
¶ Return a pointer to the cells as a numpy object.

property
celltypes
¶ Get the cell types array.

linear_copy
(deep=False)¶ Return a copy of the unstructured grid containing only linear cells.
Converts the following cell types to their linear equivalents.
VTK_QUADRATIC_TETRA –> VTK_TETRA
VTK_QUADRATIC_PYRAMID –> VTK_PYRAMID
VTK_QUADRATIC_WEDGE –> VTK_WEDGE
VTK_QUADRATIC_HEXAHEDRON –> VTK_HEXAHEDRON
 Parameters
deep (bool) – When True, makes a copy of the points array. Default False. Cells and cell types are always copied.
 Returns
grid – UnstructuredGrid containing only linear cells.
 Return type

property
offset
¶ Get Cell Locations Array.

save
(filename, binary=True)¶ Write an unstructured grid to disk.
 Parameters
filename (str) – Filename of grid to be written. The file extension will select the type of writer to use. “.vtk” will use the legacy writer, while “.vtu” will select the VTK XML writer.
binary (bool, optional) – Writes as a binary file by default. Set to False to write ASCII.
Notes
Binary files write much faster than ASCII, but binary files written on one system may not be readable on other systems. Binary can be used only “.vtk” files
pv.Structured Grid Class Methods¶
The following is a description of the methods available to a
pv.StructuredGrid
object. It inherits all methods from the original
vtk
object, vtk.vtkStructuredGrid.
Attributes
Return a length 3 tuple of the grid’s dimensions. 

Return the X coordinates of all points. 

Return the Y coordinates of all points. 

Return the Z coordinates of all points. 
Methods

Hide cells without deleting them. 

Write a structured grid to disk. 

class
pyvista.
StructuredGrid
(*args, **kwargs)¶ Bases:
vtkCommonDataModelPython.vtkStructuredGrid
,pyvista.core.pointset.PointGrid
Extend the functionality of a vtk.vtkStructuredGrid object.
Can be initialized in several ways:
Create empty grid
Initialize from a vtk.vtkStructuredGrid object
Initialize directly from the point arrays
See _from_arrays in the documentation for more details on initializing from point arrays
Examples
>>> import pyvista >>> import vtk >>> import numpy as np
>>> # Create empty grid >>> grid = pyvista.StructuredGrid()
>>> # Initialize from a vtk.vtkStructuredGrid object >>> vtkgrid = vtk.vtkStructuredGrid() >>> grid = pyvista.StructuredGrid(vtkgrid)
>>> # Create from NumPy arrays >>> xrng = np.arange(10, 10, 2) >>> yrng = np.arange(10, 10, 2) >>> zrng = np.arange(10, 10, 2) >>> x, y, z = np.meshgrid(xrng, yrng, zrng) >>> grid = pyvista.StructuredGrid(x, y, z)

property
dimensions
¶ Return a length 3 tuple of the grid’s dimensions.

hide_cells
(ind)¶ Hide cells without deleting them.
Hides cells by setting the ghost_cells array to HIDDEN_CELL.
 Parameters
ind (iterable) – List or array of cell indices to be hidden. The array can also be a boolean array of the same size as the number of cells.
Examples
Hide part of the middle of a structured surface.
>>> import pyvista as pv >>> import numpy as np >>> x = np.arange(10, 10, 0.25) >>> y = np.arange(10, 10, 0.25) >>> z = 0 >>> x, y, z = np.meshgrid(x, y, z) >>> grid = pv.StructuredGrid(x, y, z) >>> grid.hide_cells(range(79*30, 79*50))

save
(filename, binary=True)¶ Write a structured grid to disk.
 Parameters
filename (str) – Filename of grid to be written. The file extension will select the type of writer to use. “.vtk” will use the legacy writer, while “.vts” will select the VTK XML writer.
binary (bool, optional) – Writes as a binary file by default. Set to False to write ASCII.
Notes
Binary files write much faster than ASCII, but binary files written on one system may not be readable on other systems. Binary can be used only with the legacy writer.

property
x
¶ Return the X coordinates of all points.

property
y
¶ Return the Y coordinates of all points.

property
z
¶ Return the Z coordinates of all points.
Methods in Common with Structured and Unstructured Grids¶
These methods are in common to both pv.StructuredGrid
and
pv.UnstructuredGrid
objects.
Attributes
Compute the volume of the point grid. 
Methods

Plot the curvature of the external surface of the grid. 

class
pyvista.
PointGrid
(*args, **kwargs)¶ Bases:
pyvista.core.pointset.PointSet
Class in common with structured and unstructured grids.

plot_curvature
(curv_type='mean', **kwargs)¶ Plot the curvature of the external surface of the grid.
 Parameters
curv_type (str, optional) –
One of the following strings indicating curvature types
mean
gaussian
maximum
minimum
**kwargs (optional) – Optional keyword arguments. See help(pyvista.plot)
 Returns
cpos – Camera position, focal point, and view up. Used for storing and setting camera view.
 Return type
list

property
volume
¶ Compute the volume of the point grid.
This extracts the external surface and computes the interior volume
