Skip to content
Projects

plasma_plots.charts

General charts of labeled data: parameter scans, breakdowns, cross sections, matrices.

These plots are not tied to a simulation’s grid; they take 1-D arrays over a parameter or a category, Datasets of such arrays, or plain dicts:

  • [plot_scan()][plot_scan]: a quantity over a scanned parameter with error bars or a shaded band, e.g. the beam divergence over the extraction voltage, from repeated runs or their spread;
  • [plot_breakdown()][plot_breakdown]: horizontal bars of parts of a total, e.g. the power deposited on each component of a beamline;
  • [plot_twin()][plot_twin] and [plot_stacked()][plot_stacked]: profiles over the same coordinate with two value axes, or one panel per profile;
  • [plot_cross_sections()][plot_cross_sections]: collision cross sections over energy, on log-log axes;
  • [plot_matrix()][plot_matrix]: the non-zero pattern or the values of a (sparse) matrix;
  • [plot_child_langmuir()][plot_child_langmuir]: a measured current density against the Child–Langmuir law;
  • [plot_variables()][plot_variables]: every variable of a Dataset in a grid of panels.

The accessors expose them as array.plasma.plot.scan, .breakdown, .twin, .stacked, .cross_sections, .matrix, .child_langmuir and dataset.plasma.plot.variables, .breakdown, .cross_sections.

Examples

>>> divergence.plasma.plot.scan(x="voltage", samples="seed", band=True)
>>> power.plasma.plot.breakdown() # power over a "component" dimension
>>> sigma.plasma.plot.cross_sections() # cross sections over "energy"

Functions

NameDescription
matrix_entriesThe non-zero entries of a matrix as rows, columns and values.
plot_breakdownDraw the parts of a total as horizontal bars, e.g. the power deposited per component.
plot_child_langmuirPlot a measured current density against the Child–Langmuir law of a planar diode.
plot_cross_sectionsPlot collision cross sections (or rate coefficients) over energy on log-log axes.
plot_matrixPlot the non-zero pattern or the values of a matrix, e.g. a solver's system matrix.
plot_scanPlot a quantity over a scanned parameter, with error bars or a shaded band.
plot_stackedPlot profiles in panels stacked over a shared horizontal axis, one row each.
plot_twinPlot two profiles over the same coordinate with a value axis each, left and right.
plot_variablesPlot every variable of a Dataset in a grid of panels, as a profile or a slice each.
prepare_breakdownThe parts plot_breakdown() draws, as one array over a category dimension.
prepare_scanThe values and errors plot_scan() draws.

matrix_entriesfunction#

def matrix_entries(matrix)

The non-zero entries of a matrix as rows, columns and values.

Parameters

NameTypeDescription
matrixarray_like, scipy.sparse matrix, dict or (rows, cols, values) tripleA dense 2-D array (or xarray.DataArray), a SciPy sparse matrix (anything with tocoo()), a dict with "row_indices", "col_indices", "values" and optionally "shape" (as picnic writes PETSc matrices), or a triple.

Returns

(numpy.ndarray, numpy.ndarray, numpy.ndarray, (int, int))
Rows, columns, values and the matrix shape.

Raises

ValueError
If a dense matrix is not two-dimensional.

plot_breakdownfunction#

def plot_breakdown(values, *, dim: str | None = None, ax=None, sort: bool = False, total: bool = False, annotate: bool = True, scale: float = 1.0, color=None, title: str | None = None, xlabel: str | None = None)

Draw the parts of a total as horizontal bars, e.g. the power deposited per component.

Parameters

NameTypeDefaultDescription
values(xarray.DataArray, xarray.Dataset or dict)requiredA 1-D array over a category dimension, a Dataset of scalar variables, or a dict of names to numbers (see prepare_breakdown()).
dimstrNoneThe category dimension of an array. Default: its only dimension.
axmatplotlib.axes.AxesNoneThe axes to draw into. Default: a new figure, its height from the number of parts.
sortboolFalseOrder the bars by value, the largest on top. Default: False, the given order from the top down.
totalboolFalseAdd the sum as the last bar. Default: False.
annotateboolTrueWrite each value, and its share of the sum, at the end of its bar. Default: True.
scalefloat1.0Multiply the values, e.g. 1e-6 for W shown in MW (give xlabel then). Default: 1.
colorstrNoneThe bar color. Default: the first color of the style.
titlestrNoneThe axes title. Default: the array’s label.
xlabelstrNoneThe value axis label. Default: the array’s label and units.

