Skip to content
Projects

plasma_plots.geometry

Electrodes, walls, apertures and other shapes drawn over a plot: plasma_plots.geometry.

[draw_geometry()][draw_geometry] fills or outlines shapes in an existing axes. The slice plots take the same shapes as an overlay, overlays={"geometry": shapes}, so a potential is drawn with the electrodes on top in one call.

A shape is any of these:

  • a closed outline: an array of shape (2, N) or (N, 2), or an (x, y) pair of arrays;
  • an object with an outlines() method returning such outlines (e.g. beamtracer’s electrode geometries) or with an exterior (a shapely polygon);
  • {"rectangle": (x0, y0, width, height)}, {"circle": (x, y, radius)} or {"polygon": outline}, optionally with "color", "fill" and "label" keys of its own;
  • a matplotlib.patches.Patch, added as it is;
  • a matplotlib.path.Path of several loops, e.g. a section with holes (clockwise loops), filled by the non-zero rule.

Several shapes are given as a list of these.

plot_domain() draws a simulation domain of simgeometry <https://github.com/max-models/simgeometry>_ (a SimulationDomain, a GeometryCollection, or named shapes) as a technical drawing: a slice through it (z=0.0 for a 3-D domain) with every object filled and named, the domain’s boundary, optionally its grid, and the measurements drawn as dimension lines with arrows, found from the geometry itself: the extent of the domain, and along each axis a chain of the objects’ sizes and the gaps between them and to the boundary. With backend="tikz" the drawing is TikZ code for a paper. It also takes the shapes above, without simgeometry. [dimension_line()][dimension_line] draws one such measurement anywhere, and [dimension_chains()][dimension_chains] computes them without drawing.

Examples

>>> phi.plasma.plot.slice(
... x="x", y="y", overlays={"geometry": electrodes.outlines()}
... )
>>> fig, ax = plt.subplots()
>>> draw_geometry(
... ax, [{"rectangle": (0.0, 0.4, 1.0, 0.1)}, {"circle": (0.5, 0.0, 0.05)}]
... )
>>> plot_domain(domain, z=0.0, scale=1e3, unit="mm", backend="tikz").save(
... "domain.tikz"
... )

Attributes

NameDescription
AXESNo description.
BC_ROOMNo description.
CELL_ROOMNo description.
MIN_VIEWNo description.
ROUNDNo description.
SHAPE_KEYSNo description.
SIDESNo description.

Functions

NameDescription
dimension_chainsThe measurements of a domain and the boxes in it, as chains along each axis.
dimension_lineDraw one measurement: a double-headed arrow between two points with its label.
draw_geometryDraw shapes such as electrodes, walls or apertures into an axes.
plot_domainDraw a simulation domain with its objects and their measurements, as a technical drawing.
shapesSplit a geometry into single shapes.

AXESattributemodule attribute#

AXES = ('x', 'y', 'z')

BC_ROOMattributemodule attribute#

BC_ROOM = 0.8

CELL_ROOMattributemodule attribute#

CELL_ROOM = 1.0

MIN_VIEWattributemodule attribute#

MIN_VIEW = 220.0

ROUNDattributemodule attribute#

ROUND = ('circle', 'sphere')

SHAPE_KEYSattributemodule attribute#

SHAPE_KEYS = ('rectangle', 'circle', 'polygon')

SIDESattributemodule attribute#

SIDES = ('min', 'max')

dimension_chainsfunction#

def dimension_chains(lower, upper, boxes, *, style: str = 'chain', tolerance=None) -> dict

The measurements of a domain and the boxes in it, as chains along each axis.

With style="chain", along each axis the boxes are packed into rows: boxes whose intervals do not overlap share a row (a greedy packing in order of their start), so a row reads as a chain from the domain’s lower boundary to its upper one, alternating the gaps and the boxes’ sizes. A row that spans the whole axis in one piece (a box as wide as the domain) is left out, and so are gaps of zero length (a box touching the boundary or another box).

With style="baseline", every edge of a box is measured from the domain’s lower boundary, one row per edge, the nearest edge first: each row is a gap from the boundary to the edge, followed by a point marking the box the edge belongs to.

A box of zero width along an axis (e.g. (x, x, y, y) for the centre of a circle) is a point there: it splits the gaps of its row and appears as a segment (c, c, name), which has no length to draw.

Parameters

NameTypeDefaultDescription
lowersequence of 2 floatsrequiredThe corners of the domain in the plane.
uppersequence of 2 floatsrequiredThe corners of the domain in the plane.
boxessequence of (name, (xmin, xmax, ymin, ymax))requiredThe extents of the objects in the plane, in the order they are drawn. Parts outside the domain are ignored.
style('chain', 'baseline')"chain"Chains of sizes and gaps, or every edge measured from the lower boundary. Default: "chain".
tolerancefloatNoneLengths below it count as zero. Default: a billionth of the larger extent.

Returns

dict
For each axis ("x" and "y"), {"total": (lower, upper), "rows": rows} where rows is a list of chains, each a list of segments (start, end, name) in which name is the box’s name, or None for a gap.

Raises

ValueError
If style is neither "chain" nor "baseline".

Examples

