Mayavi 应用程序的使用

分节概述

本节主要聚焦于Mayavi2应用程序的交互使用。文章所提到的操作,也都可以从Mayavi脚本实现。

但如果您仅仅是希望快速开始用时Mayavi,把它作为一个类似于Matlab风格的绘图库,您可以直接跳至`simple-scripting-with-mlab`章节,然后再回到这里加深理解。

学习Mayavi的案例指导

您可以使用Mayavi2的应用程序熟悉mayavi,就像这样,从命令行中启动 “mayavi2”。

$ mayavi2

对于Window系统您可以双击安装“mayavi2.exe”可执行文件(它通常放置在“Python2XScripts”目录),或者,如果您安装了python(x,y)或者EPD,可以使用开始菜单进入。

启动Mayavi之后,您可以通过调整交互界面的大小获得一个舒适的布局。这些设定会成为mayavi的默认布局。关于界面UI的更多细节可以参考该章节:ref:general-layout-of-ui

我们将给出几个案例教您如何使用Mayavi应用程序。在案例演示之前,需要获得一些测试用的数据。以下两个案例都是用了mayavi自身附带的数据。在mayavi的根目录中,这些数据可以在``examples/data``目录中获取。如果这些数据包没有安装,可以通过以下地址进行下载:https://github.com/enthought/mayavi

UI 的总体布局

当`mayavi2`应用程序启动之后,它会提供一个用户界面,如下图所示。

Figure of Mayavi's initial UI window.

UI 界面的特点将用以下几个章节进行叙述

菜单:

menus 菜单可以打开文件,加载模块,以及设定参数。

Mayavi的pipeline管线树状预览图:
 
这是Mayavi 的 pipeline管线 树状预览图。
  • 右键单击树的节点可以对其进行重命名、删除及复制。
  • 左键单击节点将打开编辑界面,可以对其属性进行编辑。
  • 也可以在树的节点间进行拖拽。比如,通过拖拽的方式将子节点从Module 可视化模块拖拽到另一个节点下,或者将可视化从一个scene层级转移到另一个。
对象编辑器:

点击对应pipeline节点的对象,可以对Mayavi对象的属性进行修改。

Mayavi的scene层级:

这里用于展示数据可视化。您可以使用键盘或鼠标对其进行交互。更多的细节请参考接下来的章节。

Python解释器:

The built-in Python interpreter that can be used to script Mayavi and do other things. You can drag nodes from the Mayavi tree and drop them on the interpreter and then script the object represented by the node!

如果您的IPython版本在0.9.1以上,Python解释器将会使用IPython。

日志:

在这里,您将看到Mayavi的日志记录。

Mayavi的UI界面是高度可定制的:

  • the line in-between the sections can be dragged to resize particular views.
  • most of the “tabs” on the widgets can be dragged around to move them anywhere in the application.
  • 每一个预览区(Mayavi的pipeline管线树状预览区、对象编辑区、Python脚本区及日志区)都可以在菜单栏的View中选择对其可见或隐藏。

当您修改了Mayavi的界面,它都会自动保存当前配置。此外,您还可以保存不同的布局界面,通过菜单栏的`View->Perspectives`完成。

以下展示的是一个定制后的Mayavi界面,如您所见,不同区域的大小已经做了调整。

Figure of Mayavi's UI after being configured by a user.

数据可视化

Mayavi 通过将数据加载进`data sources`数据源,以及应用Module可视化模块对其进行展示,详见`an-overview-of-mayavi`章节。如果您想知道它们如何工作,请参考`Parametric surfaces example <parametric_surfaces_example>`。

您需要在`Module`可视化层级和`Filter`滤波层级之前加载数据。Mayavi支持多种文件格式,尤其是VTK的文件格式。或者,您也可以从numpy 数组加载数据。关于数据结构更高级的应用,请参考`data-structures-used-by-mayavi`章节。

当数据完成加载,您可以选择性地使用`filters`层级对数据进行过滤和变换,然后使用一个或者多个`module`可视化模块对数据进行展现。

这里列出了Mayavi所有的`modules` 可视化模块和`filters`滤波器/变换器。下面的参考能帮助您:

List of modules and filters

使用scene层级交互

