### Install Mayavi from Source via Git Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/installation.rst Steps to clone the Mayavi repository from GitHub, install dependencies, and perform a local installation. ```bash git clone https://github.com/enthought/mayavi.git cd mayavi pip install -r requirements.txt pip install PyQt5 python setup.py install ``` -------------------------------- ### Additional Examples and Backend Switching Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Provides further examples of Mayavi visualizations and demonstrates how to switch between different backends or re-initialize the notebook. ```APIDOC ## More Examples and Backend Switching This section showcases additional Mayavi visualizations and illustrates the flexibility of switching between backends or re-initializing the notebook environment. ### Wireframe Sphere Example Customize the representation of a visualization, such as rendering a sphere as a wireframe. ```python from mayavi import mlab # Clear the current figure mlab.clf() s = mlab.test_mesh_sphere() s.actor.property.representation = 'wireframe' s ``` ### Switching Backends It is possible to call `init_notebook` multiple times to switch to a different backend or re-initialize the current one. #### Example: Switching to PNG backend ```python # Re-initialize with the PNG backend mlab.init_notebook('png') mlab.clf() mlab.test_contour3d() ``` #### Example: Switching to X3D backend and Bar Chart ```python # Re-initialize with the X3D backend mlab.init_notebook('x3d') mlab.clf() mlab.test_barchart() ``` Remember that each backend has specific requirements and rendering behaviors as detailed in the preceding sections. ``` -------------------------------- ### Mayavi Pipeline Object Management Example Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/advanced_scripting.rst Demonstrates how to create an Engine, add a source, and remove it from the Mayavi pipeline. This involves starting the engine, creating a new scene, adding a parametric surface source, and then removing it. ```python >>> from mayavi.api import Engine >>> e = Engine() >>> e.start() >>> s = e.new_scene() >>> from mayavi.sources.api import ParametricSurface >>> p = ParametricSurface() >>> e.add_source(p) # calls p.start internally. >>> p.remove() # Removes p from the engine. ``` -------------------------------- ### Clone and Install Mayavi from Source Source: https://github.com/enthought/mayavi/wiki/SciPy2017-Sprints Commands to clone the Mayavi repository from GitHub and perform a local installation. ```bash git clone https://github.com/enthought/mayavi.git cd mayavi python setup.py install ``` -------------------------------- ### Install Mayavi using pip Source: https://github.com/enthought/mayavi/blob/main/README.rst This snippet shows the basic command to install Mayavi and PyQt5 using pip. It assumes Python 3.x and a 64-bit machine. If installation fails, refer to the documentation for manual VTK and UI toolkit installation. ```bash $ pip install mayavi $ pip install PyQt5 ``` -------------------------------- ### Run Mayavi Examples from Command Line Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/data.rst Provides command-line instructions for running various Mayavi visualization scripts, including structured and unstructured grids, and 2D/3D points. ```Shell mayavi2 -x structured_grid.py ``` ```Shell mayavi2 -x polydata.py -x structured_points2d.py -x structured_points3d.py -x structured_grid.py -x unstructured_grid.py ``` -------------------------------- ### Using the IVTK Viewer Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Provides an example of initializing an IVTK viewer and adding an actor to the scene for interactive visualization. ```python from tvtk.tools import ivtk from tvtk.api import tvtk a = tvtk.Actor() v = ivtk.viewer() v.scene.add_actors(a) ``` -------------------------------- ### Install Mayavi and Dependencies via Pip Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/installation.rst Commands to install the stable release of Mayavi and the required PyQt5 GUI toolkit using the pip package manager. ```bash pip install mayavi pip install PyQt5 ``` -------------------------------- ### Install Mayavi using Conda Source: https://github.com/enthought/mayavi/wiki/SciPy2017-Sprints Commands to create a Conda environment and install Mayavi with necessary dependencies. ```bash conda create -n scipy17 python=3.5 pyqt=4 source activate scipy17 conda install -c menpo mayavi conda install jupyter ``` -------------------------------- ### show Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_other_functions.rst Starts the GUI event loop to interact with the Mayavi figure. ```APIDOC ## FUNCTION show ### Description Starts interacting with the figure by creating a GUI and starting its event loop. Can be used as a decorator. ### Parameters #### Arguments - **func** (callable) - Optional - Function to execute within the event loop. - **stop** (boolean) - Optional - If True, displays a UI dialog to stop the event loop. ### Request Example mlab.show(stop=True) ### Response - **None** - Starts the event loop. ``` -------------------------------- ### tvtk ConeSource Example Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.md Demonstrates the basic usage of tvtk to create a ConeSource, configure its resolution, and set up a PolyDataMapper, Actor, and Property. It shows how to set properties during instantiation. ```python from tvtk.api import tvtk cs = tvtk.ConeSource() cs.resolution = 36 m = tvtk.PolyDataMapper() m.set_input_data(cs.output) a = tvtk.Actor() a.mapper = m p = a.property p.representation = 'w' print(p.representation) ``` ```python from tvtk.api import tvtk cs = tvtk.ConeSource(resolution=36) m = tvtk.PolyDataMapper(input=cs.output) p = tvtk.Property(representation='w') a = tvtk.Actor(mapper=m, property=p) ``` -------------------------------- ### Install Mayavi Jupyter Extension for X3D Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Installs the Mayavi Jupyter extension for X3D output rendering. This can be done per-user. ```bash $ jupyter nbextension install --py mayavi --user ``` -------------------------------- ### Build and Test TVTK from Source Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Commands to compile the TVTK module from the Mayavi source tree and verify the installation using the nose test runner. ```bash python setup.py build python -m nose.core -v tvtk/tests ``` -------------------------------- ### Install ipywidgets and ipyevents for Mayavi Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Installs necessary packages and enables Jupyter extensions for the default 'ipy' Mayavi backend. Requires pip and Jupyter. ```bash $ pip install ipywidgets ipyevents $ jupyter nbextension enable --py widgetsnbextension $ jupyter nbextension enable --py ipyevents ``` -------------------------------- ### Comprehensive Mayavi Scripting Example Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/advanced_scripting.rst An example script illustrating various Mayavi scripting features. It covers creating a new scene, opening data files, adding visualization modules like Outline, IsoSurface, and Streamline, customizing their properties, and saving images. It also includes an animation loop. ```python # Create a new mayavi scene. mayavi.new_scene() # Get the current active scene. s = mayavi.engine.current_scene # Read a data file. d = mayavi.open('fire_ug.vtu') # Import a few modules. from mayavi.modules.api import Outline, IsoSurface, Streamline # Show an outline. o = Outline() mayavi.add_module(o) o.actor.property.color = 1, 0, 0 # red color. # Make a few contours. iso = IsoSurface() mayavi.add_module(iso) iso.contour.contours = [450, 570] # Make them translucent. iso.actor.property.opacity = 0.4 # Show the scalar bar (legend). iso.module_manager.scalar_lut_manager.show_scalar_bar = True # A streamline. st = Streamline() mayavi.add_module(st) # Position the seed center. st.seed.widget.center = 3.5, 0.625, 1.25 st.streamline_type = 'tube' # Save the resulting image to a PNG file. s.scene.save('test.png') # Make an animation: for i in range(36): # Rotate the camera by 10 degrees. s.scene.camera.azimuth(10) # Resets the camera clipping plane so everything fits and then # renders. s.scene.reset_zoom() # Save the scene. s.scene.save_png('anim%d.png'%i) ``` -------------------------------- ### Install Mayavi Jupyter Extension Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/tips.rst Installs the required Javascript and CSS files for the X3D backend to enable local rendering of 3D scenes without an internet connection. ```bash jupyter nbextension install --py mayavi --user ``` -------------------------------- ### Initialize Mayavi with ITK Backend Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Initializes Mayavi to use the 'itk' backend for client-side rendering. Requires the 'itkwidgets' package to be installed. ```python mlab.init_notebook('itk') ``` -------------------------------- ### Configure Mayavi Debugging Engine Source: https://github.com/enthought/mayavi/blob/main/mayavi/tests/README.txt Shows how to swap the TestEngine for the Engine class in test setup functions to enable on-screen rendering during debugging. ```python # e = TestEngine() # Comment this out e = Engine() # Uncomment this to enable visual debugging ``` -------------------------------- ### Basic Mayavi Scripting with mlab Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/advanced_scripting.rst Shows how to use the 'mlab' interface for basic Mayavi scripting. This involves creating a figure and getting the Mayavi engine instance, which can then be used for further visualization tasks. ```python from mayavi import mlab f = mlab.figure() engine = mlab.get_engine() ``` -------------------------------- ### Create a 2D Barchart with Mayavi Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_helper_functions.rst Demonstrates how to generate a bar chart plot using a 2D numpy array with the barchart function. This example requires numpy and mayavi.mlab to be installed. ```python import numpy as np from mayavi.mlab import * def test_barchart(): """ Demo the bar chart plot with a 2D array. """ s = np.abs(np.random.random((3, 3))) return barchart(s) ``` -------------------------------- ### Python: 3D to 2D Coordinate Transformation with Mayavi Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/example_mlab_3D_to_2D.rst This Python code snippet demonstrates how to convert 3D world coordinates to 2D display coordinates using Mayavi and VTK. It applies modelview and perspective transformations to get normalized view coordinates, and then applies a viewport transformation to get pixel coordinates. The Z value is not used in this specific example. ```python from tvtk.api import ivtk from numpy import array def transform_3d_to_2d(x, y, z, scene): """Converts 3D world coordinates to 2D display coordinates. Args: x, y, z: The 3D world coordinates. scene: The Mayavi scene object. Returns: A tuple (x_display, y_display) representing the 2D display coordinates. """ # Get the scene's camera camera = scene.scene_editor.get_camera() # Get the 4x4 matrix that combines modelview and perspective transformations # This matrix transforms world coordinates to normalized view coordinates modelview_perspective_matrix = camera.get_modelview_plus_projection_matrix() # Apply the modelview-perspective transformation world_coords = array([[x, y, z, 1.0]]) normalized_view_coords = modelview_perspective_matrix.dot(world_coords.T).T # The normalized view coordinates are typically in the range [-1, 1] # We only use the X and Y components for the viewport transformation x_norm, y_norm, z_norm, w_norm = normalized_view_coords[0] # Get the viewport dimensions (in pixels) viewport = camera.viewport x_min, y_min, x_max, y_max = viewport # Apply the viewport transformation to scale and translate to pixel coordinates # The formula is: pixel_coord = min + (normalized_coord + 1) / 2 * (max - min) x_display = x_min + (x_norm + 1.0) / 2.0 * (x_max - x_min) y_display = y_min + (y_norm + 1.0) / 2.0 * (y_max - y_min) return x_display, y_display if __name__ == '__main__': from mayavi import mlab # Create a sample Mayavi scene mlab.figure(bgcolor=(1, 1, 1)) mlab.points3d([0, 1, 2], [0, 1, 2], [0, 1, 2], scale_factor=0.1) # Get the current scene object current_scene = mlab.gcf() # Example usage: Transform a point (1, 1, 1) from world coordinates to display coordinates world_x, world_y, world_z = 1, 1, 1 display_x, display_y = transform_3d_to_2d(world_x, world_y, world_z, current_scene) print(f"World coordinates: ({world_x}, {world_y}, {world_z})") print(f"Display coordinates: ({display_x:.2f}, {display_y:.2f})") # Keep the Mayavi window open mlab.show() ``` -------------------------------- ### Create or Get Mayavi Figure (mlab.figure) Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_figure.rst Creates a new Mayavi scene or retrieves an existing one. If the Mayavi engine is not running, this function also starts it. It allows customization of background color, foreground color, and scene size. ```python from mayavi import mlab # Create a new figure with default settings fig1 = mlab.figure() # Create a figure with custom background color and size fig2 = mlab.figure(bgcolor=(0.1, 0.2, 0.3), size=(800, 600)) # Get the current figure current_fig = mlab.gcf() ``` -------------------------------- ### Initialize Mayavi Visualization with IPython Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/advanced_scripting.rst Demonstrates how to start a Mayavi visualization session using IPython. It requires IPython to be launched with the '--gui=qt' option. The 'mayavi.plugins.app.main()' function initializes the Mayavi application instance. ```python from mayavi.plugins.app import main mayavi = main() ``` -------------------------------- ### Run Mayavi Test Suite Source: https://github.com/enthought/mayavi/blob/main/mayavi/tests/README.txt Demonstrates the command-line interface for executing the Mayavi test suite. The runtests.py script is the recommended entry point for running tests. ```bash $ ./runtests.py . ``` -------------------------------- ### Verify Mayavi Installation Source: https://github.com/enthought/mayavi/wiki/SciPy2017-Sprints Python commands to test the Mayavi installation by launching a test visualization within a Jupyter console. ```python %gui qt from mayavi import mlab mlab.test_plot3d() ``` -------------------------------- ### Initializing TVTK Objects with Traits Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Demonstrates initializing TVTK objects by passing properties (traits) as keyword arguments, similar to VTK object instantiation but with traits. ```python cs = tvtk.ConeSource(radius=0.1, height=0.5) ``` -------------------------------- ### Build tvtk Module Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.md This snippet demonstrates how to build the tvtk module from the mayavi source tree. It involves navigating to the mayavi source directory and running the setup.py build command. Successful building results in a tvtk_classes.zip file and an extension module. ```bash pwd python setup.py build ``` -------------------------------- ### Mayavi Initialization and Basic Usage Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Demonstrates how to initialize Mayavi for Jupyter notebooks, typically using the default 'ipy' backend, and render a basic 3D visualization. ```APIDOC ## Mayavi on Jupyter Notebooks This section covers the initialization and basic usage of Mayavi within a Jupyter notebook environment. ### Initialization To start using Mayavi in a notebook, you need to initialize it. The default backend is `'ipy'`, which is the most powerful and relies on off-screen rendering. Ensure you have `ipywidgets` and `ipyevents` installed. ```bash $ pip install ipywidgets ipyevents $ jupyter nbextension enable --py widgetsnbextension $ jupyter nbextension enable --py ipyevents ``` #### Code Example ```python from mayavi import mlab # Initialize Mayavi for the notebook (defaults to 'ipy' backend) mlab.init_notebook() # Create a sample visualization s = mlab.test_contour3d() scp = mlab.pipeline.scalar_cut_plane(s) s.module_manager.scalar_lut_manager.show_scalar_bar = True s ``` ### Interaction Once rendered, the visualizations are interactive, allowing you to manipulate the camera, cut plane, and scalar bar just like in a standard Mayavi UI. ### Clearing Figures Use `mlab.clf()` to clear the current figure. Note that for the 'ipy' backend, this clears all associated widgets for that figure. ``` -------------------------------- ### Initialize Mayavi Notebook Backend Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Initializes the Mayavi notebook integration. Defaults to the 'ipy' backend, which is the most powerful and does not require WebGL. ```python from mayavi import mlab # Always start with this. mlab.init_notebook() # Defaults to the 'ipy' backend ``` -------------------------------- ### Mayavi mlab Surf Functionality Example Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.md Illustrates how to use the Surf class from mayavi.tools.mlab to plot a surface mesh. This example generates spherical harmonic data and then visualizes it as a surface using the Surf class and a figure object. ```python >>> # Create the spherical harmonic. >>> from numpy import pi, cos, sin, mgrid >>> dphi, dtheta = pi/250.0, pi/250.0 >>> [phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta] >>> m0, m1, m2, m3, m4, m5, m6, m7 = 4, 3, 2, 3, 6, 2, 6, 4 >>> r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7 >>> x = r*sin(phi)*cos(theta) >>> y = r*cos(phi) >>> z = r*sin(phi)*sin(theta) >>> # Now show the surface. >>> from tvtk.tools import mlab >>> fig = mlab.figure() >>> s = Surf(x, y, z, z) >>> fig.add(s) ``` -------------------------------- ### TVTK Object Initialization Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Demonstrates initializing TVTK objects with properties as keyword arguments. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new account. - **email** (string) - Required - The email address for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### GET /open Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_pipeline_sources.rst Opens a supported data file. ```APIDOC ## GET /open ### Description Opens a supported data file given a filename and returns the source object. ### Method GET ### Endpoint /open ### Parameters #### Query Parameters - **filename** (string) - Required - Path to the file. - **figure** (object) - Optional - Figure to associate with the file. ### Request Example { "filename": "data.vtk" } ### Response #### Success Response (200) - **source** (object) - The reader object for the file. ``` -------------------------------- ### Run Mayavi in Non-GUI Mode Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/example_nongui.rst Demonstrates how to initialize the Mayavi application framework without launching the standard graphical interface. This is useful for automated processing or server-side execution where no display is available. ```python from mayavi.core.api import Engine from mayavi.plugins.app import Mayavi # Initialize the engine without the GUI engine = Engine() engine.start() # Configure the application to use the non-gui plugin # This is typically handled by the application entry point or plugin manager ``` ```bash # Execute the script directly python nongui.py # Execute via mayavi2 command line tool mayavi2 script.py ``` -------------------------------- ### GET /mlab/screenshot Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_figure.rst Captures the current figure as an array. ```APIDOC ## GET /mlab/screenshot ### Description Return the current figure pixmap as an array. ### Method GET ### Endpoint /mlab/screenshot ### Parameters #### Query Parameters - **mode** (str) - Optional - 'rgb' or 'rgba'. - **antialiased** (bool) - Optional - Whether to use anti-aliasing. ``` -------------------------------- ### mlab.init_notebook Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_other_functions.rst Initializes the Mayavi backend for use within Jupyter notebooks. ```APIDOC ## FUNCTION init_notebook ### Description Sets up the environment to render Mayavi visualizations inside a Jupyter notebook. ### Parameters - **backend** (str) - Optional - One of ('itk', 'ipy', 'x3d', 'png'). Default: 'ipy'. - **width** (int) - Optional - Suggested width of the element. - **height** (int) - Optional - Suggested height of the element. - **local** (bool) - Optional - Whether to use a local copy of x3dom.js. Default: True. ``` -------------------------------- ### GET /pipeline/get_vtk_src Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/data.rst Retrieves the underlying VTK dataset source from a Mayavi pipeline object. ```APIDOC ## GET /pipeline/get_vtk_src ### Description Extracts the VTK dataset feeding into an arbitrary Mayavi object. ### Method GET ### Endpoint /pipeline/get_vtk_src ### Parameters #### Query Parameters - **obj** (object) - Required - The Mayavi object to inspect. ### Request Example { "obj": "iso" } ### Response #### Success Response (200) - **dataset** (object) - The underlying TVTK dataset (e.g., ImageData, PolyData). #### Response Example { "dataset": "" } ``` -------------------------------- ### Mayavi CellArray Initialization Methods Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.md Shows different ways to initialize a tvtk.CellArray using `from_array`, including Python lists of lists, 2D numpy arrays, and lists of 2D numpy arrays. It also demonstrates the `set_cells` method for efficient initialization. ```python a = [[0], [1, 2], [3, 4, 5], [6, 7, 8, 9]] cells = tvtk.CellArray() cells.from_array(a) a = np.array([[0,1,2], [3,4,5], [6,7,8]], int) cells.from_array(a) l_a = [a[:,:1], a[:2,:2], a] cells.from_array(a) ``` ```python ids = np.array([3, 0,1,3, 3, 0,3,2, 3, 1,2,3, 3, 0,2,1]) n_cell = 4 cells = tvtk.CellArray() cells.set_cells(n_cell, ids) print(cells.data) ``` -------------------------------- ### GET /pipeline/probe_data Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/data.rst Probes the value of a Mayavi object at a specific position in 3D space. ```APIDOC ## GET /pipeline/probe_data ### Description Retrieves the data value at a specific (x, y, z) coordinate from a Mayavi pipeline object. ### Method GET ### Endpoint /pipeline/probe_data ### Parameters #### Query Parameters - **obj** (object) - Required - The Mayavi pipeline object to probe. - **x** (float) - Required - The x-coordinate. - **y** (float) - Required - The y-coordinate. - **z** (float) - Required - The z-coordinate. ### Request Example { "obj": "field", "x": 0.5, "y": 0.5, "z": 0.5 } ### Response #### Success Response (200) - **value** (array) - The probed scalar value at the given coordinate. #### Response Example { "value": [0.78386768] } ``` -------------------------------- ### Basic TVTK Object Usage Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Demonstrates how to instantiate TVTK objects like ConeSource, PolyDataMapper, and Actor, and how to configure their properties using a Pythonic API. ```python from tvtk.api import tvtk # Standard instantiation and property setting cs = tvtk.ConeSource() cs.resolution = 36 m = tvtk.PolyDataMapper() m.set_input_data(cs.output) a = tvtk.Actor() a.mapper = m p = a.property p.representation = 'w' # Equivalent instantiation with keyword arguments cs = tvtk.ConeSource(resolution=36) m = tvtk.PolyDataMapper(input=cs.output) p = tvtk.Property(representation='w') a = tvtk.Actor(mapper=m, property=p) ``` -------------------------------- ### Initialize Mayavi with PNG Backend Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Initializes Mayavi to use the 'png' backend for embedding images in the notebook. This backend relies on off-screen rendering. ```python mlab.init_notebook('png') # This may not work well if off screen rendering is not working. ``` -------------------------------- ### Integrate Mayavi Visualization in WxPython Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/building_applications.rst Example of embedding a Mayavi-based Traits visualization class into a standard WxPython frame. ```python import wx class MainWindow(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Mayavi in Wx') self.visualization = Visualization() ``` -------------------------------- ### GET probe_data Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_pipeline_data.rst Retrieves data values from a Mayavi visualization object or VTK dataset at specified x, y, z coordinates. ```APIDOC ## GET probe_data ### Description Retrieve the data described by a Mayavi visualization object at specific points (x, y, z). ### Method GET ### Endpoint mayavi.tools.pipeline.probe_data ### Parameters #### Path Parameters - **mayavi_object** (object) - Required - A Mayavi visualization object or a VTK dataset. - **x** (float/ndarray) - Required - The x position(s) where you want to retrieve the data. - **y** (float/ndarray) - Required - The y position(s) where you want to retrieve the data. - **z** (float/ndarray) - Required - The z position(s) where you want to retrieve the data. #### Query Parameters - **type** (string) - Optional - The type of data to retrieve: 'scalars', 'vectors', or 'tensors'. Default is 'scalars'. - **location** (string) - Optional - The location of the data to retrieve: 'points' or 'cells'. Default is 'points'. ### Request Example probe_data(my_viz_obj, x=0.5, y=0.5, z=0.0, type='scalars', location='points') ### Response #### Success Response (200) - **data** (ndarray) - The values of the data at the given points, matching the shape of input coordinates. #### Response Example array([0.12, 0.45, 0.89]) ``` -------------------------------- ### Initialize and Display EngineView Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/api/core_view_objects.rst Demonstrates how to instantiate an EngineView object using a Mayavi engine instance and launch its associated Traits UI window. This is used to provide a graphical interface for managing the Mayavi engine. ```python from mayavi.core.ui.api import EngineView view = EngineView(engine=engine) view.edit_traits() ``` -------------------------------- ### Running Mayavi Scripts from Command Line Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/advanced_scripting.rst Illustrates how to execute Python scripts with the mayavi2 application. This includes loading data files, creating modules, and running multiple scripts sequentially. ```bash $ mayavi2 -x script.py ``` ```bash $ mayavi2 -d foo.vtk -m IsoSurface -x setup_iso.py -x script2.py ``` -------------------------------- ### Mayavi mlab view: Set or Get Camera Viewpoint Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/mlab_camera.rst Sets or gets the camera's viewpoint, defined by azimuth, elevation, distance, and focal point. Azimuth is the angle in the x-y plane (0-360 degrees), and elevation is the angle from the z-axis (0-180 degrees). Distance is the radius from the focal point. If called without arguments, it returns the current camera view. Dependencies include numpy for array handling. ```python from mayavi import mlab # Get the current camera view azimuth, elevation, distance = mlab.view() print(f"Current view: Azimuth={azimuth}, Elevation={elevation}, Distance={distance}") # Set a new camera view mlab.view(azimuth=45, elevation=30, distance=100) # Set view with focal point mlab.view(azimuth=90, elevation=60, distance=50, focalpoint=[1, 2, 3]) # Reset to default view (often achieved by calling without arguments or specific values) mlab.view(reset_roll=True) ``` -------------------------------- ### Launch IVTK Viewer with tvtk.tools.ivtk Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.md Shows how to use the `ivtk.viewer` function from `tvtk.tools` to create an interactive visualization environment. This example demonstrates adding a VTK actor to the scene managed by the IVTK viewer, which integrates TVTK with Python interpreters and GUI toolkits. ```python from tvtk.tools import ivtk from tvtk.api import tvtk # Create your actor ... a = tvtk.Actor() # Now create the viewer. v = ivtk.viewer() v.scene.add_actors(a) # or v.scene.add_actor(a) ``` -------------------------------- ### Initialize CellArray with Connectivity Lists Source: https://github.com/enthought/mayavi/blob/main/docs/source/tvtk/README.txt Illustrates multiple ways to initialize a CellArray, including using 2D NumPy arrays and lists of arrays for varying cell types. ```python a = [[0], [1, 2], [3, 4, 5], [6, 7, 8, 9]] cells = tvtk.CellArray() cells.from_array(a) a = np.array([[0,1,2], [3,4,5], [6,7,8]], int) cells.from_array(a) l_a = [a[:,:1], a[:2,:2], a] cells.from_array(a) ``` -------------------------------- ### Apply UserDefined Filters Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/tips.rst Examples of wrapping VTK filters using the UserDefined filter in Mayavi via CLI and mlab scripting. ```bash mayavi2 -d ParametricSurface -s "function='dini'" -f UserDefined:GeometryFilter -s "filter.extent_clipping=True" -s "filter.extent = [-1,1,-1,1,0,5]" -f UserDefined:CleanPolyData -m Surface -s "actor.property.representation = 'p'" -s "actor.property.point_size=2" ``` ```python filtered_obj = mlab.pipeline.user_defined(obj, filter='GeometryFilter') ``` -------------------------------- ### Install Mayavi using EDM Source: https://github.com/enthought/mayavi/wiki/SciPy2017-Sprints Commands to create and configure a Python environment using Enthought Deployment Manager (EDM) for Mayavi development. ```bash edm install mayavi jupyter notebook edm shell edm environments create --version 3.6 py3 edm shell -e py3 edm install mayavi jupyter notebook pyqt ``` -------------------------------- ### Mayavi2 Application Command Line Arguments Source: https://github.com/enthought/mayavi/blob/main/docs/source/mayavi/auto/changes.rst Demonstrates how to use the mayavi2 application with command-line arguments to specify data, modules, and scene settings. This allows for scripted visualization and batch processing. ```bash 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')" ``` -------------------------------- ### Initialize Mayavi with X3D Backend Source: https://github.com/enthought/mayavi/blob/main/examples/mayavi/mayavi_jupyter.ipynb Initializes Mayavi to use the 'x3d' backend for rendering X3D elements in the notebook. Can be configured for local rendering (requires extension) or remote content. ```python mlab.init_notebook(backend='x3d', local=False) # local=True is the default but requires the nbextension to be installed. # local=False pulls the content from the internet. ```