Point-Based 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')
../_images/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 hard-coded 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')
../_images/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()
../_images/beam.gif

You can also render the beam as as a wire-frame object:

# Animate plot as a wire-frame
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()
../_images/beam_wireframe.gif

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 sub-selects points along the y-z 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')
../_images/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')
../_images/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

cells

returns a pointer to the cells as a numpy object

celltypes

Get the cell types array

offset

Get Cell Locations Array

Methods

linear_copy([deep])

Returns a copy of the input unstructured grid containing only linear cells.

save(filename[, binary])

Writes 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 empy 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

returns a pointer to the cells as a numpy object

property celltypes

Get the cell types array

linear_copy(deep=False)

Returns a copy of the input 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

pyvista.UnstructuredGrid

property offset

Get Cell Locations Array

save(filename, binary=True)

Writes 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

dimensions

Returns a length 3 tuple of the grid’s dimensions

x

The X coordinates of all points

y

The Y coordinates of all points

z

The Z coordinates of all points

Methods

save(filename[, binary])

Writes a structured grid to disk.

class pyvista.StructuredGrid(*args, **kwargs)

Bases: vtkCommonDataModelPython.vtkStructuredGrid, pyvista.core.pointset.PointGrid

Extends 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

Returns a length 3 tuple of the grid’s dimensions

save(filename, binary=True)

Writes 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

The X coordinates of all points

property y

The Y coordinates of all points

property z

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

volume

Computes volume by extracting the external surface and computing interior volume

Methods

plot_curvature([curv_type])

Plots 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)

Plots 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

Computes volume by extracting the external surface and computing interior volume