Mayavi的scenes场景置于UI界面,点击选项卡的小“x”可以关闭它,每一个scene都有一个工具栏,它有多种功能:

  • 用于设置视角的按钮,进行不同角度的可视化,可沿x轴、y轴及z轴的正方向和负方向,或者等轴。
  • A button to turn on parallel projection instead of the default perspective projection. This is particularly useful when one is looking at 2D plots.
  • 用于显示轴向器的按钮,它将指示当前可视化的坐标轴方向。
  • 用于全屏显示的按钮。需要注意的是,当开启全屏全屏时,您需要按”q”或”e”键退出全屏返回正常的窗口。
  • 用于保存scene的可视化图像的按钮,它支持多种格式。文件的格式由命名的扩展名决定。
  • 用于设置scene属性的按钮。

鼠标和键盘是scene交互的主要方法。

鼠标交互

鼠标的交互模式有两种:

  • Camera模式:默认模式,相机通过鼠标移动进行操作。该模式用’c’键可以激活。
  • Actor mode: in this mode the mouse actions operate on the actor the mouse is currently above. This mode is activated by pressing the ‘a’ key.

scene的视角可以通过多种鼠标动作发生改变,按键通常和拖拽配合使用。

  • 按住鼠标左键拖拽可以对 camera/actor进行旋转。

    • 按住键盘的“shift”可以对scene进行平移,这和鼠标的中键效果相同。
    • 按住“ctrl”键将会绕相机的轴进行旋转(滚动)。
    • 同时按住 “shift” 和 “ctrl”键再拖拽图像,可以对图像进行缩放,这和右键的功能是一样的。
  • holding the right mouse button down and dragging upwards will zoom in (or increase the actors scale) and dragging downwards will zoom out (or reduce scale).

  • 按住鼠标中间进行拖拽可对图像进行平移。

  • 滚动鼠标球也可以对图像进行缩放。

键盘交互

scene也可与键盘交互使用,它有多个功能。如下:

数字”3”键:

开启或关闭渲染。

‘stereo’如果没有设置为”True”,这个功能将不可用。

“a”键:

Use actor mode for mouse interaction instead of camera mode.

‘c’:

Use camera mode for mouse interaction instead of actor mode.

‘e’/’q’/’Esc’:

Exit full-screen mode.

‘f’:

Move camera’s focal point to current mouse location. This will move the camera focus to center the view at the current mouse position.

‘j’:

Use joystick mode for the mouse interaction. In joystick mode the mouse somewhat mimics a joystick. For example, holding the mouse left button down when away from the center will rotate the scene.

‘l’:

Configure the lights that are illumining the scene. This will pop-up a window to change the light configuration.

‘p’:

Pick the data at the current mouse point. This will pop-up a window with information on the current pick. The UI will also allow one to change the behavior of the picker to pick cells, points or arbitrary points.

‘r’:

Reset the camera focal point and position. This is very handy.

‘s’:

Save the scene to an image, this will first popup a file selection dialog box so you can choose the filename, the extension of the filename determines the image type.

‘t’:

Use trackball mode for the mouse interaction. This is the default mode for the mouse interaction.

‘=’/’+’:

Zoom in.

‘-’:

Zoom out.

‘left’/’right’/’up’/’down’ arrows:
 

Pressing the left, right, up and down arrow let you rotate the camera in those directions. When “SHIFT” modifier is also held down the camera is panned.

From interactive usage to scripting

It is easy to learn how to script Mayavi when using the interactive application. In this sub-section, we give a few tips for this purpose.

The embedded Python interpreter

The embedded Python interpreter offers extremely powerful possibilities. The interpreter features command completion, automatic documentation, tooltips and some multi-line editing. In addition it supports the following features:

  • The name mayavi is automatically bound to the mayavi.script.Script instance. This may be used to easily script Mayavi.

  • The name application is bound to the envisage application.

  • If a Python file is opened via the File->Open File... menu item one can edit it with a color syntax capable editor. To execute this script in the embedded Python interpreter, the user may type Control-r on the editor window. To save the file press Control-s. This is a very handy feature when developing simple Mayavi scripts. You can also increase and decrease the font size using Control-n and Control-s.

  • As mentioned earlier, one may drag and drop nodes from the Mayavi pipeline tree view onto the Python shell. The object may then be scripted as one normally would. A commonly used pattern when this is done is the following:

    >>> tvtk_scene_1
    <mayavi.core.scene.Scene object at 0x9f4cbe3c>
    >>> s = _
    

    In this case the name s is bound to the dropped tvtk_scene object. The _ variable stores the last evaluated expression which is the dropped object. Using tvtk_scene_1 will also work but is a mouthful.

