# plasma_plots.geometry

*module*

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()`][plasma_plots.geometry.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**

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

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L1-L1)

## plasma_plots.geometry.AXES

*attribute* · *module attribute*

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

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L248-L248)

## plasma_plots.geometry.BC_ROOM

*attribute* · *module attribute*

```python
BC_ROOM = 0.8
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L1157-L1157)

## plasma_plots.geometry.CELL_ROOM

*attribute* · *module attribute*

```python
CELL_ROOM = 1.0
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L1158-L1158)

## plasma_plots.geometry.MIN_VIEW

*attribute* · *module attribute*

```python
MIN_VIEW = 220.0
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L1160-L1160)

## plasma_plots.geometry.ROUND

*attribute* · *module attribute*

```python
ROUND = ('circle', 'sphere')
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L753-L753)

## plasma_plots.geometry.SHAPE_KEYS

*attribute* · *module attribute*

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

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L51-L51)

## plasma_plots.geometry.SIDES

*attribute* · *module attribute*

```python
SIDES = ('min', 'max')
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L910-L910)

## plasma_plots.geometry.dimension_chains

*function*

```python
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**

- `lower` (`sequence of 2 floats`) — The corners of the domain in the plane.
- `upper` (`sequence of 2 floats`) — The corners of the domain in the plane.
- `boxes` (`sequence of (name, (xmin, xmax, ymin, ymax))`) — The extents of the objects in the plane, in the order they are drawn. Parts outside the domain are ignored.
- `style` (`('chain', 'baseline')`) (default: `"chain"`) — Chains of sizes and gaps, or every edge measured from the lower boundary. Default: ``"chain"``.
- `tolerance` (`float`) (default: `None`) — Lengths 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**

```pycon
>>> 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')]]
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L251-L371)

## plasma_plots.geometry.dimension_line

*function*

```python
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**

- `ax` (`matplotlib.axes.Axes`) — The axes to draw into.
- `start` (`(float, float)`) — The measured points, in data coordinates.
- `end` (`(float, float)`) — The measured points, in data coordinates.
- `offset` (`float`) (default: `0.0`) — The 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.
- `label` (`str`) (default: `None`) — The text at the middle of the arrow, e.g. the distance. Default: none.
- `anchors` (`pair of (float, float)`) (default: `None`) — Where the two extension lines start. Default: the measured points (and no extension lines when ``offset`` is 0).
- `label_side` (`(1, -1)`) (default: `1`) — The 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``.
- `color` (`color`) (default: `'k'`) — The color of the arrow, the extension lines and the label. Default: black.
- `linewidth` (`float`) (default: `0.8`) — The width of the arrow line in points; the extension lines are thinner. Default: 0.8.
- `fontsize` (`float or str`) (default: `None`) — The size of the label. Default: Matplotlib's ``font.size``.
- `head_size` (`float`) (default: `7.0`) — The size of the arrow heads in points. Default: 7.
- `overshoot` (`float`) (default: `3.0`) — How far the extension lines reach past the arrow, in points. Default: 3.
- `heads` (`('<->', '->', '<-', '-')`) (default: `"<->"`) — The arrow heads: at both ends, at the end (a radius, from the centre), at the start, or none. Default: ``"<->"``.
- `zorder` (`float`) (default: `5`) — Drawn above the data and the geometry by default. Default: 5.

**Returns**

- (`list`) — The drawn artists: the arrow, the extension lines and the label.

**Examples**

```pycon
>>> 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")
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L386-L535)

## plasma_plots.geometry.draw_geometry

*function*

