Skip to content
Projects

plasma_plots

Type part of a name or a dotted path

Plots and diagnostics of labeled xarray data from plasma simulations, such as Struphy’s output.

plasma-plots adds accessors to the objects Struphy returns; you rarely call a function directly:

  • out.plot and out.analysis on a Struphy Output: whole-run plots and diagnostics.
  • array.plasma.plot, .analysis and .data on every xarray.DataArray, e.g. a product from out.evaluate("em_fields/phi").
  • dataset.plasma.plot, .analysis and .data on marker Datasets such as orbits.

Creating a Struphy Output loads plasma-plots, so its output needs no import. For xarray data from elsewhere, import plasma_plots first; without it, .plasma raises AttributeError: 'DataArray' object has no attribute 'plasma'.

Printing an accessor lists its methods (print(phi.plasma.plot)), and help() on a method shows every parameter (help(phi.plasma.plot.slice)). plasma-plots guide (or python -m plasma_plots guide) prints this guide, plasma-plots api an index of every method and function with its signature. The plasma-plots command also saves figures from the shell, e.g. plasma-plots plot sim_1 em_fields/phi slice t=-1 eta3=0 -o phi.png or plasma-plots quicklook sim_1 -o figures/ (plasma-plots --help).

Classes

NameDescription
PlasmaAccessorStruphy diagnostics of one array: array.plasma.plot, .analysis and .data.
SkippedPlotWhat a plot returns on MPI ranks other than 0, where nothing is drawn.

Functions