Recording Mayavi actions to a script

Mayavi features a very handy and powerful script recording facility. This can be used to:

  • record all actions performed on the Mayavi UI into a human readable, Python script that should be able to recreate your visualization.
  • learn how to script the Mayavi objects, in combination with mlab.

Here is how you can use this feature:

  1. When you start the mayavi2 application, on the pipeline tree view toolbar you will find a red record icon next to the question mark icon. Click it. Note that this will also work from a standalone mlab session, on the toolbar of the Mayavi pipeline window.

  2. You’ll see a window popup with a few lines of boilerplate code so you can run your script standalone/with mayavi2 -x script.py ``or ``python script.py. Keep this window open and ignore for now the Save script button, which will be used when you are finished.

  3. Now do anything you please on the UI. As you perform those actions, the code needed to perform those actions is added to the code listing and displayed in the popup window. For example, create a new source (either via the adder node dialog/view, the file menu or right click, i.e. any normal option), then add a module/filter etc. Modify objects on the tree view.

  4. Move the camera on the UI, rotate the camera, zoom, pan. All of these will generate suitable Python code. For the camera only the end position is stored (otherwise you’ll see millions of useless lines of code). The major keyboard actions on the scene are recorded (except for the ‘c’/’t’/’j’/’a’ keys). This implies that it will record any left/right/up/down arrows the ‘+’/’-’ keys etc.

    Since the code is updated as the actions are performed, this is a nice way to learn the Mayavi API.

  5. Once you are done, clicking on the record icon again will stop the recording: in the pop-up window, the Recording box will be ticked off and no code corresponding to new actions will be displayed any more. If you want to save the recorded script to a Python file, click on the Save script button at the bottom of the window. Save the script to some file, say script.py. If you are only interested in the code and not saving a file you may click cancel at this point.

  6. Close the recorder window. You can quit Mayavi, if you want to.

  7. Now from the shell do:

    $  mayavi2 -x script.py
    

    or even:

    $ python script.py
    

    These should run all the code to get you where you left. You can feel free to edit this generated script – in fact that is the whole point of automatic script generation!

It is important to understand that it is possible to script an existing session of Mayavi too. So, if after starting Mayavi you did a few things or ran a Mayavi script and then want to record any further actions, that are certainly possible. Follow the same procedure as before. The only gotcha you have to remember in this case is that the script recorder will not create the objects you already have setup on the session.

注解

You should also be able to delete/drag drop objects on the Mayavi tree view. However, these probably aren’t things you’d want to do in an automatic script.

As noted earlier, script recording will work for a mlab session or anywhere else where Mayavi is used. It will not generate any mlab specific code but write generic Mayavi code using the OO Mayavi API.

警告

Limitations

The script recorder works for some important actions. At this point it does not support the following actions:

  • On the scene, the ‘c’/’t’/’j’/’a’/’p’ keys are not recorded
    correctly since this is much more complicated to implement and typically not necessary for basic scripting.
  • Arbitrary scripting of the interface is obviously not going to work
    as you may expect.
  • Only trait changes and specific calls are recorded explicitly in the
    code. So calling arbitrary methods on arbitrary Mayavi objects will not record anything typically.

Command line arguments

The mayavi2 application features several useful command line arguments that are described in the following section. These options are described in the mayavi2 man page as well.

A complete pipeline may be built from the command line, so that Mayavi can be integrated in shell scripts to provide useful visualizations.

Mayavi can be run like so:

mayavi2 [options] [args]

Where arg1, arg2 etc. are optional file names that correspond to saved Mayavi2 visualizations (filename.mv2), Mayavi2 scripts (filename.py) or any datafile supported by Mayavi. If no options or arguments are provided Mayavi will start up with a default blank scene.

The options are:

-h This prints all the available command line options and exits. Also available through --help.
-V This prints the Mayavi version on the command line and exits. Also available through --version.
-z file_name This loads a previously saved Mayavi2 visualization. Also available through --viz file_name or --visualization file_name.
-d data_file

