This page presents scripting Mayavi2 using the advanced, object-oriented API. Mayavi2 has recently acquired an easy-to-use, thought maybe not as powerful, scripting module: mlab. You are invited to refer to the section of Mayavi2 user guide.

Introduction

Here, you will be presented some examples of rendering scenes you can get with MayaVi2. You are advised to read Cookbook/MayaVi/ScriptingMayavi2 to understand what you see, although most examples given here are self-explanatory.

Please note that these examples are not up to date. The example gallery for the latest version of Mayavi can be found at http://enthought.github.com/mayavi/mayavi/auto/examples.html.

Example using IsoSurface Module (contour.py)

   1 #!/usr/bin/env mayavi2
   2 
   3 """This script demonstrates how one can script MayaVi and use its
   4 contour related modules.  Notice the magic line at the top.
   5 """
   6 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
   7 # Copyright (c) 2005-2007, Enthought, Inc.
   8 # License: BSD Style.
   9 
  10 # Standard library imports
  11 from os.path import join, dirname
  12 
  13 # Enthought library imports
  14 import enthought.mayavi
  15 from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
  16 from enthought.mayavi.filters.threshold import Threshold
  17 from enthought.mayavi.modules.outline import Outline
  18 from enthought.mayavi.modules.grid_plane import GridPlane
  19 from enthought.mayavi.modules.contour_grid_plane import ContourGridPlane
  20 from enthought.mayavi.modules.iso_surface import IsoSurface
  21 from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane
  22 
  23 
  24 def contour():
  25     """The script itself.  We needn't have defined a function but
  26     having a function makes this more reusable.
  27     """
  28     # 'mayavi' is always defined on the interpreter.
  29     # Create a new scene.
  30     mayavi.new_scene()
  31 
  32     # Read a VTK (old style) data file.
  33     r = VTKFileReader()
  34     r.initialize(join(dirname(enthought.mayavi.__file__),
  35                       'examples', 'data', 'heart.vtk'))
  36     mayavi.add_source(r)
  37 
  38     # Create an outline for the data.
  39     o = Outline()
  40     mayavi.add_module(o)
  41 
  42     # Create three simple grid plane modules.
  43     # First normal to 'x' axis.
  44     gp = GridPlane()
  45     mayavi.add_module(gp)
  46     # Second normal to 'y' axis.
  47     gp = GridPlane()
  48     mayavi.add_module(gp)
  49     gp.grid_plane.axis = 'y'
  50     # Third normal to 'z' axis.
  51     gp = GridPlane()
  52     mayavi.add_module(gp)
  53     gp.grid_plane.axis = 'z'
  54 
  55     # Create one ContourGridPlane normal to the 'x' axis.
  56     cgp = ContourGridPlane()
  57     mayavi.add_module(cgp)
  58     # Set the position to the middle of the data.
  59     cgp.grid_plane.position = 15
  60 
  61     # Another with filled contours normal to 'y' axis.
  62     cgp = ContourGridPlane()
  63     mayavi.add_module(cgp)
  64     # Set the axis and position to the middle of the data.
  65     cgp.grid_plane.axis = 'y'
  66     cgp.grid_plane.position = 15
  67     cgp.contour.filled_contours = True
  68 
  69     # An isosurface module.
  70     iso = IsoSurface(compute_normals=True)
  71     mayavi.add_module(iso)
  72     iso.contour.contours = [220.0]
  73 
  74     # An interactive scalar cut plane.
  75     cp = ScalarCutPlane()
  76     mayavi.add_module(cp)
  77     cp.implicit_plane.normal = 0,0,1
  78 
  79 
  80 if __name__ == '__main__':
  81     contour()

