# plasma_plots.coils

*module*

Stellarator coilsets and plasma boundaries as Datasets in plasma-plots' conventions.

The `CoilStellaration <https://huggingface.co/datasets/proxima-fusion/coilstellaration>`_
dataset stores a coilset by its unique coils: closed curves given by the Fourier coefficients of
their ``x``, ``y`` and ``z`` coordinates in the layout of DESC's ``FourierXYZCoil``, one current
per coil, the number of field periods and whether the coilset is stellarator symmetric. The plasma
boundaries come from `ConStellaration
<https://huggingface.co/datasets/proxima-fusion/constellaration>`_ as Fourier series of ``R`` and
``Z`` (``SurfaceRZFourier``).

* [`from_coilset()`][plasma_plots.coils.from_coilset] expands a coilset into every coil of the device, the way DESC's
  ``CoilSet`` does, and returns a Dataset over ``coil`` and the curve parameter ``s`` with
  ``X``, ``Y``, ``Z`` coordinates, the ``current`` of each coil, its ``length`` and its
  ``curvature`` along ``s``;
* [`from_boundary()`][plasma_plots.coils.from_boundary] evaluates a boundary into a Dataset over ``(rho, theta, zeta)`` with a
  single ``rho = 1``, in the layout of [`from_desc()`][plasma_plots.desc.from_desc], with the minor radius
  that CoilStellaration normalizes distances and curvatures by;
* [`boundary_from_desc()`][boundary_from_desc] writes a DESC equilibrium's last surface in ConStellaration's
  layout;
* [`plot_boundary_sections()`][plot_boundary_sections] (``plasma.plasma.plot.boundary_sections()``) draws a
  boundary's cross-sections at several toroidal angles over half a field period;
* [`distance_to_surface()`][distance_to_surface] and [`coil_to_coil_distance()`][coil_to_coil_distance] give, at every point of every
  coil, the distance to the plasma and to the nearest other coil: the benchmark's distance
  metrics are their minima;
* [`pyvista_coils()`][plasma_plots.pyvista_plots.pyvista_coils] (``coils.plasma.plot.coils_3d()``) draws
  the coils as tubes around the plasma.

Neither function needs DESC or the ``coilstellaration`` package: plain dicts as stored in the
dataset's ``json`` columns are enough.

**Examples**

```pycon
>>> # a dict from the dataset's coilsets
>>> coils = plasma_plots.from_coilset(coilset)
>>> # ConStellaration's boundary.json
>>> plasma = plasma_plots.from_boundary(boundary)
>>> a = plasma.attrs["minor_radius"]
>>> float(coils.curvature.max()) * a  # normalized_coil_curvatures/max
>>> float(plasma_plots.coils.distance_to_surface(coils, plasma).min()) / a
>>> coils.plasma.plot.coils_3d(color_by="curvature", surface=plasma).show()
```

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

## plasma_plots.coils.COILSET_KEYS

*attribute* · *module attribute*

```python
COILSET_KEYS = ('coil_x_n', 'coil_y_n', 'coil_z_n', 'currents', 'n_field_periods', 'is_stellarator_symmetric')
```

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

## plasma_plots.coils.boundary_from_desc

*function*

```python
def boundary_from_desc(eq, *, max_poloidal_mode=None, max_toroidal_mode=None) -> dict
```

The last flux surface of a DESC equilibrium in ConStellaration's boundary layout.

