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.plotandout.analysison a StruphyOutput: whole-run plots and diagnostics.array.plasma.plot,.analysisand.dataon everyxarray.DataArray, e.g. a product fromout.evaluate("em_fields/phi").dataset.plasma.plot,.analysisand.dataon 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
| Name | Description |
|---|---|
PlasmaAccessor | Struphy diagnostics of one array: array.plasma.plot, .analysis and .data. |
SkippedPlot | What a plot returns on MPI ranks other than 0, where nothing is drawn. |
Functions
| Name | Description |
|---|---|
animate_quadtree | Animate a quadtree that follows moving particles: the cells and particles of every frame. |
figure | Compose several plots into one figure, drawn with Matplotlib, or as one Plotly or TikZ figure. |
from_boundary | A ConStellaration plasma boundary as a surface Dataset, with its minor radius. |
from_coilset | Every coil of a coilset as points along its curve, with currents and curvatures. |
from_desc | Evaluate DESC quantities on a grid, as a Dataset in plasma-plots' conventions. |
from_gvec | Return GVEC evaluations in plasma-plots' conventions; see plasma_plots.gvec. |
get_backend | Return the backend of plots that do not pass backend= themselves. |
get_math | Return how the formulas of labels reach Plotly figures. |
get_style | Return the name of the current style. |
is_plotting_rank | Tell whether this process draws plots and writes their files. |
mpi_rank | Return this process' rank in MPI_COMM_WORLD, without initializing MPI. |
plot_domain | Draw a simulation domain with its objects and their measurements, as a technical drawing. |
plot_quadtree | Plot the cells of a quadtree, its particles and the Barnes-Hut walk for a target. |
repeat_periodic | Copy a poloidal/toroidal sector to the full periodic domain. |
save_figure | Save a figure in several formats at once, as <name>.<format>. |
scene | Show a pyvista.Plotter as an interactive 3-D scene in a notebook. |
scene_to_plotly | Convert a pyvista.Plotter into an interactive Plotly 3-D figure. |
set_backend | Set the backend of every plot that does not pass backend= itself. |
set_math | Set how the formulas of labels (Matplotlib's $...$ mathtext) reach Plotly figures. |
set_style | Set the style of every later plot. |
style | Draw 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#
plasma_plots.accessorsView sourceclass 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#
plasma_plots.mpiView sourceclass 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
Examples
>>> skipped = SkippedPlot("plot_slice", rank=1)>>> skipped.save("slice.png").fig is skipped # nothing is writtenTrue>>> list(skipped), bool(skipped)([], False)animate_quadtreefunction#
plasma_plots.treesView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
trees | sequence | None | One 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). |
points | sequence of array | None | One (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_color | array or sequence of array | None | Values 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. |
times | sequence of float | None | The time (or other sweep value) of each frame, for the titles and the slider of the Plotly version. Default: the frame numbers. |
sweep | str | '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_only | bool | False | Draw only the leaves. Default: False. |
max_depth | int | None | Draw no cells deeper than this. Default: all. |
leaf_capacity | int | 8 | The most points a leaf of a tree built from points holds. Default: 8. |
bounds | (float, float, float) | None | The 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) | None | The axes limits (x_min, x_max, y_min, y_max), fixed over the animation. Default: the
smallest square holding every frame’s root cell. |
cmap | str or matplotlib.colors.Colormap | None | The colormap of the outlines. Default: "viridis" without its darkest fifth. |
point_cmap | str or matplotlib.colors.Colormap | None | The colormap of point_color. Default: "coolwarm". |
linewidth | float | 0.8 | The width of the outlines in points. Default: 0.8. |
s | float | 6 | The size of the particle dots. Default: 6. |
interval | int | 100 | The delay between frames, in milliseconds. Default: 100. |
max_frames | int | None | Keep at most this many frames, evenly spaced (the first and last included), e.g. to keep a Plotly animation small. Default: all. |
title | str | None | A 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
coloris 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#
plasma_plots.figuresView sourcedef 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) -> FigureCompose 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
| Name | Type | Default | Description |
|---|---|---|---|
nrows | int | 1 | The number of rows of panels. Default: 1. |
ncols | int | 1 | The 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. |
sharex | bool or {'row', 'col', 'all'} | False | Share the horizontal axes (and their zoom, in Plotly), as for matplotlib.pyplot.subplots.
Default: False. |
sharey | bool or {'row', 'col', 'all'} | False | Share the vertical axes. Default: False. |
figsize | (float, float) | None | The size in inches. Default: from the number of panels. |
title | str | None | A title above all panels. Default: none. |
caption | str | None | A 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].ratefrom_boundaryfunction#
plasma_plots.coilsView sourcedef from_boundary(boundary, *, theta=64, zeta=None) -> xr.DatasetA 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
| Name | Type | Default | Description |
|---|---|---|---|
boundary | (dict, str or object) | required | r_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. |
theta | int or sequence of float | 64 | Poloidal angles: an integer as that many points over [0, 2π), else the values.
Default: 64. |
zeta | int or sequence of float | None | Toroidal 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.DatasetR(m) over(rho, theta, zeta)with coordinatesX,Y,Z, the angles’period, and the attributesnfp,major_radius(them = n = 0coefficient ofR, m) andminor_radius(m):sqrt(A / π)of the mean areaAof the cross-sections at constantphi, the length CoilStellaration’snormalized_*metrics divide by.
Raises
TypeError- If
boundaryis none of the accepted kinds. ValueError- If keys are missing or
r_coshas 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#
plasma_plots.coilsView sourcedef from_coilset(coilset, *, n_points: int = 128) -> xr.DatasetEvery 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
| Name | Type | Default | Description |
|---|---|---|---|
coilset | (dict, str, object or desc.coils.CoilSet) | required | A 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_points | int | 128 | Points along each coil, equally spaced in s over [0, 2π). Default: 128. |
Returns
xarray.Dataset- Over
coilands: the coordinatesX,Y,Z(m),unique_coil(the stored coil each one copies),mirroredandfield_period; the variablescurrent(A, per coil, reversed on the mirrored coils),length(m, per coil) andcurvature(1/m, along each coil); the attributesnfp,stellarator_symmetricandfourier_order.
Raises
TypeError- If
coilsetis 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 periodsFrozen({'coil': 30, 's': 128})>>> coils.curvature.max(dim="s") # the sharpest bend of each coilfrom_descfunction#
plasma_plots.descView sourcedef 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.DatasetEvaluate DESC quantities on a grid, as a Dataset in plasma-plots’ conventions.
See plasma_plots.desc for what the Dataset contains.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
eq | desc.equilibrium.Equilibrium | required | The equilibrium, e.g. desc.io.load("eq.h5") or desc.examples.get("W7-X"). |
names | str or sequence of str | required | DESC’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. |
rho | int, float or sequence of float | 11 | The flux surfaces: an integer as that many points from 0 to 1, a float or a sequence as the values. Default: 11 points. |
theta | int, float or sequence of float | 32 | The poloidal angles (PEST angles with sfl="pest"): an integer as that many points
over [0, 2π), else the values. Default: 32 points. |
zeta | int, float or sequence of float | 24 | The 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(ortheta_P) andzeta, vectors alongcomponent, with the coordinatesX,Y,Z, labels, units, the angles’periodand thenfpattribute.
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#
plasma_plots.gvecView sourcedef from_gvec(data: xr.DataArray | xr.Dataset, *, nfp: int | None = None) -> xr.DataArray | xr.DatasetReturn 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
| Name | Type | Default | Description |
|---|---|---|---|
data | xarray.Dataset or xarray.DataArray | required | A Dataset from state.evaluate(...), state.evaluate_sfl(...) or gvec.Evaluations
(also after to_netcdf and open_dataset), or one of its variables. |
nfp | int | None | The 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_Bandcomponent, the coordinatesX,Y,Z(frompos),X1,X2, labels from thesymbolattributes, the angles’periodand thenfpattribute.
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#
plasma_plots.plotly_backendView sourcedef get_backend() -> strReturn the backend of plots that do not pass backend= themselves.
Returns
str"matplotlib"(the default),"plotly"or"tikz".
get_mathfunction#
plasma_plots.plotly_backendView sourcedef get_math() -> strReturn how the formulas of labels reach Plotly figures.
Returns
str"unicode"(the default) or"latex".
get_stylefunction#
plasma_plots.stylesView sourcedef get_style() -> strReturn the name of the current style.
is_plotting_rankfunction#
plasma_plots.mpiView sourcedef is_plotting_rank() -> boolTell whether this process draws plots and writes their files.
Returns
boolTrueon rank 0 of an MPI job and in any process outside one.
mpi_rankfunction#
plasma_plots.mpiView sourcedef mpi_rank() -> intReturn 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 run0plot_domainfunction#
plasma_plots.geometryView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
domain | (simgeometry.SimulationDomain, GeometryCollection, shape, dict or list) | required | The 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. |
x | float | None | The position of the slice through a 3-D domain; exactly one of them. |
y | float | None | The position of the slice through a 3-D domain; exactly one of them. |
z | float | None | The position of the slice through a 3-D domain; exactly one of them. |
views | sequence of dict or str | None | Several 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) | None | The 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) | True | The 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. |
measure | sequence of str | None | The names of the objects to measure; the others are drawn without measurements. Default: all of them. |
extra_dimensions | sequence | None | Measurements 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". |
angles | bool | False | Mark 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. |
boundaries | bool or dict | False | Write 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. |
scale | float | 1.0 | Multiply every coordinate, e.g. 1e3 to draw a domain in metres in mm. Default: 1. |
unit | str | None | The unit of the plotted coordinates, written after every measurement and in the axis labels. Default: none. |
fmt | str | '{:.4g}' | The format of the measured values. Default: "{:.4g}". |
grid | bool | False | Draw the lines of the domain’s grid (a SimulationDomain). Default: False. |
cells | bool | None | Measure 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. |
names | bool | True | A legend naming the objects. Default: True. |
axes | bool | None | Show the axes with their ticks. Default: hidden when measurements are drawn, as in a drawing, shown otherwise. |
colors | dict or sequence | None | The fill colors, by object name or in their order; the collection’s styles apply
first. Default: Matplotlib’s color cycle. |
opacity | float | 0.7 | The opacity of the fills. Default: 0.7. |
hatch | bool or str | None | Hatch the objects as the section faces of a technical drawing: True for "///",
or any Matplotlib hatch; with backend="tikz" a TikZ pattern.
Default: none. |
resolution | int | 256 | Samples per axis when tracing the outline of a sliced 3-D object. Default: 256. |
ax | matplotlib.axes.Axes | None | Draw 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) | None | The width of the new figure in inches; a height can only shrink the scale. Default: Matplotlib’s. |
title | str | None | The 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 indata:"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 ofdimension_chains(),"boundaries"the side labels,"cells"the cell size and count per axis,"radii","angles"(object, degrees) and"extra"the lengths ofextra_dimensions; all in the plotted units. Withviews,data["views"]is a list of these.
Raises
TypeError- If the slice does not fit the domain’s dimension,
domainis not a domain, orviewsis combined withx,y,zorax. ValueError- If the slice lies outside the domain, an option has an unknown value,
measurenames unknown objects, orcells=Trueis 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#
plasma_plots.treesView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
tree | object | None | A 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). |
points | array | None | (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_color | array | None | (N,) values to color the particles by, e.g. their charge, on a diverging map
symmetric about zero. Default: one color. |
leaves_only | bool | False | Draw only the leaves, the cells that hold particles. Default: False. |
max_depth | int | None | Draw no cells deeper than this. Default: all. |
target | (float, float) | None | A 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. |
theta | float | 0.5 | The opening angle of the walk. Default: 0.5. |
ax | matplotlib.axes.Axes | None | The axes to draw into. Default: a new figure. |
cmap | str or matplotlib.colors.Colormap | None | The colormap of the outlines. Default: "viridis". |
linewidth | float | 0.8 | The width of the outlines in points. Default: 0.8. |
s | float | 6 | The size of the particle dots. Default: 6. |
title | str | None | The 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 indata["walk"].
Raises
ValueError- If
coloris 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#
plasma_plots.arraysView sourcedef 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.DatasetCopy 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
| Name | Type | Default | Description |
|---|---|---|---|
data | xarray.DataArray or xarray.Dataset | required | The 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_period | int | 1 | Number of copies represented by the input in the poloidal and toroidal directions. A value of one leaves that direction unchanged. Default: one. |
toroidal_period | int | 1 | Number of copies represented by the input in the poloidal and toroidal directions. A value of one leaves that direction unchanged. Default: one. |
R0 | float | 0.0 | Centre of the circular poloidal rotation in the (R, Z) plane. R0 is
normally the major radius of a Struphy torus. Default: zero. |
Z0 | float | 0.0 | Centre of the circular poloidal rotation in the (R, Z) plane. R0 is
normally the major radius of a Struphy torus. Default: zero. |
dims | tuple of str | None | Names of the poloidal and toroidal dimensions. Default: the second and third
logical dimensions, e.g. ("eta2", "eta3"). |
Returns
xarray.DataArray or xarray.Datasetdatacopied 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"]Truesave_figurefunction#
plasma_plots.plottingView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
figure | (PlotResult, Figure, plotly.graph_objects.Figure or matplotlib.figure.Figure) | required | What 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. |
name | str or pathlib.Path | required | The files’ path without the format, e.g. "maxwell-wave" or "figures/energy". |
formats | sequence 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"). |
show | bool | False | Show the figure first. Default: False. |
frame | int | None | For 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. |
still | plotly.graph_objects.Figure | None | A 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. |
width | int | 1100 | Width of an image of a Plotly figure, in layout pixels. Default: 1100. |
height | int | 650 | Height of an image of a Plotly figure, in layout pixels. Default: 650. |
scale | float | 2.0 | Resolution factor of an image of a Plotly figure. Default: 2. |
dark | bool | False | For 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. |
posters | bool | False | For 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#
plasma_plots.pyvista_plotsView sourcedef scene(plotter, *, alt: str | None = None, title: str | None = None, window_size=None, backend: Literal['vtkjs', 'plotly'] = 'vtkjs', decimate: float | None = None) -> SceneShow 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
| Name | Type | Default | Description |
|---|---|---|---|
plotter | pyvista.Plotter | required | The scene, e.g. from phi.plasma.plot.isosurface(...). Set its camera first. |
alt | str | None | A text alternative for the screenshot. |
title | str | None | A title for the scene, e.g. of the frame it is shown in. |
window_size | (int, int) | None | The 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". |
decimate | float | None | Fraction 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#
plasma_plots.pyvista_plotsView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
plotter | pyvista.Plotter | required | The scene. |
max_faces | int or None | 200000 | Surfaces 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#
plasma_plots.plotly_backendView sourcedef set_backend(backend: str) -> strSet the backend of every plot that does not pass backend= itself.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
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
backendis 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#
plasma_plots.plotly_backendView sourcedef set_math(mode: str) -> strSet 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
| Name | Type | Default | Description |
|---|---|---|---|
mode | ('unicode', 'latex') | "unicode" | The new mode. |
Returns
str- The previous mode, e.g. to restore it afterwards.
Raises
ValueError- If
modeis not"unicode"or"latex".
Examples
>>> plasma_plots.set_backend("plotly")>>> plasma_plots.set_math("latex") # e.g. in the first cell of a docs notebookset_stylefunction#
plasma_plots.stylesView sourcedef set_style(name: str = 'default', **overrides) -> NoneSet the style of every later plot.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
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
rcParamsname.
Examples
>>> plasma_plots.set_style("colorblind")>>> plasma_plots.set_style("paper", figure_figsize=(3.4, 3.0))stylefunction#
plasma_plots.stylesView sourcedef 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
| Name | Type | Default | Description |
|---|---|---|---|
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
rcParamsin effect.
Raises
ValueError- If there is no style of that name, or an override is not a Matplotlib
rcParamsname.
Examples
>>> with plasma_plots.style("dark"):... energy.plasma.plot.timeseries().save("energy_dark.png")