Example using Glyph Module (glyph.py)

   1 #!/usr/bin/env mayavi2
   2 
   3 """This script demonstrates the use of a VectorCutPlane, splitting the
   4 pipeline using a MaskPoints filter and then viewing the filtered data
   5 with the Glyph module.
   6 """
   7 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
   8 # Copyright (c) 2005-2007, Enthought, Inc.
   9 # License: BSD Style.
  10 
  11 # Standard library imports
  12 from os.path import join, dirname
  13 
  14 # Enthought library imports
  15 import enthought.mayavi
  16 from enthought.mayavi.sources.vtk_xml_file_reader import VTKXMLFileReader
  17 from enthought.mayavi.modules.outline import Outline
  18 from enthought.mayavi.modules.glyph import Glyph
  19 from enthought.mayavi.modules.vector_cut_plane import VectorCutPlane
  20 from enthought.mayavi.modules.vectors import Vectors
  21 from enthought.mayavi.filters.mask_points import MaskPoints
  22 
  23 
  24 def glyph():
  25     """The script itself.  We needn't have defined a function but
  26     having a function makes this more reusable.
  27     """
  28     # 'mayavi' is always defined on the interpreter.
  29     # Create a new VTK scene.
  30     mayavi.new_scene()
  31 
  32     # Read a VTK (old style) data file.
  33     r = VTKXMLFileReader()
  34     r.initialize(join(dirname(enthought.mayavi.__file__),
  35                       'examples', 'data', 'fire_ug.vtu'))
  36     mayavi.add_source(r)
  37 
  38     # Create an outline and a vector cut plane.
  39     mayavi.add_module(Outline())
  40 
  41     v = VectorCutPlane()
  42     mayavi.add_module(v)
  43     v.glyph.color_mode = 'color_by_scalar'
  44 
  45     # Now mask the points and show glyphs (we could also use
  46     # Vectors but glyphs are a bit more generic)
  47     m = MaskPoints()
  48     m.filter.set(on_ratio=10, random_mode=True)
  49     mayavi.add_filter(m)
  50 
  51     g = Glyph()
  52     mayavi.add_module(g)
  53     # Note that this adds the module to the filtered output.
  54     g.glyph.scale_mode = 'scale_by_vector'
  55     # Use arrows to view the scalars.
  56     g.glyph.glyph_source = g.glyph.glyph_list[1]
  57 
  58 
  59 if __name__ == '__main__':
  60     glyph()