``R`` and ``Z`` of the surface ``rho = 1``, evaluated on a grid of DESC's angles (its
``zeta`` is the cylindrical angle ``phi``), are transformed into the coefficients of
``cos(m theta - nfp n phi)`` and ``sin(m theta - nfp n phi)``. With enough modes (the default:
DESC's own resolution of the surface) the series reproduces the surface to round-off, so
[`from_boundary()`][plasma_plots.coils.from_boundary] of the result is DESC's surface. Only stellarator-symmetric
equilibria are supported.

**Parameters**

- `eq` (`desc.equilibrium.Equilibrium`) — The equilibrium, e.g. ``desc.examples.get("W7-X")``.
- `max_poloidal_mode` (`int`) (default: `None`) — ``M`` and ``N`` of the series. Default: DESC's ``eq.surface.M`` and ``eq.surface.N``.
- `max_toroidal_mode` (`int`) (default: `None`) — ``M`` and ``N`` of the series. Default: DESC's ``eq.surface.M`` and ``eq.surface.N``.

**Returns**

- (`dict`) — ``r_cos`` and ``z_sin`` (nested lists, ``(M + 1, 2N + 1)``), ``r_sin`` and ``z_cos`` (``None``), ``n_field_periods`` and ``is_stellarator_symmetric``: the layout of ConStellaration's ``boundary.json``.

**Raises**

- `ValueError` — If the equilibrium isn't stellarator symmetric.

**Examples**

```pycon
>>> boundary = boundary_from_desc(desc.examples.get("W7-X"))
>>> from_boundary(boundary).attrs["minor_radius"]  # DESC's "a"
```

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

## plasma_plots.coils.coil_to_coil_distance

*function*

```python
def coil_to_coil_distance(coils: xr.Dataset) -> xr.DataArray
```

The distance from every point of every coil to the nearest point of any other coil.

Coils are sampled at their points, so as for [`distance_to_surface()`][plasma_plots.coils.distance_to_surface] the distance
converges from above as ``n_points`` of [`from_coilset()`][plasma_plots.coils.from_coilset] grows.

**Parameters**

- `coils` (`xarray.Dataset`) — Coils from [`from_coilset()`][plasma_plots.coils.from_coilset], with at least two coils.

**Returns**

- (`xarray.DataArray`) — ``coil_distance`` (m) over ``(coil, s)``; its minimum is the coil–coil distance.

**Raises**

- `ValueError` — If ``coils`` isn't over ``(coil, s)`` or has a single coil.

**Examples**

```pycon
>>> d = coil_to_coil_distance(coils)
>>> # normalized_coil_to_coil_min_distances
>>> float(d.min()) / plasma.attrs["minor_radius"]
```

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

## plasma_plots.coils.distance_to_surface

*function*

```python
def distance_to_surface(coils: xr.Dataset, surface) -> xr.DataArray
```

The distance from every point of every coil to the nearest point of a surface.

The surface is sampled at its grid points, so the distance is an upper bound that converges
as the surface grid is refined: with spacing ``h`` it is within about ``h² / (8 r)`` of the
exact one, ``r`` the distance itself.

**Parameters**

- `coils` (`xarray.Dataset`) — Coils from [`from_coilset()`][plasma_plots.coils.from_coilset].
- `surface` (`xarray.Dataset or xarray.DataArray`) — Anything with ``X``, ``Y``, ``Z`` coordinates: [`from_boundary()`][plasma_plots.coils.from_boundary], or the last surface of [`from_desc()`][plasma_plots.desc.from_desc] (``rho=[1.0]`` over the whole torus).

**Returns**

- (`xarray.DataArray`) — ``plasma_distance`` (m) over ``(coil, s)``; its minimum is the coil–plasma distance.

**Raises**

- `ValueError` — If ``coils`` isn't over ``(coil, s)`` or ``surface`` lacks ``X``, ``Y``, ``Z``.

**Examples**

```pycon
>>> d = distance_to_surface(coils, plasma)
>>> # normalized_coil_to_plasma_min_distances
>>> float(d.min()) / plasma.attrs["minor_radius"]
```

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

## plasma_plots.coils.from_boundary

*function*

```python
def from_boundary(boundary, *, theta=64, zeta=None) -> xr.Dataset
```

A 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()`][plasma_plots.desc.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()`][plasma_plots.pyvista_plots.pyvista_coils] and
[`distance_to_surface()`][plasma_plots.coils.distance_to_surface].

**Parameters**