Returns

PlotResult
The figure, the axes, the bars, and in data["values"] the parts as drawn (see prepare_breakdown()).

Raises

ValueError
If an array is not one-dimensional, or a Dataset variable is not a scalar.

Examples

>>> plot_breakdown(
... {"duct": 0.8e6, "neutralizer": 2.1e6, "dump": 4.0e6},
... scale=1e-6,
... xlabel="P (MW)",
... )
>>> power.plasma.plot.breakdown(sort=True, total=True)

plot_child_langmuirfunction#

def plot_child_langmuir(measured, *, gap=None, voltage=None, mass=None, charge=None, initial_velocity: float = 0.0, show_error: bool = True, logx: bool = False, logy: bool = False, title: str | None = None)

Plot a measured current density against the Child–Langmuir law of a planar diode.

The theory is plasma_plots.theory.sheaths.child_langmuir(), J ∝ V^{3/2} / d², in SI units. Give the fixed one of gap and voltage; the measured array runs over the other.

Parameters

NameTypeDefaultDescription
measuredxarray.DataArray, (x, J) pair or dictrequiredThe current density in A/m² over the voltage in V (with gap) or over the gap in m (with voltage), or a dict of labels to these, e.g. one per code.
gapfloatNoneThe gap width d in m, for a current over voltage.
voltagefloatNoneThe voltage V in V, for a current over the gap width.
massfloatNoneThe particle mass in kg. Default: the electron mass.
chargefloatNoneThe particle charge in C. Default: e.
initial_velocityfloat0.0The injection speed in m/s (see child_langmuir()). Default: 0.
show_errorboolTrueAdd a panel with the relative difference to the law. Default: True.
logxboolFalseUse a logarithmic parameter axis. Default: False.
logyboolFalseUse a logarithmic current axis. Default: False.
titlestrNoneThe title. Default: "Space-charge-limited current".

Raises

ValueError
If not exactly one of gap and voltage is given.

Examples

>>> plot_child_langmuir(J_over_V, gap=0.01, mass=1.67e-27) # protons
>>> J.plasma.plot.child_langmuir(voltage=5e3, logx=True, logy=True)

plot_cross_sectionsfunction#

def plot_cross_sections(data, *, ax=None, reference=None, markers: bool = True, logx: bool = True, logy: bool = True, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None)

Plot collision cross sections (or rate coefficients) over energy on log-log axes.

Parameters

NameTypeDefaultDescription
dataxarray.DataArray, xarray.Dataset, dict or (energy, sigma) pairrequiredThe tabulated cross sections: a 1-D array over energy, a 2-D array over energy and a process dimension (one line per process), a Dataset (one line per variable), a dict of labels to any of these, or an (energy, sigma) pair.
axmatplotlib.axes.AxesNoneThe axes to draw into. Default: a new figure.
referencecallable, (energy, sigma) pair or dictNoneFits or theory to compare with, drawn as black lines over the tabulated range: a function of energy, a pair, or a dict of labels to these, e.g. {"Janev fit": plasma_plots.theory.negative_ions.electron_detachment_cross_section}. Default: none.
markersboolTrueMark the tabulated points. Default: True.
logxboolTrueUse a logarithmic energy axis. Default: True.
logyboolTrueUse a logarithmic cross-section axis. Default: True.
titlestrNoneThe axes title. Default: "Cross sections".
xlabelstrNoneThe energy axis label. Default: the coordinate’s label of the first array, else "energy".
ylabelstrNoneThe value axis label. Default: the value label of the first array, else "σ".

Returns

PlotResult
The figure, the axes and the drawn lines.

Raises

ValueError
If an array has more than two dimensions.

Examples

>>> plot_cross_sections(catalogue) # a Dataset of processes over "energy"
>>> sigma.plasma.plot.cross_sections(reference={"fit": fit})

plot_matrixfunction#

def plot_matrix(matrix, *, kind: str = 'pattern', ax=None, markersize: float | None = None, cmap=None, rank_boundaries=None, title: str | None = None)

Plot the non-zero pattern or the values of a matrix, e.g. a solver’s system matrix.

Parameters

