Skip to content
Projects

3-D views

These views draw a field where it actually lives: on the physical X, Y, Z points that every Struphy field product carries. On a mapped domain (a torus, a cylinder, a stellarator) that is what makes them different from the logical-coordinate field plots.

They need the optional PyVista extra:

Terminal window
pip install "plasma-plots[pyvista]"

On this page, the 3-D figures have an Interactive 3-D view button that loads the scene itself, exported with plasma_plots.scene.

Each method returns a pyvista.Plotter without showing it. Call .show() in a notebook or an interactive session, or .screenshot("view.png") in a batch job (set pyvista.OFF_SCREEN = True first). To draw several views into one scene, pass the plotter back in with plotter=. Dimensions other than eta1, eta2, eta3 (and component for vectors) are selected by keyword, exactly as for the 2-D plots, e.g. t=-1.

phi.plasma.plot.isosurface(values=[-0.5, 0.5], cmap="RdBu_r", t=0)

values is a number of evenly spaced levels or a list of explicit levels. The domain boundary is drawn translucently for context (show_domain=False turns it off).

Isosurfaces of a helical mode in a torus
Open in a new tab

opacity and colors take one value for all levels or a list with one per level, e.g. an opaque surface inside a translucent shell:

distance.plasma.plot.isosurface(
values=[0, 0.2], colors=["tab:blue", "lightgrey"], opacity=[1, 0.3]
)

Explicit colors replace the colormap, so the scalar bar gives way to a legend of the levels (“level 0”, “level 0.2”). Name them with labels=["surface", "shell"], which also adds the legend to colormapped surfaces. In a 2-D run, colors and a list of opacities apply to the contour lines, and a single opacity to the plane.

slices_3d(cuts=...) draws surfaces of constant eta1, eta2 or eta3 where they sit in physical space. On a torus, cuts in eta3 are poloidal cross-sections:

phi.plasma.plot.slices_3d(
cuts={"eta3": [0, 0.25, 0.5, 0.75]}, cmap="RdBu_r", t=0
)
Poloidal cross-sections of a mode in a torus
Open in a new tab

A cut in eta1 shows the field on one flux surface, the usual way to see a mode’s poloidal and toroidal structure:

phi.plasma.plot.slices_3d(cuts={"eta1": 0.5}, cmap="RdBu_r", t=0)
A mode on one flux surface
Open in a new tab

Cut positions are logical coordinates (a float picks the nearest grid point), or grid indices (integers, e.g. -1 for the last). Without cuts, the middle of each direction is drawn. All cuts share one color scale.

streamlines() traces field lines, e.g. of the magnetic field, from seeds in a sphere around source_center:

b.plasma.plot.streamlines(
n_points=60, source_center=(3.5, 0, 0), source_radius=0.35
)
Magnetic field lines in a torus
Open in a new tab

glyphs() draws arrows colored by magnitude. stride thins the grid, and selecting a single eta1 shows the field on one surface:

b.isel(eta1=[24]).plasma.plot.glyphs(stride=3, scale=0.5)
Magnetic field arrows on a flux surface
Open in a new tab

Both expect Cartesian (x, y, z) components, as in the *_phy products of out.pproc(physical=True). For contravariant logical components, e.g. from out.evaluate(name, eta1=..., eta2=..., eta3=..., representation="v"), pass components="contravariant". They are then pushed forward with the mapping’s Jacobian, differentiated numerically from X, Y, Z (plasma_plots.pyvista_plots.push_forward).

orbits_3d() draws marker orbits as lines (or tubes, with tube_radius), colored by time, by orbit class, or by any saved quantity such as "v_par" or "weight". Samples where a marker has left the domain are dropped. Pass any field as domain= to draw its boundary:

orbits.plasma.plot.orbits_3d(color_by="classification", domain=phi.isel(t=0))
Guiding-center orbits colored as passing, trapped or lost
Open in a new tab

out.plot.domain_3d() draws a run’s mapping as a wireframe. The grid lines cover the real boundary and, with cross_section=True (the default), the whole eta3 = 0 face. Periodic seams and polar axes are left out. This is useful for checking a geometry and its orientation:

out.plot.domain_3d(n1=6, n2=24, n3=36)
# or, for any struphy domain object:
from plasma_plots.pyvista_plots import pyvista_domain
pyvista_domain(domain, n1=6, n2=24, n3=36)
Wireframe of a toroidal mapping
Open in a new tab

