Chapter 4. Using MayaVi from Python

Table of Contents
An example
Useful Python Modules

If you have installed MayaVi from the sources and are not using a binary release, then you can use MayaVi as a Python module. This chapter details how you can use MayaVi as a Python module. If you are looking for a powerful, interactive, cross-platform Python interpreter you might be interested in IPython.

An example

Its very easy using MayaVi as a Python module. Thanks to Tkinter, it is also possible to use MayaVi from the Python interpreter. This means that one can script MayaVi! This is a pretty powerful and useful feature. To illustrate using MayaVi as a module and its scriptability, we will consider a few simple examples where the user generates some data and a VTK file and then uses MayaVi to visualize the data.

Generating some data

>>> # generate the data.
>>> from Numeric import *
>>> import scipy
>>> x = (arange(50.0)-25)/2.0
>>> y = (arange(50.0)-25)/2.0
>>> r = sqrt(x[:,NewAxis]**2+y**2)
>>> z = 5.0*scipy.special.j0(r)  # Bessel function of order 0
>>> # now dump the data to a VTK file.
>>> import pyvtk
>>> # Flatten the 2D array data as per VTK's requirements.
>>> z1 = reshape(transpose(z), (-1,))
>>> point_data = pyvtk.PointData(pyvtk.Scalars(z1))
>>> grid = pyvtk.StructuredPoints((50,50, 1), (-12.5, -12.5, 0), (0.5, 0.5, 1))
>>> data = pyvtk.VtkData(grid, point_data)
>>> data.tofile('/tmp/test.vtk')

The above example uses the Numeric , SciPy and pyVtk modules. Please note the step where z1 is obtained from z. This step is done to correctly flatten the two dimensional array z. The problem with Numeric arrays and VTK data is that you have to be careful of the order of the data points. The way VTK reads data (for all the data formats that have a structure) is something like this:

>>> for k in range(n_z):
>>>     for j in range(n_y):
>>>         for i in range(n_x):
>>>             read_line()

This means that the x values must be iterated over first, the y values next and the z values last. If you simply flatten the 2D numeric array then this will not happen properly. By using reshape(transpose(z), (-1,)) we ensure that the data points are specified in the correct order. The next step is to visualize the generated data.