```python
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**

- `ax` (`matplotlib.axes.Axes`) — The axes to draw into.
- `geometry` (`shape or sequence of shapes`) — Outlines, objects with ``outlines()`` or ``exterior``, shape dicts or patches (see [`plasma_plots.geometry`][plasma_plots.geometry]).
- `color` (`str`) (default: `'0.6'`) — The fill color. Default: a mid grey.
- `edgecolor` (`str`) (default: `None`) — The outline color. Default: ``color`` when filled, else black.
- `fill` (`bool`) (default: `True`) — Fill the shapes; ``False`` draws their outlines only. Default: ``True``.
- `alpha` (`float`) (default: `1.0`) — The opacity. Default: 1.
- `linewidth` (`float`) (default: `0.8`) — The outline width in points. Default: 0.8.
- `scale` (`float`) (default: `1.0`) — Multiply every coordinate, e.g. ``1e3`` for shapes in m over a plot in mm. Default: 1.
- `label` (`str`) (default: `None`) — A legend label, given to the first shape only. Default: none.
- `zorder` (`float`) (default: `3`) — Drawn above the data (a mesh or lines) by default. Default: 3.
- `hatch` (`str`) (default: `None`) — A Matplotlib hatch over the fill, e.g. ``"///"`` for the section faces of a technical drawing; with ``backend="tikz"`` a TikZ pattern. Default: none.
- `hatch_color` (`color`) (default: `'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`][plasma_plots.geometry].

**Examples**

```pycon
>>> 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)
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L131-L241)

## plasma_plots.geometry.plot_domain

*function*

```python
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**

- `domain` (`(simgeometry.SimulationDomain, GeometryCollection, shape, dict or list)`) — 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`) (default: `None`) — The position of the slice through a 3-D domain; exactly one of them.
- `y` (`float`) (default: `None`) — The position of the slice through a 3-D domain; exactly one of them.
- `z` (`float`) (default: `None`) — The position of the slice through a 3-D domain; exactly one of them.
- `views` (`sequence of dict or str`) (default: `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)`) (default: `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)`) (default: `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`) (default: `None`) — The names of the objects to measure; the others are drawn without measurements. Default: all of them.
- `extra_dimensions` (`sequence`) (default: `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')`) (default: `"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`) (default: `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`) (default: `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`) (default: `1.0`) — Multiply every coordinate, e.g. ``1e3`` to draw a domain in metres in mm. Default: 1.
- `unit` (`str`) (default: `None`) — The unit of the plotted coordinates, written after every measurement and in the axis labels. Default: none.
- `fmt` (`str`) (default: `'{:.4g}'`) — The format of the measured values. Default: ``"{:.4g}"``.
- `grid` (`bool`) (default: `False`) — Draw the lines of the domain's grid (a ``SimulationDomain``). Default: ``False``.
- `cells` (`bool`) (default: `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`) (default: `True`) — A legend naming the objects. Default: ``True``.
- `axes` (`bool`) (default: `None`) — Show the axes with their ticks. Default: hidden when measurements are drawn, as in a drawing, shown otherwise.
- `colors` (`dict or sequence`) (default: `None`) — The fill colors, by object name or in their order; the collection's ``styles`` apply first. Default: Matplotlib's color cycle.
- `opacity` (`float`) (default: `0.7`) — The opacity of the fills. Default: 0.7.
- `hatch` (`bool or str`) (default: `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`) (default: `256`) — Samples per axis when tracing the outline of a sliced 3-D object. Default: 256.
- `ax` (`matplotlib.axes.Axes`) (default: `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)`) (default: `None`) — The width of the new figure in inches; a height can only shrink the scale. Default: Matplotlib's.
- `title` (`str`) (default: `None`) — The title of every view. Default: the position of the slice (none for a 2-D domain).
- `backend` (`('matplotlib', 'plotly', 'tikz')`) (default: `"matplotlib"`) — Draw with Matplotlib, as an interactive Plotly figure, or as TikZ/pgfplots code for LaTeX (see [`plasma_plots.tikz_backend`][plasma_plots.tikz_backend]). Default: the one set with [`plasma_plots.set_backend()`][plasma_plots.plotly_backend.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()`][plasma_plots.geometry.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.

> **See Also**
>
> [`dimension_line()`][plasma_plots.geometry.dimension_line] : One measurement between two points of your own.
> [`dimension_chains()`][plasma_plots.geometry.dimension_chains] : The measurements without drawing them.
> [`draw_geometry()`][plasma_plots.geometry.draw_geometry] : The objects over any axes, without measurements.

**Examples**

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

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L1501-L1805)

## plasma_plots.geometry.shapes

*function*

```python
def shapes(geometry) -> list
```

Split a geometry into single shapes.

**Parameters**

- `geometry` (`shape or sequence of shapes`) — Outlines, objects with ``outlines()`` or ``exterior``, shape dicts or patches (see [`plasma_plots.geometry`][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**

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

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/geometry.py#L78-L128)