pyvista_surfaces draws surface meshes that are not fields: a vessel, coils, conductors, or a surface from marching cubes. A mesh is a PyVista dataset, a (vertices, faces) pair of arrays (shapes (n, 3) and (m, 3), triangles), or an object with vertices and cells, such as simgeometry’s SurfaceMesh. Pass a dict to label the meshes; each gets its own color from Matplotlib’s color cycle, and the labels go in a legend:

import numpy as np
import pyvista as pv
from plasma_plots.pyvista_plots import pyvista_surfaces
vessel = pv.ParametricTorus(
ringradius=3.0, crosssectionradius=1.0
).triangulate()
vertices, faces = vessel.points, vessel.faces.reshape(-1, 4)[:, 1:]
pyvista_surfaces(
{
"vessel": (vertices, faces),
"probe 1": pv.Sphere(radius=0.3, center=(3.0, 0.0, 0.0)),
"probe 2": pv.Sphere(radius=0.3, center=(0.0, 3.0, 0.0)),
},
opacity={"vessel": 0.3, "probe 1": 1.0, "probe 2": 1.0},
)
A translucent toroidal vessel with two spherical probes
Open in a new tab

colors= and opacity= take one value, a list or a dict by label. scalars= colors the surfaces by a value on one color scale instead: the name of a point-data array, or a function of the (n, 3) points, e.g. a potential:

def potential(points):
return 1 / np.linalg.norm(points - [3.0, 0.0, 0.0], axis=1)
pyvista_surfaces((vertices, faces), scalars=potential, cmap="plasma")

As with the other views, plotter= draws into an existing scene, e.g. the geometry around an isosurface.

pyvista_points draws labelled point sets, such as samples, grid nodes or crossings. A set is an (n, 3) array or a component-major (3, n) one, as simgeometry stores points: the last axis holds the coordinates when its length is 3, else the first one does. (n, 2) points lie in the z = 0 plane. vectors= adds an arrow at every point, e.g. normals, with the longest vector_scale long (default: 5% of the scene). Drawn into the same plotter= as pyvista_surfaces, the color cycle continues and the scene keeps one legend of both:

from plasma_plots.pyvista_plots import pyvista_points
rng = np.random.default_rng(0)
theta, phi = rng.uniform(0, 2 * np.pi, (2, 150))
normals = np.stack(
[np.cos(theta) * np.cos(phi), np.cos(theta) * np.sin(phi), np.sin(theta)]
) # (3, n)
samples = 3.0 * np.stack([np.cos(phi), np.sin(phi), 0 * phi]) + normals
plotter = pyvista_surfaces({"vessel": (vertices, faces)}, opacity=0.3)
pyvista_points(
{"wall samples": samples, "probes": [[3.0, 0.0, 0.0], [0.0, 3.0, 0.0]]},
vectors={"wall samples": normals},
size={"wall samples": 6, "probes": 14},
plotter=plotter,
)
A translucent toroidal vessel with sample points and their normals on its wall, and two probe points
Open in a new tab

colors=, size= and opacity= take one value, a list or a dict by label, and scalars= colors the points by a function of the points or by given values, as for surfaces.

In a 2-D run one logical direction has a single grid point, or you have selected it away (phi.isel(eta3=0)). The same methods then show the plane itself, and the camera looks straight at it:

  • isosurface() draws the colored plane with contour lines.
  • slices_3d() without cuts draws the whole plane. Cuts through a plane are drawn as lines.
  • streamlines() seeds on the plane and keeps the lines on it.
  • glyphs() draws arrows in the plane.
phi.plasma.plot.isosurface(values=7, cmap="RdBu_r", t=0)
u.plasma.plot.streamlines(n_points=80)

Contour lines over a 2-D cylinder cross-section

Field lines of a 2-D flow

movie() renders one 3-D view per time step into a GIF (needs imageio, which comes with the pyvista extra) or a video such as .mp4 (needs imageio-ffmpeg). Scalar views share one color scale over all frames, and the camera stays fixed after the first frame:

phi.plasma.plot.movie(
"mode.gif",
kind="slices",
cuts={"eta3": [0, 0.25, 0.5, 0.75]},
cmap="RdBu_r",
)
phi_2d.plasma.plot.movie(
"mode_2d.gif", kind="isosurface", values=7, cmap="RdBu_r"
)

