Skip to content

plasma_plots.gallery

Output helpers of the struphy-hub example gallery: figure files, profiling exports and metadata.

The example scripts on https://struphy-hub.github.io/examples/ use these helpers to write their results, so that a copied example runs on its own with pip install "plasma-plots[gallery]". Every helper writes to the current directory and names its files after the example’s stem: <stem>.png, <stem>.plotly.json and <stem>.html for each figure, <stem>.metadata.json for the measured values, and <stem>-profile.h5 with its plot data for the profiling. The website’s build reads exactly these files.

The scripts also run under MPI (mpirun -n 4 python <script>.py): the simulation, the post-processing and the analysis run on every rank, and only rank 0 writes files. The helpers take care of that, so a script needs no rank checks of its own.

Importing this module sets Struphy’s logging level to INFO, which prints one block per time step (step number, times, wall clock and scalar quantities), as one wants to see in a CI log.

Attributes

NameDescription
GANTT_MAX_INTERVALSNo description.

Functions

NameDescription
barrierWait until every MPI rank got here; does nothing in a serial run.
export_profilingExport the scope-profiler data of a run made with profiling_activated=True.
heatmap_figureDraw a two-dimensional array as a Plotly heatmap.
heatmap_movieAnimate a three-dimensional array as a Plotly heatmap, one frame per sweep value.
is_rootTell whether this process writes files: MPI rank 0, or a serial run.
merge_metadataAdd result fields to <stem>.metadata.json, keeping the fields already there.
save_extra_figureSave an additional figure of an example and return its entry for the figures metadata.
save_figureWrite static PNG, Plotly JSON and standalone HTML versions of a figure.
space_time_figureDraw a space-time map of a field: space along x, time up, colors symmetric about zero.

GANTT_MAX_INTERVALSattributemodule attribute#

GANTT_MAX_INTERVALS = 5000

barrierfunction#

def barrier() -> None

Wait until every MPI rank got here; does nothing in a serial run.

Use it, for example, before rank 0 reads a file that the ranks wrote together.

export_profilingfunction#

def export_profiling(sim, stem: str) -> dict

Export the scope-profiler data of a run made with profiling_activated=True.

Writes the raw HDF5 (<stem>-profile.h5) and the plot data that the example page draws as Plotly figures: durations, gantt and region statistics as JSON. Needs scope-profiler[pproc], which the gallery extra installs. Call it on every rank; only rank 0 writes.

Parameters

NameTypeDescription
simstruphy.SimulationThe simulation, after sim.run(profiling_activated=True).
stemstrThe example’s stem, which names the files.

Returns

dict
The metadata fields that point to the files, for merge_metadata().

Examples

>>> profiling = export_profiling(sim, "weak-landau-damping")
>>> merge_metadata("weak-landau-damping", **profiling)

heatmap_figurefunction#

def heatmap_figure(data, *, x: str, y: str, title: str, xaxis_title: str, yaxis_title: str, colorbar_title: str = '', colorscale: str = 'Viridis', zmin=None, zmax=None, x_values=None, y_values=None)

Draw a two-dimensional array as a Plotly heatmap.

Parameters

NameTypeDefaultDescription
dataxarray.DataArrayrequiredThe values, with the two dimensions x and y.
xstrrequiredThe dimension along the horizontal axis.
ystrrequiredThe dimension along the vertical axis.
titlestrrequiredTitle of the figure.
xaxis_titlestrrequiredTitle of the horizontal axis.
yaxis_titlestrrequiredTitle of the vertical axis.
colorbar_titlestr''Title of the color bar.
colorscalestr'Viridis'Plotly color scale. Default: "Viridis".
zminfloatNoneLower end of the color scale. Default: the data’s minimum.
zmaxfloatNoneUpper end of the color scale. Default: the data’s maximum.
x_valuesarrayNoneReplaces the coordinate of x, e.g. to plot a logical coordinate in physical length.
y_valuesarrayNoneReplaces the coordinate of y.

Returns

plotly.graph_objects.Figure
The heatmap.

Examples

>>> heatmap_figure(
... f.plasma.analysis.spatial_average(),
... x="t",
... y="v1",
... title="f(v, t)",
... xaxis_title="t [a.u.]",
... yaxis_title="v [a.u.]",
... )

heatmap_moviefunction#

def heatmap_movie(data, *, x: str, y: str, title: str, xaxis_title: str, yaxis_title: str, colorbar_title: str = '', sweep: str = 't', colorscale: str = 'Viridis', zmin=0.0, zmax=None, x_values=None, y_values=None, max_frames: int = 150)

Animate a three-dimensional array as a Plotly heatmap, one frame per sweep value.

A frame per saved step would embed tens of megabytes in the page, so at most max_frames evenly spaced frames are kept.

Parameters

NameTypeDefaultDescription
dataxarray.DataArrayrequiredThe values, with the dimensions x, y and sweep.
xstrrequiredThe dimension along the horizontal axis.
ystrrequiredThe dimension along the vertical axis.
titlestrrequiredTitle of the figure.
xaxis_titlestrrequiredTitle of the horizontal axis.
yaxis_titlestrrequiredTitle of the vertical axis.
colorbar_titlestr''Title of the color bar.
sweepstr't'The dimension the frames run over. Default: "t".
colorscalestr'Viridis'Plotly color scale. Default: "Viridis".
zminfloat0.0Lower end of the color scale. Default: 0.
zmaxfloatNoneUpper end of the color scale. Default: each frame’s maximum.
x_valuesarrayNoneReplaces the coordinate of x, e.g. in physical length.
y_valuesarrayNoneReplaces the coordinate of y.
max_framesint150The most frames kept. Default: 150.