NameTypeDefaultDescription
matrixarray_like, scipy.sparse matrix, dict or (rows, cols, values) triplerequiredThe matrix (see matrix_entries()).
kind('pattern', 'values')"pattern""pattern" marks each non-zero entry, colored by its sign; "values" colors the entries by value on a symmetric diverging scale. Default: "pattern".
axmatplotlib.axes.AxesNoneThe axes to draw into. Default: a new figure.
markersizefloatNoneThe marker size of a pattern. Default: from the matrix size.
cmapstr or matplotlib.colors.ColormapNoneThe colormap of kind="values". Default: "RdBu_r".
rank_boundariessequence of intNoneRow (and column) indices where the part of each MPI rank begins, e.g. PETSc’s ownership ranges, drawn as dashed lines. Default: none.
titlestrNoneThe axes title. Default: the shape and the number of non-zero entries.

Returns

PlotResult
The figure, the axes, the drawn artists, and in data the "shape" and the number of non-zero entries "nnz".

Raises

ValueError
If kind is not one of the two, or a dense matrix is not two-dimensional.

Examples

>>> plot_matrix(scipy.sparse.diags([1, -2, 1], [-1, 0, 1], shape=(40, 40)))
>>> plot_matrix(matrix_dict, rank_boundaries=matrix_dict["ownership_ranges"])

plot_scanfunction#

def plot_scan(data: xr.DataArray, *, x: str | None = None, error=None, samples: str | None = None, band: bool = False, ax=None, label: str | None = None, color=None, reference=None, logx: bool = False, logy: bool = False, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None)

Plot a quantity over a scanned parameter, with error bars or a shaded band.

Parameters

NameTypeDefaultDescription
dataxarray.DataArrayrequiredThe scanned quantity over the parameter x, or over x and samples.
xstrNoneThe scanned parameter. Default: the only dimension other than samples.
errorxarray.DataArray, array_like or (lower, upper) pairNoneThe error of each value: symmetric, or the distances below and above it. Default: the standard deviation over samples, if given, else none.
samplesstrNoneA dimension of repeated runs (seeds, shots) to average over. Default: none.
bandboolFalseShade the error as a band around a line instead of drawing error bars. Default: False.
axmatplotlib.axes.AxesNoneThe axes to draw into, e.g. to compare several scans. Default: a new figure.
labelstrNoneThe legend label; the axes then get a legend. Default: none.
colorstrNoneThe color. Default: the next color of the style.
referencecallable, (x, y) pair or dictNoneExpected curves, drawn as lines over the scanned range: a function of the parameter, an (x, y) pair, or a dict of labels to these. Default: none.
logxboolFalseUse a logarithmic parameter axis. Default: False.
logyboolFalseUse a logarithmic value axis. Default: False.
titlestrNoneThe axes title. Default: the array’s label.
xlabelstrNoneThe horizontal axis label. Default: the parameter’s label.
ylabelstrNoneThe value axis label. Default: the array’s label and units.

Returns

PlotResult
The figure, the axes, the drawn artists, and in data["scan"] the values and errors (see prepare_scan()).

Raises

ValueError
If more than one dimension remains besides samples, or the errors do not match.

Examples

>>> # mean and spread of five seeds per voltage
>>> plot_scan(divergence, samples="seed", band=True, reference=theory)
>>> plot_scan(growth, error=growth_error, label="PIC", ax=ax)

plot_stackedfunction#

def plot_stacked(profiles, *, sharex: bool = True, height_ratios=None, step=None, logy: bool = False, title: str | None = None, figsize=None)

Plot profiles in panels stacked over a shared horizontal axis, one row each.

Parameters

NameTypeDefaultDescription
profilessequence or xarray.DatasetrequiredOne entry per row: a 1-D array, or a list or dict (labels to arrays) of 1-D arrays drawn together in that row; a Dataset gives one row per variable.
sharexboolTrueShare the horizontal axis, labeled on the bottom row only. Default: True.
height_ratiossequence of floatNoneThe relative row heights. Default: equal.
step('pre', 'mid', 'post')"pre"Draw step lines (see plasma_plots.plotting.plot_lineout()). Default: straight lines.
logybool or sequence of boolFalseLogarithmic value axes, for every row or per row. Default: linear.
titlestrNoneA title above the panels. Default: none.
figsize(float, float)NoneThe figure size in inches. Default: from the number of rows.

Returns

PlotResult
The figure, the array of axes (one per row) and the drawn lines.

Raises

ValueError
If there is no profile, or a profile is not one-dimensional.

Examples

>>> plot_stacked([density, {"T_e": Te, "T_i": Ti}, potential])
>>> profiles_ds.plasma.plot.variables(cols=1) # the same for a Dataset

plot_twinfunction#