- `boundary` (`(dict, str or object)`) — ``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`) (default: `64`) — Poloidal angles: an integer as that many points over ``[0, 2π)``, else the values. Default: 64.
- `zeta` (`int or sequence of float`) (default: `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.Dataset`) — ``R`` (m) over ``(rho, theta, zeta)`` with coordinates ``X``, ``Y``, ``Z``, the angles' ``period``, and the attributes ``nfp``, ``major_radius`` (the ``m = n = 0`` coefficient of ``R``, m) and ``minor_radius`` (m): ``sqrt(A / π)`` of the mean area ``A`` of the cross-sections at constant ``phi``, the length CoilStellaration's ``normalized_*`` metrics divide by.

**Raises**

- `TypeError` — If ``boundary`` is none of the accepted kinds.
- `ValueError` — If keys are missing or ``r_cos`` has an even number of toroidal modes.

**Examples**

```pycon
>>> plasma = from_boundary(json.loads(row["boundary.json"]))
>>> plasma.attrs["minor_radius"]
>>> plasma.R.plasma.plot.slices_3d().show()
```

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

## plasma_plots.coils.from_coilset

*function*

```python
def from_coilset(coilset, *, n_points: int = 128) -> xr.Dataset
```

Every 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**

- `coilset` (`(dict, str, object or desc.coils.CoilSet)`) — 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`) (default: `128`) — Points along each coil, equally spaced in ``s`` over ``[0, 2π)``. Default: 128.

**Returns**

- (`xarray.Dataset`) — Over ``coil`` and ``s``: the coordinates ``X``, ``Y``, ``Z`` (m), ``unique_coil`` (the stored coil each one copies), ``mirrored`` and ``field_period``; the variables ``current`` (A, per coil, reversed on the mirrored coils), ``length`` (m, per coil) and ``curvature`` (1/m, along each coil); the attributes ``nfp``, ``stellarator_symmetric`` and ``fourier_order``.

**Raises**

- `TypeError` — If ``coilset`` is none of the accepted kinds.
- `ValueError` — If keys are missing, the coefficient arrays don't match, or ``n_points < 3``.

**Examples**

```pycon
>>> coils = from_coilset(json.loads(row["json"]))
>>> coils.sizes  # 5 unique coils, mirrored, 3 field periods
Frozen({'coil': 30, 's': 128})
>>> coils.curvature.max(dim="s")  # the sharpest bend of each coil
```

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

## plasma_plots.coils.plot_boundary_sections

*function*

```python
def plot_boundary_sections(boundary, *, planes: int | None = 5, theta: int = 128, ax=None, cmap='viridis', title: str | None = None)
```

Draw a plasma boundary's cross-sections in the ``(R, Z)`` plane at several toroidal angles.

The view ConStellaration draws of its boundaries: by default five planes from ``phi = 0`` to
half a field period, ``phi = π / nfp``, which for a stellarator-symmetric surface show every
shape it takes.

**Parameters**

- `boundary` (`(dict, str, object or xarray.Dataset)`) — A boundary as [`from_boundary()`][plasma_plots.coils.from_boundary] takes it (ConStellaration's ``boundary.json``), or a surface Dataset with ``R`` and ``Z`` over ``theta`` and ``zeta`` and a single ``rho``, such as [`from_boundary()`][plasma_plots.coils.from_boundary]'s or the last surface of [`from_desc()`][plasma_plots.desc.from_desc].
- `planes` (`int or None`) (default: `5`) — The number of toroidal angles, evenly from 0 to ``π / nfp``; for a Dataset the nearest of its angles. ``None`` draws every angle of a Dataset. Default: 5.
- `theta` (`int`) (default: `128`) — Poloidal points per cross-section of a boundary (not of a Dataset). Default: 128.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes to draw into. Default: a new figure.
- `cmap` (`str or matplotlib colormap`) (default: `'viridis'`) — The colors of the planes, from the first to the last. Default: ``"viridis"``.
- `title` (`str`) (default: `None`) — The axes title. Default: none.

**Returns**

- (`PlotResult`) — The figure, the axes, one closed line per plane, and in ``data["surface"]`` the surface at the drawn angles.

**Raises**

- `ValueError` — If ``planes`` is below 1, or the Dataset lacks ``R``, ``Z`` or the ``theta`` and
``zeta`` dimensions.

**Examples**

```pycon
>>> plot_boundary_sections(json.loads(row["boundary.json"]))
>>> plasma_plots.from_boundary(boundary).plasma.plot.boundary_sections(
...     planes=3
... )
```

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