Example without Mayavi2 UI (nongui.py)

   1 #!/usr/bin/env python
   2 
   3 """This script demonstrates how one can use the MayaVi framework
   4 without displaying MayaVi's UI.  Note: look at the end of this file to
   5 see how the non gui plugin is chosen instead of the default gui
   6 mayavi plugin.
   7 
   8 """
   9 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
  10 # Copyright (c) 2005, Enthought, Inc.
  11 # License: BSD Style.
  12 
  13 # On systems with multiple wx installations installed, pick one that works
  14 # with the libraries Mayavi depends on.
  15 try:
  16     import wxversion
  17     wxversion.ensureMinimal('2.6')
  18 except ImportError:
  19     pass
  20 
  21 # Standard library imports
  22 import sys
  23 from os.path import join, dirname
  24 
  25 # Enthought library imports
  26 from enthought.mayavi.app import Mayavi, NONGUI_PLUGIN_DEFINITIONS
  27 
  28 
  29 class MyApp(Mayavi):
  30     def run(self):
  31         """This is executed once the application GUI has started.
  32         *Make sure all other MayaVi specific imports are made here!*
  33         """
  34 
  35         # Various imports to do different things.
  36         from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
  37         from enthought.mayavi.modules.outline import Outline
  38         from enthought.mayavi.modules.axes import Axes
  39         from enthought.mayavi.modules.grid_plane import GridPlane
  40         from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget
  41         from enthought.mayavi.modules.text import Text
  42         from enthought.mayavi.modules.contour_grid_plane import ContourGridPlane
  43         from enthought.mayavi.modules.iso_surface import IsoSurface
  44 
  45         script = self.script
  46 
  47         # Create a new scene.
  48         script.new_scene()
  49 
  50         # Read a VTK (old style) data file.
  51         r = VTKFileReader()
  52         r.initialize('data/heart.vtk')
  53         r.initialize(join(dirname(__file__), 'data', 'heart.vtk'))
  54         script.add_source(r)
  55 
  56         # Put up some text.
  57         t = Text(text='MayaVi rules!', x_position=0.2, y_position=0.9, width=0.8)
  58         t.property.color = 1, 1, 0  # Bright yellow, yeah!
  59         script.add_module(t)
  60 
  61         # Create an outline for the data.
  62         o = Outline()
  63         script.add_module(o)
  64 
  65         # Create an axes for the data.
  66         a = Axes()
  67         script.add_module(a)
  68 
  69         # Create three simple grid plane modules.
  70         # First normal to 'x' axis.
  71         gp = GridPlane()
  72         script.add_module(gp)
  73         # Second normal to 'y' axis.
  74         gp = GridPlane()
  75         gp.grid_plane.axis = 'y'
  76         script.add_module(gp)
  77         # Third normal to 'z' axis.
  78         gp = GridPlane()
  79         script.add_module(gp)
  80         gp.grid_plane.axis = 'z'
  81 
  82         # Create one ImagePlaneWidget.
  83         ipw = ImagePlaneWidget()
  84         script.add_module(ipw)
  85         # Set the position to the middle of the data.
  86         ipw.ipw.slice_position = 16
  87 
  88         # Create one ContourGridPlane normal to the 'x' axis.
  89         cgp = ContourGridPlane()
  90         script.add_module(cgp)
  91         # Set the position to the middle of the data.
  92         cgp.grid_plane.axis = 'y'
  93         cgp.grid_plane.position = 15
  94 
  95         # An isosurface module.
  96         iso = IsoSurface(compute_normals=True)
  97         script.add_module(iso)
  98         iso.contour.contours = [200.0]
  99 
 100         # Set the view.
 101         s = script.engine.current_scene
 102         cam = s.scene.camera
 103         cam.azimuth(45)
 104         cam.elevation(15)
 105         s.render()
 106 
 107 
 108 if __name__ == '__main__':
 109     m = MyApp()
 110     # Note how we change the plugins that are loaded only here.
 111     m.main(plugin_defs=NONGUI_PLUGIN_DEFINITIONS)

Example with a 3D array as numerical source (numeric_source.py)

   1 #!/usr/bin/env mayavi2
   2 
   3 """This script demonstrates how to create a numpy array data and
   4 visualize it as image data using a few modules.
   5 
   6 """
   7 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
   8 # Copyright (c) 2005-2007, Enthought, Inc.
   9 # License: BSD Style.
  10 
  11 # Standard library imports
  12 import enthought.util.scipyx as scipy
  13 
  14 # Enthought library imports
  15 from enthought.mayavi.sources.array_source import ArraySource
  16 from enthought.mayavi.modules.outline import Outline
  17 from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget
  18 
  19 
  20 def make_data(dims=(128, 128, 128)):
  21     """Creates some simple array data of the given dimensions to test
  22     with."""
  23     np = dims[0]*dims[1]*dims[2]
  24 
  25     # Create some scalars to render.
  26     x, y, z = scipy.ogrid[-5:5:dims[0]*1j,-5:5:dims[1]*1j,-5:5:dims[2]*1j]
  27     x = x.astype('f')
  28     y = y.astype('f')
  29     z = z.astype('f')
  30 
  31     scalars = (scipy.sin(x*y*z)/(x*y*z))
  32     return scipy.transpose(scalars).copy() # This makes the data contiguous.
  33 
  34 
  35 def view_numpy():
  36     """Example showing how to view a 3D numpy array in mayavi2.
  37     """
  38     # 'mayavi' is always defined on the interpreter.
  39     mayavi.new_scene()
  40     # Make the data and add it to the pipeline.
  41     data = make_data()
  42     src = ArraySource(transpose_input_array=False)
  43     src.scalar_data = data
  44     mayavi.add_source(src)
  45     # Visualize the data.
  46     o = Outline()
  47     mayavi.add_module(o)
  48     ipw = ImagePlaneWidget()
  49     mayavi.add_module(ipw)
  50     ipw.module_manager.scalar_lut_manager.show_scalar_bar = True
  51 
  52     ipw_y = ImagePlaneWidget()
  53     mayavi.add_module(ipw_y)
  54     ipw_y.ipw.plane_orientation = 'y_axes'
  55 
  56 
  57 if __name__ == '__main__':
  58     view_numpy()