A mode rotating through poloidal cross-sections

A rotating mode in a 2-D cross-section

plasma_plots.scene(plotter) shows a plotter as an interactive 3-D scene. As the last expression of a notebook cell, it displays the scene as a standalone vtk.js page together with a screenshot. Jupyter shows the page. Docs sites built from the notebook show the screenshot and load the scene on click, as on this page:

import plasma_plots
plotter = phi.plasma.plot.isosurface(values=[-0.5, 0.5], cmap="RdBu_r", t=0)
plotter.camera_position = "iso"
plasma_plots.scene(plotter, alt="Isosurfaces of a helical mode in a torus")

alt describes the screenshot and title names the scene, and window_size=(w, h) sets the screenshot’s size. vtk.js would label its own color bar 0 to 255, so the interactive scene carries the plotter’s color bars as an overlay with the right values instead. Most of a small scene’s size (about 1 MB) is the inlined vtk.js viewer; decimate=0.5 drops half of every surface’s triangles for large meshes.

backend="plotly" shows the scene as a Plotly 3-D figure instead: a few hundred kB, themed like the page, with the values on hover, and without the screenshot or trame. Surfaces become Mesh3d traces, lines and points Scatter3d, each with its color or color scale and opacity. Very large meshes are decimated to max_faces (200 000) triangles; for those, and for streamlines with many tubes, the vtk.js scene renders better:

plasma_plots.scene(plotter, backend="plotly", title="|B| on the last surface")
# or the figure itself
from plasma_plots import scene_to_plotly
scene_to_plotly(plotter).write_html("scene.html")

Outside a notebook, .save_html("scene.html") and .save_png("scene.png") write the two files of the vtk.js scene.

The export needs trame-pyvista, which comes with the scene extra:

Terminal window
pip install "plasma-plots[scene]"

The screenshot needs an off-screen plotter. Plotters created in a notebook are off screen already. In a script, set pyvista.OFF_SCREEN = True before creating the plotter.

field.plasma.data.grid(t=-1) returns the field as a pyvista.StructuredGrid on its physical points. Vector fields also get their magnitude as "|name|". You can hand the grid to any PyVista filter:

grid = phi.plasma.data.grid(t=-1)
grid.contour([0.5]).plot(cmap="RdBu_r")

For ParaView, field.plasma.data.to_vtk("frames") writes one .vts structured grid per time and a .pvd collection that ParaView opens as a time series. Any array works, e.g. a filtered mode from filter_time(...).filtered.

To share a scene as a standalone web page, like the interactive views on this page, write it with plasma_plots.scene(plotter).save_html("scene.html") (see Interactive scenes in notebooks).

Some Struphy mappings cover only one poloidal or toroidal sector. Copy the result to the full torus before plotting it:

from plasma_plots import repeat_periodic
pol_period, tor_period = 1, 6
phi = out.evaluate(
"em_fields/phi",
t=-1,
eta1=np.array([1.0]),
eta2=np.linspace(0.0, 1.0, 64, endpoint=False),
eta3=np.linspace(0.0, 1.0, 64, endpoint=False),
)
# Simulated sector (1 poloidal, 6 toroidal)
phi.plasma.plot.slices_3d(
cuts={"eta1": 1.0},
cmap="RdBu_r",
title=f"Simulated sector ({pol_period} poloidal, {tor_period} toroidal)",
)
# Copy the sector to the full torus, rotating both the values' physical coordinates
# and the attached X/Y/Z coordinates
full_phi = repeat_periodic(
phi,
poloidal_period=pol_period,
toroidal_period=tor_period,
R0=3.0, # major radius of the circular poloidal axis
)
full_phi.plasma.plot.slices_3d(
cuts={"eta1": 1.0},
cmap="RdBu_r",
title=f"Full torus ({pol_period} poloidal, {tor_period} toroidal)",
)

The first plot shows the simulated sector; the titled second plot shows the expanded full torus. repeat_periodic copies the values and rotates the attached X, Y, Z coordinates around both toroidal and poloidal axes, automatically matching the direction the sector is oriented in. R0 and Z0 specify the poloidal rotation centre; use the major-axis parameters of the mapping. repeat_periodic works with both 2-D surfaces drawn with slices_3d and full 3-D volumes drawn with isosurface.

A simulated poloidal and toroidal sector of a torus
Open in a new tab
The sector copied to a full torus
Open in a new tab