NameDescription
animate_quadtreeAnimate a quadtree that follows moving particles: the cells and particles of every frame.
figureCompose several plots into one figure, drawn with Matplotlib, or as one Plotly or TikZ figure.
from_boundaryA ConStellaration plasma boundary as a surface Dataset, with its minor radius.
from_coilsetEvery coil of a coilset as points along its curve, with currents and curvatures.
from_descEvaluate DESC quantities on a grid, as a Dataset in plasma-plots' conventions.
from_gvecReturn GVEC evaluations in plasma-plots' conventions; see plasma_plots.gvec.
get_backendReturn the backend of plots that do not pass backend= themselves.
get_mathReturn how the formulas of labels reach Plotly figures.
get_styleReturn the name of the current style.
is_plotting_rankTell whether this process draws plots and writes their files.
mpi_rankReturn this process' rank in MPI_COMM_WORLD, without initializing MPI.
plot_domainDraw a simulation domain with its objects and their measurements, as a technical drawing.
plot_quadtreePlot the cells of a quadtree, its particles and the Barnes-Hut walk for a target.
repeat_periodicCopy a poloidal/toroidal sector to the full periodic domain.
save_figureSave a figure in several formats at once, as <name>.<format>.
sceneShow a pyvista.Plotter as an interactive 3-D scene in a notebook.
scene_to_plotlyConvert a pyvista.Plotter into an interactive Plotly 3-D figure.
set_backendSet the backend of every plot that does not pass backend= itself.
set_mathSet how the formulas of labels (Matplotlib's $...$ mathtext) reach Plotly figures.
set_styleSet the style of every later plot.
styleDraw with a style inside a with block.

Modules

  • accessorsThe .plasma accessor: plots, diagnostics and plot data of a single labeled array or dataset.
  • analysisNumerical diagnostics returning values and labeled arrays, without rendering.
  • arraysSmall xarray metadata helpers used by plasma_plots.
  • chartsGeneral charts of labeled data: parameter scans, breakdowns, cross sections, matrices.
  • cliThe plasma-plots command: quick looks at simulation output without writing Python.
  • coilsStellarator coilsets and plasma boundaries as Datasets in plasma-plots' conventions.
  • descEvaluate DESC equilibria into Datasets in plasma-plots' conventions.
  • fieldline_plotsPlots of traced field lines, from plasma_plots.fieldlines.
  • fieldlinesMagnetic field lines on the mapped grid, traced, cut, classified and sampled along.
  • figuresSeveral plots in one figure, with any backend: plasma_plots.figure(...).
  • galleryOutput helpers of the struphy-hub example gallery: figure files, profiling exports and metadata.
  • geometryElectrodes, walls, apertures and other shapes drawn over a plot: plasma_plots.geometry.
  • gvecRead GVEC's evaluation Datasets in plasma-plots' conventions.
  • heroAnimated SVG header pictures for the home pages of the docs: plasma_plots.hero.
  • labelsNumbers in plot labels and titles, written the way a reader writes them.
  • mpiPlot on MPI rank 0 only.
  • output_accessorsPlots and diagnostics of a whole run, as out.plot and out.analysis.
  • phase_spacePhase-space views of markers: position against velocity, as points or a weighted histogram.
  • plotly_backendInteractive Plotly versions of the plots: backend="plotly".
  • plottingSmall, composable plotting functions for labeled Struphy output.
  • pyvista_plotsThree-dimensional PyVista views of labeled Struphy output.
  • spectralFourier and spectral diagnostics of labeled arrays, computed on demand.
  • spectral_plotsPlots of the spectral diagnostics in plasma_plots.spectral.
  • stylesNamed plot styles and a colour-blind-safe palette: plasma_plots.set_style.
  • theoryAnalytic theory to compare Struphy runs against.
  • tikz_backendLaTeX versions of the plots, as TikZ/pgfplots code: backend="tikz".
  • treesQuadtrees: the cells of a tree code, a Barnes-Hut walk and the particles they hold.

PlasmaAccessorclass#

class PlasmaAccessor(array: xr.DataArray)

Struphy diagnostics of one array: array.plasma.plot, .analysis and .data.

Registered on every xarray.DataArray when plasma_plots is imported. A GVEC evaluation is read in plasma-plots’ conventions first (see plasma_plots.gvec.from_gvec()).

Examples

>>> import plasma_plots
>>> phi.plasma.plot.slice(x="eta1", y="eta2", t=-1)

analysisproperty#

analysis: 'ArrayAnalysis'

Diagnostics of this array, e.g. array.plasma.analysis.growth_rate().

dataproperty#

data: 'ArrayData'

The data behind each plot, without rendering it.

E.g. for a different plotting library: array.plasma.data.slice(x="eta1", y="v1", t=-1).

plotproperty#

plot: 'ArrayPlots'

Plots of this array, e.g. array.plasma.plot.slice(x="eta1", y="v1", t=-1).

SkippedPlotclass#

class SkippedPlot(name: str, rank: int)

What a plot returns on MPI ranks other than 0, where nothing is drawn.

Any public attribute or call returns the same object, so plot(...).save(path), plotter.show() or animation.save(path) run on every rank but act only on rank 0. It is false and iterates as empty, like the (empty) list of files it wrote.

Parameters

NameTypeDescription
namestrThe skipped plot function, shown by repr.
rankintThe rank that skipped it.

Examples

>>> skipped = SkippedPlot("plot_slice", rank=1)
>>> skipped.save("slice.png").fig is skipped # nothing is written
True
>>> list(skipped), bool(skipped)
([], False)

animate_quadtreefunction#

def animate_quadtree(trees=None, *, points=None, point_color=None, times=None, sweep: str = 't', color: str | None = 'depth', leaves_only: bool = False, max_depth: int | None = None, leaf_capacity: int = 8, bounds=None, extent=None, cmap=None, point_cmap=None, linewidth: float = 0.8, s: float = 6, interval: int = 100, max_frames: int | None = None, title: str | None = None, backend=None)

Animate a quadtree that follows moving particles: the cells and particles of every frame.

Each frame draws the cells of its tree as plot_quadtree() does, colored by depth on one scale for the whole animation, with the particles on top, so the refinement can be watched following the particles as they cluster, spread or form filaments.

Parameters

NameTypeDefaultDescription
treessequenceNoneOne tree per frame: a QuadtreeCells or a tree with tree-d-3d’s attribute names (see quadtree_cells()). Default: built from points for every frame (build_quadtree() with leaf_capacity and bounds).
pointssequence of arrayNoneOne (2, N) or (N, 2) array of positions per frame (the number of particles may change), or one array with a leading frame axis. Needed without trees. Default: no particles.
point_colorarray or sequence of arrayNoneValues to color the particles by on a diverging map symmetric about zero: one (N,) array for every frame (e.g. the charges), or one per frame. Default: one color.
timessequence of floatNoneThe time (or other sweep value) of each frame, for the titles and the slider of the Plotly version. Default: the frame numbers.
sweepstr't'The name of the sweep, e.g. "t" or "step". Default: "t".
color'depth'"depth"Color the outlines by depth, with a color bar, or draw them in one gray. Default: "depth".
leaves_onlyboolFalseDraw only the leaves. Default: False.
max_depthintNoneDraw no cells deeper than this. Default: all.
leaf_capacityint8The most points a leaf of a tree built from points holds. Default: 8.
bounds(float, float, float)NoneThe root cell (x_centre, y_centre, half_width) of trees built from points. Default: the smallest square around each frame’s points.
extent(float, float, float, float)NoneThe axes limits (x_min, x_max, y_min, y_max), fixed over the animation. Default: the smallest square holding every frame’s root cell.
cmapstr or matplotlib.colors.ColormapNoneThe colormap of the outlines. Default: "viridis" without its darkest fifth.
point_cmapstr or matplotlib.colors.ColormapNoneThe colormap of point_color. Default: "coolwarm".
linewidthfloat0.8The width of the outlines in points. Default: 0.8.
sfloat6The size of the particle dots. Default: 6.
intervalint100The delay between frames, in milliseconds. Default: 100.
max_framesintNoneKeep at most this many frames, evenly spaced (the first and last included), e.g. to keep a Plotly animation small. Default: all.
titlestrNoneA format string for each frame’s title, with the fields sweep, time, cells, leaves and depth. Default: "{sweep} = {time}: {leaves} leaves, depth {depth}".
backend('matplotlib', 'plotly', 'tikz')"matplotlib"Draw with this backend; default: the one of plasma_plots.set_backend(). With Plotly the result is a figure with one frame per time, a slider and Play/Pause buttons.

Returns

matplotlib.animation.FuncAnimation or PlotResult
The animation (retain it, e.g. in a variable, or it stops), or with Plotly the converted figure.

Raises

ValueError
If color is unknown, neither trees nor points are given, or the frame counts differ.

Examples

>>> # builds the trees
>>> animate_quadtree(points=history, times=t, leaf_capacity=16)
>>> animate_quadtree(
... trees, points=[tree.pos for tree in trees], backend="plotly"
... )

figurefunction#

def figure(nrows: int = 1, ncols: int = 1, *, backend: str | None = None, sharex: bool | str = False, sharey: bool | str = False, figsize=None, title: str | None = None, caption: str | None = None, **options) -> Figure

Compose several plots into one figure, drawn with Matplotlib, or as one Plotly or TikZ figure.

Use it as a with block: every plot method given ax=fig[i] draws into panel i; at the end of the block the figure is finished, and with backend="plotly" or backend="tikz" converted once. In a notebook a Plotly figure is shown at the end of the block, as the inline backend shows a Matplotlib figure at the end of the cell.

Parameters

NameTypeDefaultDescription
nrowsint1The number of rows of panels. Default: 1.
ncolsint1The number of columns of panels. Default: 1.
backend('matplotlib', 'plotly', 'tikz')"matplotlib"Finish the figure as a Matplotlib figure, as an interactive Plotly figure, or as a TikZ/pgfplots figure for LaTeX. Default: the one set with plasma_plots.set_backend(), "matplotlib" unless changed.
sharexbool or {'row', 'col', 'all'}FalseShare the horizontal axes (and their zoom, in Plotly), as for matplotlib.pyplot.subplots. Default: False.
shareybool or {'row', 'col', 'all'}FalseShare the vertical axes. Default: False.
figsize(float, float)NoneThe size in inches. Default: from the number of panels.
titlestrNoneA title above all panels. Default: none.
captionstrNoneA caption for the page that shows the figure (a docs page, a gallery study): the Matplotlib figure carries it as fig.caption, a Plotly figure as layout.meta["caption"], and a web figure saved from it as its title. Default: none.
**options{}Passed on to matplotlib.pyplot.subplots, e.g. gridspec_kw={"height_ratios": [3, 1]}.

Returns

Figure
The figure; index it for the panels’ axes, and save or show it after the block.

Examples

>>> with plasma_plots.figure(2, 1, sharex=True, backend="plotly") as fig:
... energy.plasma.plot.timeseries(fit=(0.0, 5.0), ax=fig[0])
... drift.plasma.plot.timeseries(logy=True, ax=fig[1])
>>> fig.save("energies.html")
>>> fig.results[0].fit_results[0].rate

from_boundaryfunction#

def from_boundary(boundary, *, theta=64, zeta=None) -> xr.Dataset

A ConStellaration plasma boundary as a surface Dataset, with its minor radius.

The boundary is a SurfaceRZFourier: R and Z as Fourier series in the poloidal angle theta and the cylindrical toroidal angle phi, R = sum r_cos[m, n] cos(m theta - nfp n phi) (plus r_sin) and Z = sum z_sin[m, n] sin(m theta - nfp n phi) (plus z_cos), with m = 0 ... M along the first axis and n = -N ... N along the second.

The Dataset is laid out like one surface of from_desc(): dims rho (the single value 1), theta and zeta (= phi), coordinates X, Y, Z, and the variable R, so plasma.R.plasma.plot.slices_3d() draws it and it serves as the surface of pyvista_coils() and distance_to_surface().

Parameters

NameTypeDefaultDescription
boundary(dict, str or object)requiredr_cos, z_sin ((M + 1, 2N + 1)), optional r_sin, z_cos (None for a stellarator-symmetric surface) and n_field_periods: ConStellaration’s boundary.json as a dict or JSON string, or an object with these attributes such as constellaration.geometry.surface_rz_fourier.SurfaceRZFourier.
thetaint or sequence of float64Poloidal angles: an integer as that many points over [0, 2π), else the values. Default: 64.
zetaint or sequence of floatNoneToroidal angles: an integer as that many points over one field period [0, 2π/nfp), else the values. Default: the whole torus, 24 points per field period.

Returns

xarray.Dataset
R (m) over (rho, theta, zeta) with coordinates X, Y, Z, the angles’ period, and the attributes nfp, major_radius (the m = n = 0 coefficient of R, m) and minor_radius (m): sqrt(A / π) of the mean area A of the cross-sections at constant phi, the length CoilStellaration’s normalized_* metrics divide by.

Raises

TypeError
If boundary is none of the accepted kinds.
ValueError
If keys are missing or r_cos has an even number of toroidal modes.

Examples

>>> plasma = from_boundary(json.loads(row["boundary.json"]))
>>> plasma.attrs["minor_radius"]
>>> plasma.R.plasma.plot.slices_3d().show()

from_coilsetfunction#

def from_coilset(coilset, *, n_points: int = 128) -> xr.Dataset

Every coil of a coilset as points along its curve, with currents and curvatures.

The unique coils are expanded as DESC’s CoilSet expands them: for a stellarator-symmetric coilset, their mirror images across the plane phi = pi / nfp (followed by z -> -z) in reverse order and with the opposite current, then all of these rotated into every field period. Coil i of the Dataset is coil i of DESC’s expanded coilset.

Parameters

NameTypeDefaultDescription
coilset(dict, str, object or desc.coils.CoilSet)requiredA coilset in CoilStellaration’s layout: coil_x_n, coil_y_n, coil_z_n ((n_unique_coils, 2N + 1) Fourier coefficients in meters, ordered [sin(N s), ..., sin(s), 1, cos(s), ..., cos(N s)]), currents (A), n_field_periods and is_stellarator_symmetric; as a dict (e.g. json.loads of the dataset’s json column), that JSON string, an object with these attributes such as coilstellaration.types.Coilset, or a DESC CoilSet of FourierXYZCoil.
n_pointsint128Points along each coil, equally spaced in s over [0, 2π). Default: 128.

Returns

xarray.Dataset
Over coil and s: the coordinates X, Y, Z (m), unique_coil (the stored coil each one copies), mirrored and field_period; the variables current (A, per coil, reversed on the mirrored coils), length (m, per coil) and curvature (1/m, along each coil); the attributes nfp, stellarator_symmetric and fourier_order.

Raises

TypeError
If coilset is none of the accepted kinds.
ValueError
If keys are missing, the coefficient arrays don’t match, or n_points < 3.

Examples

>>> coils = from_coilset(json.loads(row["json"]))
>>> coils.sizes # 5 unique coils, mirrored, 3 field periods
Frozen({'coil': 30, 's': 128})
>>> coils.curvature.max(dim="s") # the sharpest bend of each coil

from_descfunction#

def from_desc(eq, names: str | Sequence[str], *, rho: int | float | Sequence[float] = 11, theta: int | float | Sequence[float] = 32, zeta: int | float | Sequence[float] = 24, sfl: str | None = None) -> xr.Dataset

Evaluate DESC quantities on a grid, as a Dataset in plasma-plots’ conventions.

See plasma_plots.desc for what the Dataset contains.

Parameters

NameTypeDefaultDescription
eqdesc.equilibrium.EquilibriumrequiredThe equilibrium, e.g. desc.io.load("eq.h5") or desc.examples.get("W7-X").
namesstr or sequence of strrequiredDESC’s names of the quantities ("|B|", "iota", "sqrt(g)", "B", "J", "p", "D_Mercier", "V", …; see DESC’s list of variables). "theta_PEST" becomes the coordinate theta_P. Quantities that are not scalars, profiles, fields or 3-vectors (such as "grad(B)") are not supported, nor "x": the position is X, Y, Z.
rhoint, float or sequence of float11The flux surfaces: an integer as that many points from 0 to 1, a float or a sequence as the values. Default: 11 points.
thetaint, float or sequence of float32The poloidal angles (PEST angles with sfl="pest"): an integer as that many points over [0, 2π), else the values. Default: 32 points.
zetaint, float or sequence of float24The toroidal angles: an integer as that many points over one field period [0, 2π/nfp), else the values, which may cover the whole torus. Default: 24 points.
sfl(None, 'pest')None"pest" for a grid in the straight-field-line PEST angle theta_P (DESC’s own theta becomes a coordinate, found by eq.map_coordinates) rather than in DESC’s poloidal angle. Default: None.

Returns

xarray.Dataset
The quantities over rho, theta (or theta_P) and zeta, vectors along component, with the coordinates X, Y, Z, labels, units, the angles’ period and the nfp attribute.

Raises

ValueError
For an unknown sfl, a name DESC doesn’t know, a quantity of an unsupported shape or a coordinate triplet such as "x".

Examples

>>> ev = from_desc(eq, ["|B|", "iota", "sqrt(g)"], rho=11, theta=64, zeta=40)
>>> ev["|B|"].plasma.plot.panels(
... sweep="zeta", coords="physical", plane="RZ", nrows=1, ncols=3
... )
>>> pest = from_desc(eq, "|B|", rho=[0.5], theta=64, zeta=48, sfl="pest")
>>> pest["|B|"].plasma.plot.slice(x="zeta", y="theta_P", rho=0.5)

from_gvecfunction#

def from_gvec(data: xr.DataArray | xr.Dataset, *, nfp: int | None = None) -> xr.DataArray | xr.Dataset

Return GVEC evaluations in plasma-plots’ conventions; see plasma_plots.gvec.

Data that is not in GVEC’s layout (see is_gvec()) comes back with only the steps that apply, so calling it twice is harmless.

Parameters

NameTypeDefaultDescription
dataxarray.Dataset or xarray.DataArrayrequiredA Dataset from state.evaluate(...), state.evaluate_sfl(...) or gvec.Evaluations (also after to_netcdf and open_dataset), or one of its variables.
nfpintNoneThe number of field periods. Default: the N_FP variable (evaluate "N_FP" with the rest), else an nfp attribute, else from a toroidal grid that spans one field period uniformly (GVEC’s default grid); without one, the toroidal angle gets no period.

Returns

xarray.Dataset or xarray.DataArray
The same data, of the same type, with the dimensions rho, theta/theta_B/ theta_P, zeta/zeta_B and component, the coordinates X, Y, Z (from pos), X1, X2, labels from the symbol attributes, the angles’ period and the nfp attribute.

Examples

>>> ev = from_gvec(
... state.evaluate("mod_B", "pos", "N_FP", rho=11, theta=32, zeta=24)
... )
>>> ev.mod_B.plasma.plot.panels(
... sweep="zeta", coords="physical", plane="RZ", nrows=1, ncols=3
... )
>>> boozer = from_gvec(
... state.evaluate_sfl(
... "mod_B", "pos", rho=[0.5], theta=32, zeta=24, sfl="boozer"
... )
... )
>>> boozer.mod_B.plasma.plot.slice(x="zeta_B", y="theta_B", rho=0.5)

get_backendfunction#

def get_backend() -> str

Return the backend of plots that do not pass backend= themselves.

Returns

str
"matplotlib" (the default), "plotly" or "tikz".

get_mathfunction#

def get_math() -> str

Return how the formulas of labels reach Plotly figures.

Returns

str
"unicode" (the default) or "latex".

get_stylefunction#

def get_style() -> str

Return the name of the current style.

Returns

str
One of the keys of STYLES.

is_plotting_rankfunction#

def is_plotting_rank() -> bool

Tell whether this process draws plots and writes their files.

Returns

bool
True on rank 0 of an MPI job and in any process outside one.

mpi_rankfunction#

def mpi_rank() -> int

Return this process’ rank in MPI_COMM_WORLD, without initializing MPI.

The rank comes from mpi4py if the application has already initialized MPI, otherwise from the per-rank variables MPI launchers export. STRUPHY_MPI=0 makes every process rank 0.

Returns

int
The rank, or 0 outside an MPI job.

Examples

>>> mpi_rank() # in a serial run
0

plot_domainfunction#

def plot_domain(domain, *, x: float | None = None, y: float | None = None, z: float | None = None, views=None, bounds=None, dimensions=True, measure=None, extra_dimensions=None, circles: str = 'diameter', angles: bool = False, boundaries=False, scale: float = 1.0, unit: str | None = None, fmt: str = '{:.4g}', grid: bool = False, cells: bool | None = None, names: bool = True, axes: bool | None = None, colors=None, opacity: float = 0.7, hatch=None, resolution: int = 256, ax=None, figsize=None, title: str | None = None, backend=None)

Draw a simulation domain with its objects and their measurements, as a technical drawing.

A 3-D domain is sliced at x=, y= or z=, or drawn in several views side by side at one scale; a 2-D one is drawn as it is. Every object the plane cuts is filled in its own color and named in the legend (with its voltage when it is a conductor), the domain’s boundary is drawn, and the measurements are dimension lines with arrows, found from the geometry itself: the extent of the domain along each axis, and for the objects a chain along each axis of their sizes and the gaps between them and to the boundary (objects that overlap along an axis get rows of their own), or every edge measured from the lower boundary (dimensions="baseline"). The values are in the plotted units, so scale=1e3, unit="mm" labels a domain built in metres in mm; the size of a circle or a sphere is its diameter, marked ⌀, or with circles="radius" its centre is measured and its radius drawn. boundaries=True writes the boundary conditions of a SimulationDomain on its sides, and cells=True (or grid=True) the size and the number of its cells.

Parameters

NameTypeDefaultDescription
domain(simgeometry.SimulationDomain, GeometryCollection, shape, dict or list)requiredThe domain: a SimulationDomain (its objects, bounds, grid and boundary conditions), a GeometryCollection (named objects and bounds), a single shape, or a dict of names to shapes or a list of shapes (the bounds are then the shapes’ extent). A shape is a simgeometry shape, or one of this module’s: {"rectangle": (x0, y0, width, height)}, {"circle": (x, y, radius)}, {"polygon": outline} (named by their "label" in a list) or an outline array; these need no simgeometry.
xfloatNoneThe position of the slice through a 3-D domain; exactly one of them.
yfloatNoneThe position of the slice through a 3-D domain; exactly one of them.
zfloatNoneThe position of the slice through a 3-D domain; exactly one of them.
viewssequence of dict or strNoneSeveral slices of a 3-D domain, drawn side by side at one scale with their lower sides aligned, e.g. [{"y": 0.0}, {"x": 0.0}] or ["y=0", "x=0"] for a front and a side view; instead of x, y or z. Default: one view.
bounds(lower, upper)NoneThe corners of the domain, e.g. ((0, -4), (8, 4)), for shapes without a collection or to draw another region; as many coordinates as the domain has dimensions. Default: the domain’s own bounds, or the shapes’ extent.
dimensions(True, 'chain', 'baseline', 'extents', False)TrueThe measurements: chains of the objects’ sizes and gaps (True or "chain"), every edge measured from the lower boundary ("baseline"), only the extent of the domain ("extents"), or none (False). Default: True.
measuresequence of strNoneThe names of the objects to measure; the others are drawn without measurements. Default: all of them.
extra_dimensionssequenceNoneMeasurements of your own, in the domain’s coordinates in the plane (before scale): (start, end), (start, end, label) or {"start": ..., "end": ..., "offset": ..., "label": ...} (see :func:dimension_line). The label is the distance by default. Default: none.
circles('diameter', 'radius')"diameter"Measure a circle or a sphere by its diameter, marked ⌀, in the chains, or by its centre in the chains and its radius drawn from the centre, marked R. Default: "diameter".
anglesboolFalseMark the angle of every straight edge inclined to the axes (a cone, a slanted tube, a polygon’s sides) against the nearest axis. Default: False.
boundariesbool or dictFalseWrite the boundary conditions on the domain’s sides: True those of a SimulationDomain (its field and particle boundary conditions, e.g. φ = 5 kV, particles: kill), or a dict of labels by side such as {"xmin": "cathode", "ymax": "open"}, which replaces (or with None removes) those. Default: False.
scalefloat1.0Multiply every coordinate, e.g. 1e3 to draw a domain in metres in mm. Default: 1.
unitstrNoneThe unit of the plotted coordinates, written after every measurement and in the axis labels. Default: none.
fmtstr'{:.4g}'The format of the measured values. Default: "{:.4g}".
gridboolFalseDraw the lines of the domain’s grid (a SimulationDomain). Default: False.
cellsboolNoneMeasure the first cell of the grid along each axis and write the number of cells, beyond the top and the right side. Default: as grid.
namesboolTrueA legend naming the objects. Default: True.
axesboolNoneShow the axes with their ticks. Default: hidden when measurements are drawn, as in a drawing, shown otherwise.
colorsdict or sequenceNoneThe fill colors, by object name or in their order; the collection’s styles apply first. Default: Matplotlib’s color cycle.
opacityfloat0.7The opacity of the fills. Default: 0.7.
hatchbool or strNoneHatch the objects as the section faces of a technical drawing: True for "///", or any Matplotlib hatch; with backend="tikz" a TikZ pattern. Default: none.
resolutionint256Samples per axis when tracing the outline of a sliced 3-D object. Default: 256.
axmatplotlib.axes.AxesNoneDraw into these axes, e.g. over a field drawn with plot.slice; the limits are widened for the measurements. Not with views. Default: a new figure, as wide as figsize (or Matplotlib’s default) and as high as its content, at one scale for all views.
figsize(float, float)NoneThe width of the new figure in inches; a height can only shrink the scale. Default: Matplotlib’s.
titlestrNoneThe title of every view. Default: the position of the slice (none for a 2-D domain).
backend('matplotlib', 'plotly', 'tikz')"matplotlib"Draw with Matplotlib, as an interactive Plotly figure, or as TikZ/pgfplots code for LaTeX (see plasma_plots.tikz_backend). Default: the one set with plasma_plots.set_backend(), "matplotlib" unless changed.

Returns

PlotResult
The figure and axes (a list with views), the drawn artists, and in data: "axes" the names of the plane’s axes, "extent" the domain’s size along them, "objects" each drawn object’s (min, max) along them, "chains" the measurements of dimension_chains(), "boundaries" the side labels, "cells" the cell size and count per axis, "radii", "angles" (object, degrees) and "extra" the lengths of extra_dimensions; all in the plotted units. With views, data["views"] is a list of these.

Raises

TypeError
If the slice does not fit the domain’s dimension, domain is not a domain, or views is combined with x, y, z or ax.
ValueError
If the slice lies outside the domain, an option has an unknown value, measure names unknown objects, or cells=True is given for a domain without a grid.

Examples

>>> result = plot_domain(domain, z=0.0, scale=1e3, unit="mm")
>>> result.data["objects"]["plasma grid"]["x"]
(28.0, 32.0)
>>> plot_domain(domain, z=0.0, scale=1e3, unit="mm", backend="tikz").save(
... "domain.tikz"
... )
>>> # a front and a side view, with the boundary conditions and the cells
>>> plot_domain(domain, views=["y=0", "x=0.03"], boundaries=True, cells=True)
>>> # a 2-D collection
>>> plot_domain(
... electrodes, dimensions="baseline", circles="radius", angles=True
... )
>>> # without simgeometry
>>> plot_domain(
... [{"rectangle": (4.5, -3.0, 1.0, 6.0), "label": "anode"}], unit="mm"
... )

plot_quadtreefunction#

def plot_quadtree(tree=None, *, points=None, color: str | None = 'depth', point_color=None, leaves_only: bool = False, max_depth: int | None = None, target=None, theta: float = 0.5, ax=None, cmap=None, linewidth: float = 0.8, s: float = 6, title: str | None = None, backend=None)

Plot the cells of a quadtree, its particles and the Barnes-Hut walk for a target.

Parameters

NameTypeDefaultDescription
treeobjectNoneA QuadtreeCells, a tree with tree-d-3d’s attribute names (see quadtree_cells()), or None to build one from points (build_quadtree() with its defaults).
pointsarrayNone(2, N) or (N, 2) particle positions, drawn as dots. Default: none.
color('depth', 'count')"depth"Color the outlines by depth, or the leaves by the particles they hold (needs counts), with a color bar; None draws them in one gray. Default: "depth".
point_colorarrayNone(N,) values to color the particles by, e.g. their charge, on a diverging map symmetric about zero. Default: one color.
leaves_onlyboolFalseDraw only the leaves, the cells that hold particles. Default: False.
max_depthintNoneDraw no cells deeper than this. Default: all.
target(float, float)NoneA point to show a Barnes-Hut walk for (barnes_hut_walk()): the cells taken as multipoles and the leaves summed directly are outlined boldly. Default: none.
thetafloat0.5The opening angle of the walk. Default: 0.5.
axmatplotlib.axes.AxesNoneThe axes to draw into. Default: a new figure.
cmapstr or matplotlib.colors.ColormapNoneThe colormap of the outlines. Default: "viridis".
linewidthfloat0.8The width of the outlines in points. Default: 0.8.
sfloat6The size of the particle dots. Default: 6.
titlestrNoneThe title. Default: the number of cells, or the walk’s counts with a target.
backend('matplotlib', 'plotly', 'tikz')"matplotlib"Draw with this backend; default: the one of plasma_plots.set_backend().

Returns

PlotResult
The figure and axes, with the cells in data["cells"] and, with a target, the walk’s masks in data["walk"].

Raises

ValueError
If color is unknown, "count" has no counts, or neither a tree nor points are given.

Examples

>>> plot_quadtree(points=positions) # builds the tree
>>> plot_quadtree(tree, points=tree.pos, target=(0.1, 0.4), theta=0.7)
>>> plot_quadtree(tree, color="count", leaves_only=True, backend="plotly")

repeat_periodicfunction#

def repeat_periodic(data: xr.DataArray | xr.Dataset, *, poloidal_period: int = 1, toroidal_period: int = 1, R0: float = 0.0, Z0: float = 0.0, dims: tuple[str, str] | None = None) -> xr.DataArray | xr.Dataset

Copy a poloidal/toroidal sector to the full periodic domain.

The copies retain the values of data and extend its logical coordinates by one sector per copy. Attached X, Y and Z coordinates are rotated around the toroidal axis and around the circular poloidal axis, respectively. This is useful for plotting a Struphy run whose mapping covers only one of several identical sectors.

Parameters

NameTypeDefaultDescription
dataxarray.DataArray or xarray.DatasetrequiredThe field or collection of fields. Physical coordinates are transformed when all of X, Y and Z are present; without them only the data and logical coordinates are repeated.
poloidal_periodint1Number of copies represented by the input in the poloidal and toroidal directions. A value of one leaves that direction unchanged. Default: one.
toroidal_periodint1Number of copies represented by the input in the poloidal and toroidal directions. A value of one leaves that direction unchanged. Default: one.
R0float0.0Centre of the circular poloidal rotation in the (R, Z) plane. R0 is normally the major radius of a Struphy torus. Default: zero.
Z0float0.0Centre of the circular poloidal rotation in the (R, Z) plane. R0 is normally the major radius of a Struphy torus. Default: zero.
dimstuple of strNoneNames of the poloidal and toroidal dimensions. Default: the second and third logical dimensions, e.g. ("eta2", "eta3").

Returns

xarray.DataArray or xarray.Dataset
data copied over the requested full periodic domain.

Raises

ValueError
If a period is not a positive integer or a requested dimension is absent.

Examples

>>> full = repeat_periodic(phi, poloidal_period=2, toroidal_period=6, R0=3.0)
>>> full.sizes["eta3"] == 6 * phi.sizes["eta3"]
True

save_figurefunction#

def save_figure(figure, name, *, formats=('html', 'png', 'plotly.json'), show: bool = False, frame: int | None = None, still=None, width: int = 1100, height: int = 650, scale: float = 2.0, dark: bool = False, posters: bool = False) -> list[str]

Save a figure in several formats at once, as <name>.<format>.

The defaults write an interactive page, an image and the figure JSON of a Plotly figure: the three files a web page needs. Like PlotResult.save(), this does nothing on MPI ranks other than 0.

Parameters

NameTypeDefaultDescription
figure(PlotResult, Figure, plotly.graph_objects.Figure or matplotlib.figure.Figure)requiredWhat to save: the result of a plot (e.g. with backend="plotly"), a figure of plasma_plots.figure(), or a figure made some other way.
namestr or pathlib.PathrequiredThe files’ path without the format, e.g. "maxwell-wave" or "figures/energy".
formatssequence of str('html', 'png', 'plotly.json')The formats, each appended to name after a dot; the last extension picks how it is written, as in PlotResult.save(). Default: ("html", "png", "plotly.json").
showboolFalseShow the figure first. Default: False.
frameintNoneFor the image of a Plotly animation: the frame it shows (e.g. -1 for the last). The page and the JSON keep the whole animation. Default: the first frame.
stillplotly.graph_objects.FigureNoneA figure that the image shows instead, e.g. a view of an animation that is none of its frames. The page and the JSON keep figure.
widthint1100Width of an image of a Plotly figure, in layout pixels. Default: 1100.
heightint650Height of an image of a Plotly figure, in layout pixels. Default: 650.
scalefloat2.0Resolution factor of an image of a Plotly figure. Default: 2.
darkboolFalseFor a Matplotlib figure, also write each image as <name>.dark.<format>, recoloured for a dark page with a transparent background (plasma_plots.styles.to_dark()); the docs theme shows it in dark mode. Default: False.
postersboolFalseFor a Plotly figure, also write <name>.png and <name>.dark.png, pictures for a docs page in light and dark mode (plasma_plots.plotly_backend.save_posters(); needs kaleido). Default: False.

Returns

list of str
The paths written; empty on MPI ranks other than 0.

Examples

>>> dispersion = spectrum.plasma.plot.dispersion(kmin=0, backend="plotly")
>>> # maxwell-wave.html, .png, .plotly.json
>>> save_figure(dispersion, "maxwell-wave", show=True)
>>> save_figure(movie, "phase-space", frame=len(movie.fig.frames) // 2)
>>> save_figure(
... go.Figure(go.Scatter(x=t, y=energy)), "energy", formats=("html",)
... )

scenefunction#

def scene(plotter, *, alt: str | None = None, title: str | None = None, window_size=None, backend: Literal['vtkjs', 'plotly'] = 'vtkjs', decimate: float | None = None) -> Scene

Show a pyvista.Plotter as an interactive 3-D scene in a notebook.

As the last expression of a cell, the result displays as a standalone vtk.js page (text/html) plus a screenshot (image/png). Jupyter shows the page; docs sites built from the notebook show the screenshot and swap in the scene on click. alt and title travel in the output’s "pyvista-scene" metadata.

The screenshot needs an off-screen plotter: plotters created in a notebook are, and in a script set pyvista.OFF_SCREEN = True (or pass off_screen=True) before creating one. The export needs trame-pyvista: pip install "plasma-plots[scene]".

With backend="plotly" the scene displays as a Plotly 3-D figure instead (scene_to_plotly()): lighter, themed like the page and with values on hover, but without vtk.js’ rendering of large meshes. It needs neither a screenshot nor trame.

Parameters

NameTypeDefaultDescription
plotterpyvista.PlotterrequiredThe scene, e.g. from phi.plasma.plot.isosurface(...). Set its camera first.
altstrNoneA text alternative for the screenshot.
titlestrNoneA title for the scene, e.g. of the frame it is shown in.
window_size(int, int)NoneThe screenshot’s size in pixels. Default: the plotter’s window size.
backend('vtkjs', 'plotly')"vtkjs"A vtk.js page with a screenshot, or a Plotly figure. Default: "vtkjs".
decimatefloatNoneFraction of each surface’s triangles to drop in the vtk.js export. Default: none.

Returns

Scene
Displays itself in Jupyter; .save_png(path) and .save_html(path) write the two files, e.g. for a docs page.

Examples

>>> plotter = phi.plasma.plot.isosurface(values=[-0.5, 0.5], t=-1)
>>> plasma_plots.scene(plotter, alt="Two isosurfaces of phi")

scene_to_plotlyfunction#

def scene_to_plotly(plotter, *, max_faces: int | None = 200000)

Convert a pyvista.Plotter into an interactive Plotly 3-D figure.

Surfaces become Mesh3d traces (colored by their scalars on the plotter’s color scale, or in their solid color), lines and point sets Scatter3d traces, each with its opacity. The first colored surface carries a color bar titled like the plotter’s scalar bar. The camera follows the plotter’s. A Plotly figure is lighter than a vtk.js page (no viewer inlined), follows the page’s theme and shows values on hover; prefer the vtk.js scene of scene() for very large meshes.

Parameters

NameTypeDefaultDescription
plotterpyvista.PlotterrequiredThe scene.
max_facesint or None200000Surfaces with more triangles are decimated to about this many (None keeps them). Default: 200 000.

Returns

plotly.graph_objects.Figure
The figure.

Examples

>>> plotter = torus.mod_B.plasma.plot.slices_3d(cuts={"rho": [1.0]})
>>> scene_to_plotly(plotter).show()

set_backendfunction#

def set_backend(backend: str) -> str

Set the backend of every plot that does not pass backend= itself.

Parameters

NameTypeDefaultDescription
backend('matplotlib', 'plotly', 'tikz')"matplotlib"The new default ("tikz": see plasma_plots.tikz_backend).

Returns

str
The previous default, e.g. to restore it afterwards.

Raises

ValueError
If backend is not "matplotlib", "plotly" or "tikz".

Examples

>>> previous = plasma_plots.set_backend("plotly")
>>> phi.plasma.plot.slice(t=-1, eta3=0) # a Plotly figure
>>> plasma_plots.set_backend(previous)

set_mathfunction#

def set_math(mode: str) -> str

Set how the formulas of labels (Matplotlib’s $...$ mathtext) reach Plotly figures.

With "unicode" (the default) a formula becomes Unicode text with sub- and superscripts, which every Plotly front end shows. With "latex" a label with a formula is kept as LaTeX, one $...$ formula per label (the text around it in \text{...}), which plotly.js typesets with MathJax: on the max-models docs sites (the theme’s PlotlyFigure loads MathJax for such figures), in the pictures kaleido draws, and in the HTML pages save() writes (which load MathJax from a CDN). Hover labels, which plotly.js does not typeset, keep the Unicode form. JupyterLab may show the LaTeX as written. The mode applies when a figure is converted, so set it before plotting.

Parameters

NameTypeDefaultDescription
mode('unicode', 'latex')"unicode"The new mode.

Returns

str
The previous mode, e.g. to restore it afterwards.

Raises

ValueError
If mode is not "unicode" or "latex".

Examples

>>> plasma_plots.set_backend("plotly")
>>> plasma_plots.set_math("latex") # e.g. in the first cell of a docs notebook

set_stylefunction#

def set_style(name: str = 'default', **overrides) -> None

Set the style of every later plot.

Parameters

NameTypeDefaultDescription
name('default', 'colorblind', 'paper', 'dark', 'bare')"default"The style (see STYLES). Default: "default", the plots’ usual style.
**overrides{}Matplotlib rcParams to change on top of the style, with dots written as underscores, e.g. figure_dpi=150.

Raises

ValueError
If there is no style of that name, or an override is not a Matplotlib rcParams name.

Examples

>>> plasma_plots.set_style("colorblind")
>>> plasma_plots.set_style("paper", figure_figsize=(3.4, 3.0))

stylefunction#

def style(name: str, **overrides)

Draw with a style inside a with block.

Inside the block the style also applies to plain Matplotlib figures, e.g. a colorbar or an annotation added to a plot of plasma-plots.

Parameters

NameTypeDefaultDescription
name('default', 'colorblind', 'paper', 'dark', 'bare')"default"The style (see STYLES).
**overrides{}Matplotlib rcParams to change on top of the style, with dots written as underscores, e.g. figure_dpi=150.

Yields

dict
The rcParams in effect.

Raises

ValueError
If there is no style of that name, or an override is not a Matplotlib rcParams name.

Examples

>>> with plasma_plots.style("dark"):
... energy.plasma.plot.timeseries().save("energy_dark.png")