Example using Streamline Module (streamline.py)

   1 #!/usr/bin/env mayavi2
   2 """This script demonstrates how one can script MayaVi to display
   3 streamlines and an iso surface.
   4 """
   5 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
   6 # Copyright (c) 2005-2007, Enthought, Inc.
   7 # License: BSD Style.
   8 
   9 # Standard library imports
  10 from os.path import join, dirname
  11 
  12 # Enthought library imports
  13 from enthought.mayavi.sources.vtk_xml_file_reader import VTKXMLFileReader
  14 from enthought.mayavi.modules.outline import Outline
  15 from enthought.mayavi.modules.streamline import Streamline
  16 from enthought.mayavi.modules.iso_surface import IsoSurface
  17 
  18 
  19 def setup_data(fname):
  20     """Given a VTK XML file name `fname`, this creates a mayavi2
  21     reader for it and adds it to the pipeline.  It returns the reader
  22     created.
  23     """
  24     mayavi.new_scene()
  25     r = VTKXMLFileReader()
  26     r.initialize(fname)
  27     mayavi.add_source(r)
  28     return r
  29 
  30 def streamline():
  31     """Sets up the mayavi pipeline for the visualization.
  32     """
  33     # Create an outline for the data.
  34     o = Outline()
  35     mayavi.add_module(o)
  36 
  37     s = Streamline(streamline_type='tube')
  38     mayavi.add_module(s)
  39     s.stream_tracer.integration_direction = 'both'
  40     s.seed.widget.center = 3.5, 0.625, 1.25
  41     s.module_manager.scalar_lut_manager.show_scalar_bar = True
  42 
  43     i = IsoSurface()
  44     mayavi.add_module(i)
  45     i.contour.contours[0] = 550
  46     i.actor.property.opacity = 0.5
  47 
  48 
  49 if __name__ == '__main__':
  50     import enthought.mayavi
  51     fname = join(dirname(enthought.mayavi.__file__),
  52                  'examples', 'data', 'fire_ug.vtu')
  53     r = setup_data(fname)
  54     streamline()