>>> chains = dimension_chains(
... (0, 0), (10, 4), [("a", (2, 3, 1, 3)), ("b", (6, 8, 0, 4))]
... )
>>> chains["x"]["rows"]
[[(0.0, 2.0, None), (2.0, 3.0, 'a'), (3.0, 6.0, None), (6.0, 8.0, 'b'), (8.0, 10.0, None)]]
>>> chains["y"]["rows"] # b spans the whole height: no row of its own
[[(0.0, 1.0, None), (1.0, 3.0, 'a'), (3.0, 4.0, None)]]
>>> baseline = dimension_chains(
... (0, 0), (10, 4), [("a", (2, 3, 1, 3))], style="baseline"
... )
>>> baseline["x"]["rows"]
[[(0.0, 2.0, None), (2.0, 2.0, 'a')], [(0.0, 3.0, None), (3.0, 3.0, 'a')]]

dimension_linefunction#

def dimension_line(ax, start, end, *, offset: float = 0.0, label: str | None = None, anchors=None, label_side: int | None = None, color='k', linewidth: float = 0.8, fontsize=None, head_size: float = 7.0, overshoot: float = 3.0, heads: str = '<->', zorder: float = 5) -> list

Draw one measurement: a double-headed arrow between two points with its label.

The arrow is drawn parallel to the line from start to end, displaced by offset to its left (for a measurement from left to right, a negative offset puts the arrow below; from bottom to top, a positive offset puts it on the left). Thin extension lines connect the measured points (or anchors) to the arrow, as in a technical drawing, and the label sits at its middle, reading from left to right or from bottom to top.

Parameters

NameTypeDefaultDescription
axmatplotlib.axes.AxesrequiredThe axes to draw into.
start(float, float)requiredThe measured points, in data coordinates.
end(float, float)requiredThe measured points, in data coordinates.
offsetfloat0.0The displacement of the arrow from the measured points, in data units, to the left of the direction from start to end. Default: 0, the arrow between the points.
labelstrNoneThe text at the middle of the arrow, e.g. the distance. Default: none.
anchorspair of (float, float)NoneWhere the two extension lines start. Default: the measured points (and no extension lines when offset is 0).
label_side(1, -1)1The side of the arrow the label is on: 1 the left of the direction from start to end, -1 the right. Default: the side the arrow was displaced to (away from the measured points), the left for offset=0.
colorcolor'k'The color of the arrow, the extension lines and the label. Default: black.
linewidthfloat0.8The width of the arrow line in points; the extension lines are thinner. Default: 0.8.
fontsizefloat or strNoneThe size of the label. Default: Matplotlib’s font.size.
head_sizefloat7.0The size of the arrow heads in points. Default: 7.
overshootfloat3.0How far the extension lines reach past the arrow, in points. Default: 3.
heads('<->', '->', '<-', '-')"<->"The arrow heads: at both ends, at the end (a radius, from the centre), at the start, or none. Default: "<->".
zorderfloat5Drawn above the data and the geometry by default. Default: 5.

Returns

list
The drawn artists: the arrow, the extension lines and the label.

Examples

>>> fig, ax = plt.subplots()
>>> # below
>>> dimension_line(ax, (0.0, 0.0), (2.0, 0.0), offset=-0.3, label="2 mm")
>>> # on the right
>>> dimension_line(ax, (2.0, 0.0), (2.0, 1.0), offset=-0.3, label="1 mm")

draw_geometryfunction#

def draw_geometry(ax, geometry, *, color='0.6', edgecolor=None, fill: bool = True, alpha: float = 1.0, linewidth: float = 0.8, scale: float = 1.0, label: str | None = None, zorder: float = 3, hatch: str | None = None, hatch_color='0.15') -> list

Draw shapes such as electrodes, walls or apertures into an axes.

Parameters

NameTypeDefaultDescription
axmatplotlib.axes.AxesrequiredThe axes to draw into.
geometryshape or sequence of shapesrequiredOutlines, objects with outlines() or exterior, shape dicts or patches (see plasma_plots.geometry).
colorstr'0.6'The fill color. Default: a mid grey.
edgecolorstrNoneThe outline color. Default: color when filled, else black.
fillboolTrueFill the shapes; False draws their outlines only. Default: True.
alphafloat1.0The opacity. Default: 1.
linewidthfloat0.8The outline width in points. Default: 0.8.
scalefloat1.0Multiply every coordinate, e.g. 1e3 for shapes in m over a plot in mm. Default: 1.
labelstrNoneA legend label, given to the first shape only. Default: none.
zorderfloat3Drawn above the data (a mesh or lines) by default. Default: 3.
hatchstrNoneA Matplotlib hatch over the fill, e.g. "///" for the section faces of a technical drawing; with backend="tikz" a TikZ pattern. Default: none.
hatch_colorcolor'0.15'The color of the hatch lines (Matplotlib 3.10 or newer; older versions use the outline color). Default: a dark grey.

Returns

list of matplotlib.patches.Patch
The drawn patches.

Raises

ValueError
If a shape is none of the kinds in plasma_plots.geometry.

Examples

>>> fig, ax = plt.subplots()
>>> draw_geometry(ax, beamtracer_geometry, scale=1e3) # m to mm
>>> draw_geometry(ax, {"rectangle": (0.0, 0.4, 1.0, 0.1)}, fill=False)

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"
... )

shapesfunction#

def shapes(geometry) -> list

Split a geometry into single shapes.

Parameters

NameTypeDescription
geometryshape or sequence of shapesOutlines, objects with outlines() or exterior, shape dicts or patches (see plasma_plots.geometry).

Returns

list
The shapes: (2, N) arrays, shape dicts and patches.

Raises

ValueError
If a shape is none of the kinds above.

Examples

>>> len(shapes([np.zeros((2, 4)), {"circle": (0.0, 0.0, 1.0)}]))
2