Opens any of the supported data file formats or non-file associated data source objects. This includes VTK file formats (*.vtk, *.xml, *.vt[i,p,r,s,u], *.pvt[i,p,r,s,u]), VRML2 (*.wrl), 3D Studio (*.3ds), PLOT3D (*.xyz), STL, BYU, RAW, PLY, PDB, SLC, FACET, OBJ, AVSUCD (*.inp), GAMBIT (*.neu), Exodus (*.exii), PNG, JPEG, BMP, PNM, DCM, DEM, MHA, MHD, MINC, XIMG, TIFF, and various others that are supported.

Note that data_file can also be a source object not associated with a file, for example ParametricSurface or PointLoad will load the corresponding data sources into Mayavi. Also available through --data.

-m module-name

A module is an object that actually visualizes the data. The given module-name is loaded in the current ModuleManager. The module name must be a valid one if not you will get an error message.

If a module is specified as package.sub.module.SomeModule then the module (SomeModule) is imported from package.sub.module. Standard modules provided with mayavi2 do not need the full path specification. For example:

mayavi2 -d data.vtk -m Outline -m user_modules.AModule

In this example Outline is a standard module and user_modules.AModule is some user defined module. Also available through --module.

-f filter-name

A filter is an object that filters out the data in some way or the other. The given filter-name is loaded with respect to the current source/filter object. The filter name must be a valid one if not you will get an error message.

If the filter is specified as package.sub.filter.SomeFilter then the filter (SomeFilter) is imported from package.sub.filter. Standard modules provided with mayavi2 do not need the full path specification. For example:

mayavi2 -d data.vtk -f ExtractVectorNorm -f user_filters.AFilter

In this example ExtractVectorNorm is a standard filter and user_filters.AFilter is some user defined filter. Also available through --filter.

-M Starts up a new module manager on the Mayavi pipeline. Also available through --module-mgr.
-n Creates a new window/scene. Any options passed after this will apply to this newly created scene. Also available through --new-window.
-o Run Mayavi in off-screen mode without any graphical user interface. This is most useful for scripts that need to render images off-screen (for an animation say) in the background without an intrusive user interface popping up. Mayavi scripts (run via the -x argument) should typically work fine in this mode. Also available through, --off-screen.
-x script-file This executes the given script in a namespace where we guarantee that the name ‘mayavi’ is Mayavi’s script instance – just like in the embedded Python interpreter. Also available through --exec.
-t

Runs the Mayavi test suite and exits. If run as such, this runs both the TVTK and Mayavi2 unit tests. If any additional arguments are passed they are passed along to the test runner. So this may be used to run other tests as well. For example:

mayavi2 -t apptools.persistence

This will run just the tests inside the apptools.persistence package. You can also specify a directory with test files to run with this, for example:

mayavi2 -t relative_path_to/integrationtests/mayavi

will run the integration tests from the Mayavi sources. Also available as --test.

-s python-expression
 

Execute the python-expression on the last created object. For example, let’s say the previous object was a module. If you want to set the color of that object and save the scene, you may do:

$ mayavi2 [...] -m Outline -s"actor.property.color = (1,0,0)" \
 -s "scene.save('test.png', size=(800, 800))"

You should use quotes for the expression. This is also available through --set.

警告

Note that -x or --exec uses execfile, so this can be dangerous if the script does something nasty! Similarly, -s or --set uses exec, which can also be dangerous if abused.

It is important to note that Mayavi’s command line arguments are processed sequentially in the same order they are given. This allows users to do interesting things.

Here are a few examples of the command line arguments:

$ mayavi2 -d ParametricSurface -s "function='dini'" -m Surface \
  -s "module_manager.scalar_lut_manager.show_scalar_bar = True" \
  -s "scene.isometric_view()" -s "scene.save('snapshot.png')"

$ mayavi2 -d heart.vtk -m Axes -m Outline -m GridPlane \
  -m ContourGridPlane -m IsoSurface

$ mayavi2 -d fire_ug.vtu -m Axes -m Outline -m VectorCutPlane \
  -f MaskPoints -m Glyph

In the above examples, heart.vtk and fire_ug.vtu VTK files can be found in the examples/data directory in the source. They may also be installed on your computer depending on your particular platform.