Example using ImagePlaneWidget Module (test.py)

   1 #!/usr/bin/env python
   2 
   3 """This script demonstrates how one can script MayaVi, set its size,
   4 create a new VTK scene and create a few simple modules.
   5 
   6 """
   7 # Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
   8 # Copyright (c) 2005, Enthought, Inc.
   9 # License: BSD Style.
  10 
  11 # On systems with multiple wx installations installed, pick one that works
  12 # with the libraries Mayavi depends on.
  13 try:
  14     import wxversion
  15     wxversion.ensureMinimal('2.6')
  16 except ImportError:
  17     pass
  18 
  19 # Standard library imports
  20 import sys
  21 from os.path import join, dirname
  22 
  23 # Enthought library imports
  24 from enthought.mayavi.app import Mayavi
  25 
  26 
  27 class MyApp(Mayavi):
  28     def run(self):
  29         """This is executed once the application GUI has started.
  30         *Make sure all other MayaVi specific imports are made here!*
  31         """
  32         # Various imports to do different things.
  33         from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
  34         from enthought.mayavi.filters.threshold import Threshold
  35         from enthought.mayavi.modules.outline import Outline
  36         from enthought.mayavi.modules.axes import Axes
  37         from enthought.mayavi.modules.grid_plane import GridPlane
  38         from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget
  39         from enthought.mayavi.modules.text import Text
  40 
  41         script = self.script
  42         # Create a new scene.
  43         script.new_scene()
  44 
  45         # Read a VTK (old style) data file.
  46         r = VTKFileReader()
  47         r.initialize(join(dirname(__file__), 'data', 'heart.vtk'))
  48         script.add_source(r)
  49 
  50         # Put up some text.
  51         t = Text(text='MayaVi rules!', x_position=0.2,
  52                  y_position=0.9, width=0.8)
  53         t.property.color = 1, 1, 0  # Bright yellow, yeah!
  54         script.add_module(t)
  55 
  56         # Create an outline for the data.
  57         o = Outline()
  58         script.add_module(o)
  59 
  60         # Create an axes for the data.
  61         a = Axes()
  62         script.add_module(a)
  63 
  64         # Create an orientation axes for the scene.  This only works with
  65         # VTK-4.5 and above which is why we have the try block.
  66         try:
  67             from enthought.mayavi.modules.orientation_axes import OrientationAxes
  68         except ImportError:
  69             pass
  70         else:
  71             a = OrientationAxes()
  72             a.marker.set_viewport(0.0, 0.8, 0.2, 1.0)
  73             script.add_module(a)
  74 
  75         # Create three simple grid plane modules.
  76         # First normal to 'x' axis.
  77         gp = GridPlane()
  78         script.add_module(gp)
  79         # Second normal to 'y' axis.
  80         gp = GridPlane()
  81         gp.grid_plane.axis = 'y'
  82         script.add_module(gp)
  83         # Third normal to 'z' axis.
  84         gp = GridPlane()
  85         script.add_module(gp)
  86         gp.grid_plane.axis = 'z'
  87 
  88         # Create one ImagePlaneWidget.
  89         ipw = ImagePlaneWidget()
  90         script.add_module(ipw)
  91         # Set the position to the middle of the data.
  92         ipw.ipw.slice_position = 16
  93 
  94 
  95 
  96 if __name__ == '__main__':
  97     a = MyApp()
  98     a.main()

Example using mlab (surf_regular_mlab.py)

See also Cookbook/MayaVi/Surf for another way of doing this.

   1 #!/usr/bin/env mayavi2
   2 """Shows how to view data created by `enthought.tvtk.tools.mlab` with
   3 mayavi2.
   4 """
   5 
   6 # Author: Prabhu Ramachandran <prabhu@aero.iitb.ac.in>
   7 # Copyright (c) 2006-2007, Enthought Inc.
   8 # License: BSD Style.
   9 
  10 import numpy
  11 
  12 from enthought.tvtk.tools import mlab
  13 from enthought.mayavi.sources.vtk_data_source import VTKDataSource
  14 from enthought.mayavi.filters.warp_scalar import WarpScalar
  15 from enthought.mayavi.modules.outline import Outline
  16 from enthought.mayavi.modules.surface import Surface
  17 
  18 
  19 def f(x, y):
  20     """Some test function.
  21     """
  22     return numpy.sin(x*y)/(x*y)
  23 
  24 def make_data():
  25     """Make some test numpy data and create a TVTK data object from it
  26     that we will visualize.
  27     """
  28     x = numpy.arange(-7., 7.05, 0.1)
  29     y = numpy.arange(-5., 5.05, 0.05)
  30     s = mlab.SurfRegular(x, y, f)
  31     return s.data
  32 
  33 def add_data(tvtk_data):
  34     """Add a TVTK data object `tvtk_data` to the mayavi pipleine.
  35     """
  36     d = VTKDataSource()
  37     d.data = tvtk_data
  38     mayavi.add_source(d)
  39 
  40 def surf_regular():
  41     """Now visualize the data as done in mlab.
  42     """
  43     w = WarpScalar()
  44     mayavi.add_filter(w)
  45     o = Outline()
  46     s = Surface()
  47     mayavi.add_module(o)
  48     mayavi.add_module(s)
  49 
  50 
  51 if __name__ == '__main__':
  52     mayavi.new_scene()
  53     d = make_data()
  54     add_data(d)
  55     surf_regular()


CategoryCookbook

Cookbook/MayaVi/Examples (last edited 2011-04-18 16:21:00 by GaelVaroquaux)