def plot_twin(left: xr.DataArray, right: xr.DataArray, *, ax=None, step=None, logy=(False, False), colors=('C0', 'C3'), title: str | None = None, xlabel: str | None = None)

Plot two profiles over the same coordinate with a value axis each, left and right.

Parameters

NameTypeDefaultDescription
leftxarray.DataArrayrequiredThe profile on the left axis, one-dimensional.
rightxarray.DataArrayrequiredThe profile on the right axis, one-dimensional; its coordinate may differ in values but should mean the same.
axmatplotlib.axes.AxesNoneThe axes of the left profile. Default: a new figure.
step('pre', 'mid', 'post')"pre"Draw both as step lines (see plasma_plots.plotting.plot_lineout()). Default: straight lines.
logy(bool, bool)(False, False)Logarithmic left and right value axes. Default: both linear.
colors(str, str)('C0', 'C3')The colors of the two profiles, also of their axis labels and ticks. Default: the style’s first color and a contrasting red.
titlestrNoneThe axes title. Default: none.
xlabelstrNoneThe horizontal axis label. Default: the left profile’s coordinate label.

Returns

PlotResult
The figure, the two axes [left, right] and the two lines.

Raises

ValueError
If a profile is not one-dimensional.

Examples

>>> plot_twin(density, temperature)
>>> n.plasma.plot.twin(T, logy=(True, False))

plot_variablesfunction#

def plot_variables(dataset: xr.Dataset, names=None, *, cols: int | None = None, x: str | None = None, y: str | None = None, logy: bool = False, title: str | None = None, **selection)

Plot every variable of a Dataset in a grid of panels, as a profile or a slice each.

After the selection a variable with one dimension left is drawn as a profile, one with two as a slice with a color bar.

Parameters

NameTypeDefaultDescription
datasetxarray.DatasetrequiredThe variables, e.g. the output of a model at one time.
namessequence of strNoneThe variables to plot, in this order. Default: every data variable.
colsintNoneThe number of columns of panels. Default: up to 3.
xstrNoneThe dimension along the horizontal axis. Default: each variable’s first remaining one.
ystrNoneThe dimension along the vertical axis of slices. Default: the second remaining one.
logyboolFalseLogarithmic value axes for the profiles. Default: False.
titlestrNoneA title above the panels. Default: the Dataset’s run attribute, if any.
**selection{}Dimensions to select, for each variable that has them: an integer is a position (t=-1 the last), a float the nearest coordinate value.

Returns

PlotResult
The figure, the array of axes and in data["results"] the result of each panel.

Raises

ValueError
If there is no variable, a name is not a data variable, or a variable has more than two dimensions left after the selection.

Examples

>>> state.plasma.plot.variables(t=-1)
>>> state.plasma.plot.variables(["n", "T", "phi"], cols=1, t=0.5)

prepare_breakdownfunction#

def prepare_breakdown(values, *, dim: str | None = None) -> xr.DataArray

The parts plot_breakdown() draws, as one array over a category dimension.

Parameters

NameTypeDefaultDescription
values(xarray.DataArray, xarray.Dataset or dict)requiredA 1-D array over a category dimension (its coordinate names the parts), a Dataset of scalar variables (one part each, named by its label), or a dict of names to numbers.
dimstrNoneThe category dimension of an array. Default: its only dimension.

Returns

xarray.DataArray
The parts over a part dimension (or the array’s own), with the names as its coordinate; units and label kept.

Raises

ValueError
If an array is not one-dimensional, or a Dataset variable is not a scalar.

prepare_scanfunction#

def prepare_scan(data: xr.DataArray, *, x: str | None = None, error=None, samples: str | None = None) -> xr.Dataset

The values and errors plot_scan() draws.

Parameters

NameTypeDefaultDescription
dataxarray.DataArrayrequiredThe scanned quantity over the parameter x, or over x and samples.
xstrNoneThe scanned parameter. Default: the only dimension other than samples.
errorxarray.DataArray, array_like or (lower, upper) pairNoneThe error of each value: symmetric, or the distances below and above it. Default: the standard deviation over samples, if given, else none.
samplesstrNoneA dimension of repeated runs (seeds, shots) to average over; the values become their mean and the default error their standard deviation. Default: none.

Returns

xarray.Dataset
value, lower and upper (the distances of the error bar below and above the value, NaN without an error) over x.

Raises

ValueError
If more than one dimension remains besides samples, x is not that one, or the errors do not match the values.