Returns

figureplotly.graph_objects.Figure
The animated heatmap, with a play button and a slider.
static_znumpy.ndarray
A well-developed frame from the middle of the sweep, for save_figure(..., static_z=static_z).

Examples

>>> f = out.evaluate("kinetic_ions/e1_v1_density/f")
>>> movie, static_z = heatmap_movie(
... f,
... x="eta1",
... y="v1",
... title="f(x, v)",
... xaxis_title="x [a.u.]",
... yaxis_title="v [a.u.]",
... )
>>> save_figure(
... movie,
... "two-stream-instability",
... suffix="-phase-space",
... static_z=static_z,
... )

is_rootfunction#

def is_root() -> bool

Tell whether this process writes files: MPI rank 0, or a serial run.

Returns

bool
True on rank 0 and in a serial run.

Examples

>>> if is_root():
... print(f"measured rate: {rate:.4f}")

merge_metadatafunction#

def merge_metadata(stem: str, **fields) -> Path

Add result fields to <stem>.metadata.json, keeping the fields already there.

Only rank 0 writes.

Parameters

NameTypeDefaultDescription
stemstrrequiredThe example’s stem, which names the file.
**fields{}The fields to add or replace, e.g. measured values, figures from save_extra_figure() and the fields export_profiling() returns.

Returns

pathlib.Path
The metadata file.

Raises

RuntimeError
If a value is a non-finite float: NaN and Infinity are not valid JSON, and a non-finite result is a broken run.

Examples

>>> merge_metadata(
... "weak-landau-damping", measuredDampingRate=rate, **profiling
... )

save_extra_figurefunction#

def save_extra_figure(figure, stem: str, key: str, *, alt: str, caption: str, static_z=None, static_active=None) -> dict

Save an additional figure of an example and return its entry for the figures metadata.

Writes <stem>-<key>.png, .plotly.json and .html with save_figure(). The example page shows every entry of figures below its main figure: pass the list to merge_metadata(stem, figures=[...]).

Parameters

NameTypeDefaultDescription
figureplotly.graph_objects.FigurerequiredThe figure to save.
stemstrrequiredThe example’s stem.
keystrrequiredNames the figure within the example, and its files.
altstrrequiredAlternative text of the image.
captionstrrequiredCaption below the figure on the example page.
static_zarrayNoneReplaces the heatmap of the first trace in the PNG only; see save_figure().
static_activeintNoneThe slider position shown in the PNG; see save_figure().

Returns

dict
The entry for the figures list of merge_metadata(): key, interactive and thumbnail paths, alt and caption.

Examples

>>> figures = [
... save_extra_figure(
... space_time,
... "weak-landau-damping",
... "space-time",
... alt="Space-time map of E",
... caption="E(x, t) of the run.",
... )
... ]
>>> merge_metadata("weak-landau-damping", figures=figures)

save_figurefunction#

def save_figure(figure, stem: str, *, width: int = 1100, height: int = 650, suffix: str = '', static_z=None, static_data=None, static_active=None) -> None

Write static PNG, Plotly JSON and standalone HTML versions of a figure.

The files are <stem><suffix>.png, .plotly.json and .html in the current directory. The PNG is also copied to ../images/examples/ when that directory exists, as the gallery thumbnail. Only rank 0 writes. Tick labels get scientific notation where the figure has not chosen a format.

An animation that starts at t = 0 can still have an informative static image: static_z or static_data replace what the PNG shows, and the JSON and HTML keep the animation.

Parameters

NameTypeDefaultDescription
figureplotly.graph_objects.FigurerequiredThe figure to save.
stemstrrequiredThe example’s stem, which names the files.
widthint1100Width of the PNG in pixels, before the factor 2 of its scale. Default: 1100.
heightint650Height of the PNG in pixels, before the factor 2 of its scale. Default: 650.
suffixstr''Appended to the stem, e.g. "-space-time" for an additional figure.
static_zarrayNoneReplaces the heatmap of the first trace in the PNG only, e.g. the static_z that heatmap_movie() returns.
static_datalist of plotly tracesNoneThe traces of the PNG, e.g. one frame’s data, drawn with the figure’s layout.
static_activeintNoneThe slider position shown in the PNG, with static_z or static_data.

Examples

>>> save_figure(figure, "weak-landau-damping")

space_time_figurefunction#

def space_time_figure(data, *, space: str, title: str, colorbar_title: str, xaxis_title: str = 'x [a.u.]', x_values=None, colorscale: str = 'RdBu')

Draw a space-time map of a field: space along x, time up, colors symmetric about zero.

Parameters

NameTypeDefaultDescription
dataxarray.DataArrayrequiredThe field, with the dimensions t and space.
spacestrrequiredThe spatial dimension, e.g. "eta1".
titlestrrequiredTitle of the figure.
colorbar_titlestrrequiredTitle of the color bar.
xaxis_titlestr'x [a.u.]'Title of the horizontal axis. Default: "x [a.u.]".
x_valuesarrayNoneReplaces the coordinate of space, e.g. in physical length.
colorscalestr'RdBu'Plotly color scale. Default: "RdBu".

Returns

plotly.graph_objects.Figure
The heatmap.

Examples

>>> e_x = out.evaluate("em_fields/e_field").isel(component=0, eta2=0, eta3=0)
>>> space_time_figure(e_x, space="eta1", title="E(x, t)", colorbar_title="E_x")