# carafe.mhd

*module*

MHD in two dimensions on a patchwork hierarchy.

`MHD2D` solves the equations of ideal magnetohydrodynamics in a plane ``(x, y)``
with all three components of the velocity and the magnetic field (2.5D), in
Heaviside–Lorentz units with :math:`\mu_0 = 1` (the field in units of
:math:`\sqrt{\mu_0}`):

.. math::

    \partial_t\rho + \nabla\cdot(\rho\mathbf u) = 0, \qquad
    \partial_t(\rho\mathbf u) + \nabla\cdot\big(\rho\mathbf u\mathbf u
        + p_T - \mathbf B\mathbf B\big) = 0,

    \partial_t E + \nabla\cdot\big((E + p_T)\mathbf u
        - (\mathbf u\cdot\mathbf B)\mathbf B\big) = 0, \qquad
    \partial_t\mathbf B = \nabla\times(\mathbf u\times\mathbf B),

with :math:`p_T = p + |\mathbf B|^2/2` and
:math:`E = p/(\gamma - 1) + \rho|\mathbf u|^2/2 + |\mathbf B|^2/2`. With a uniform
resistivity :math:`\eta` (a magnetic diffusivity in these units) the electric field
gains :math:`\eta\mathbf J`, :math:`\mathbf J = \nabla\times\mathbf B`, and the energy flux
:math:`\eta\,\mathbf J\times\mathbf B` (the Ohmic heating stays in the energy); the
Lundquist number of a layer of length :math:`L` is :math:`S = L v_A/\eta`.

Two further optional terms:

- *Braginskii (anisotropic) heat conduction*: the energy flux gains :math:`\mathbf q =
  -\kappa_\parallel\,\mathbf b(\mathbf b\cdot\nabla T) - \kappa_\perp\nabla T` with
  :math:`\mathbf b = \mathbf B/|\mathbf B|` and :math:`T = p/\rho`, uniform
  conductivities; the gradient across a face in the parallel term is the
  monotonized-central average of its four neighbours (Sharma and Hammett 2007),
  which keeps the temperature from overshooting where the field is oblique to the
  grid;
- *gravity*: a uniform acceleration :math:`\mathbf g`, with the sources
  :math:`\rho\mathbf g` of the momentum and :math:`\rho\mathbf u\cdot\mathbf g` of the
  energy. They are not well balanced: a hydrostatic atmosphere keeps spurious
  velocities that fall at first order with the cell size (about 6e-4 at a density
  jump of two, 32 cells across the Rayleigh–Taylor box, `MHD2D.rayleigh_taylor`).

**The mesh is patchwork's.** The model owns no grid: it allocates its fields on
an `patchwork.AMRHierarchy` and uses the hierarchy's halo exchange, flux register
and restriction. A uniform grid is a hierarchy of one level; refined patches
are patches of finer levels, fixed or regridded on the current density
(`MHD2D.current_tags`, `MHD2D.regrid`); all levels take the same time step.

**The magnetic field.** The density, the momentum, the energy and :math:`B_z`
are cell-centered conserved fields. The in-plane field is the curl of a vector
potential :math:`A_z` on the nodes, plus a uniform mean field
:math:`\mathbf B_0`:

.. math::

    B_x = B_{0x} + \partial_y A_z, \qquad B_y = B_{0y} - \partial_x A_z,

taken as the flux through every cell face (the difference of :math:`A_z` at the
face's two nodes). This is the face (Raviart–Thomas) value of the field as the
rotated gradient of a nodal (Q1) potential, the 2D form of constrained transport:
the discrete divergence of every cell is zero to round-off whatever :math:`A_z`
is, and :math:`A_z` advances with the electric field at the nodes,
:math:`\partial_t A_z = -E_z`. On a refined hierarchy the nodes a coarse and a fine
patch share carry the fine value (`patchwork.AMRHierarchy.restrict`), so the flux
through a coarse face equals the sum of the fine fluxes through it, and the
divergence of the composite mesh is zero to round-off as well. :math:`\mathbf B_0`
lets a periodic domain carry a net flux, which a periodic :math:`A_z` cannot.

**Numerics.** MUSCL reconstruction of the primitive variables (the slope limiters
of `carafe.limiters`), the HLLD Riemann solver (Miyoshi and Kusano 2005) with the
face-normal field taken from :math:`A_z`, the electric field at the nodes by the
upwind "CT-contact" average of the face fluxes (Gardiner and Stone 2005), Heun's
method (SSP-RK2), and refluxing (`patchwork.FluxRegister`) at coarse–fine faces.
Where a reconstructed density or pressure is not positive the face falls back to
first order. The resistive and conductive terms are explicit (``J_z`` at the nodes from
the face fields, ``J_x``, ``J_y`` at the faces from ``B_z``), and the step keeps within
the diffusion limit of the finest cells.

**Boundaries.** Periodic axes are those the hierarchy declares periodic. The faces
of each other axis are outflow (zero-gradient) boundaries or perfectly conducting,
reflecting walls (``boundaries={"y": "wall"}``): the halo mirrors the cells with the
normal velocity reversed, :math:`A_z` is odd about its wall value so the normal field
stays zero, the electric field along the wall is zero, and nothing but the pressure
crosses it.

patchwork is an optional dependency of carafe (the ``spatial`` extra): install it to
use this module.

**Regridding.** `MHD2D.regrid` moves the conserved fields (their integrals kept) and
interpolates :math:`A_z` bilinearly onto new patches, so the field stays
divergence-free; a state can be set again on the new patches (`set_state`), e.g. to
resolve an initial current sheet the base level cannot.

**Not yet.** Viscosity, the r–z metric and graded axes (slab and cylinder geometry only
in the sense of a Cartesian plane; no toroidal geometry); MPI is parallel over patches (the fields of a patch are not split between
ranks): place the patches with ``placement="morton"`` or ``"balanced"``.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1-L1)

## carafe.mhd.CONSERVED

*attribute* · *module attribute*

```python
CONSERVED = ('density', 'momentum_x', 'momentum_y', 'momentum_z', 'energy', 'bz')
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L118-L118)

## carafe.mhd.MHD2D

*class*

```python
class MHD2D
```

MHD (2.5D) on the patches of a patchwork hierarchy; see the module docstring.

**Parameters**

- `hierarchy` (`AMRHierarchy`) — The 2D Cartesian hierarchy the fields live on. Its periodic axes are periodic; the faces of the others follow ``boundaries``.
- `gamma` (`float`) (default: `5.0 / 3.0`) — The adiabatic index.
- `mean_field` (`tuple[float, float]`) (default: `(0.0, 0.0)`) — The uniform in-plane field ``(B0x, B0y)`` added to the curl of ``A_z``.
- `resistivity` (`float`) (default: `0.0`) — The uniform resistivity ``eta`` (a magnetic diffusivity); 0 for ideal MHD.
- `limiter` (`str`) (default: `'vanleer'`) — The slope limiter of the reconstruction (`carafe.limiters`): ``"minmod"``, ``"vanleer"`` (default), ``"mc"`` or ``"none"``.
- `cfl` (`float`) (default: `0.4`) — The Courant number.
- `conduction` (`tuple[float, float]`) (default: `(0.0, 0.0)`) — The heat conductivities ``(kappa_parallel, kappa_perp)`` along and across the field, in units of energy flux per gradient of ``T = p / rho``.
- `gravity` (`tuple[float, float]`) (default: `(0.0, 0.0)`) — The uniform acceleration ``(g_x, g_y)``.
- `boundaries` (`dict[str, str] | None`) (default: `None`) — The kind of the faces of each non-periodic axis, ``{"x": ..., "y": ...}``: ``"outflow"`` (the default) or ``"wall"``.
- `prefix` (`str`) (default: `'mhd_'`) — The prefix of the names of the fields the model allocates on the hierarchy (``prefix + "density"``, ..., ``prefix + "az"``).

**Numerics**

*mass*

$$
\partial_t\rho + \nabla\cdot(\rho\mathbf u) = 0
$$

*momentum*

$$
\partial_t(\rho\mathbf u) + \nabla\cdot\big(\rho\mathbf u\mathbf u + p_T\mathbf I - \mathbf B\mathbf B\big) = 0, \qquad p_T = p + \tfrac12|\mathbf B|^2
$$

*energy*

$$
\partial_t E + \nabla\cdot\big((E + p_T)\mathbf u - (\mathbf u\cdot\mathbf B)\mathbf B\big) = 0, \qquad E = \frac{p}{\gamma - 1} + \tfrac12\rho|\mathbf u|^2 + \tfrac12|\mathbf B|^2
$$

*field*

$$
B_x = B_{0x} + \partial_y A_z, \quad B_y = B_{0y} - \partial_x A_z, \quad \partial_t A_z = -E_z = u_x B_y - u_y B_x - \eta J_z, \quad \partial_t B_z + \nabla\cdot(B_z\mathbf u - u_z\mathbf B) = \eta\nabla^2 B_z
$$

*resistive*

$$
\mathbf E \mathrel{+}= \eta\mathbf J, \quad \mathbf J = \nabla\times\mathbf B, \quad \text{energy flux} \mathrel{+}= \eta\,\mathbf J\times\mathbf B
$$

*conduction*

$$
\mathbf q = -\kappa_\parallel\mathbf b(\mathbf b\cdot\nabla T) - \kappa_\perp\nabla T, \quad T = p/\rho, \quad \partial_y T|_{x\text{-face}} = \mathrm{MC}\big(\mathrm{MC}(\delta^+_{i-1}, \delta^-_{i-1}), \mathrm{MC}(\delta^+_i, \delta^-_i)\big)
$$

*gravity*

$$
\partial_t(\rho\mathbf u) \mathrel{+}= \rho\mathbf g, \qquad \partial_t E \mathrel{+}= \rho\mathbf u\cdot\mathbf g
$$

*walls*

$$
\text{mirrored halo}, \ u_n \to -u_n, \quad A_z(w - k) = 2A_z(w) - A_z(w + k), \quad E_z|_w = 0
$$

*ct contact*

$$
E_z = \tfrac14\big(\textstyle\sum_\text{faces} E_z^f\big) + \tfrac14\big(\textstyle\sum_\text{4 half-faces} (E_z^f - E_z^c)_\text{upwind}\big)
$$

Order of accuracy: 2.

Assumptions:

- MHD in the plane with three velocity and field components; Heaviside–Lorentz units ($\mu_0 = 1$); uniform resistivity $\eta$, explicit
- in-plane field from a nodal $A_z$: zero discrete divergence per cell and on the composite mesh, to round-off
- MUSCL on the primitives, HLLD, CT-contact electric field, Heun (SSP-RK2) at CFL 0.4; refluxing at coarse–fine faces
- Cartesian, uniform levels, one time step for all levels; periodic, outflow or conducting-wall faces; regridding interpolates $A_z$ bilinearly
- uniform $\kappa_\parallel$, $\kappa_\perp$ and $\mathbf g$; Sharma–Hammett limited transverse gradients; gravity not well balanced
- the order is that of a smooth Alfvén wave with the unlimited reconstruction

References:

- [Gardiner and Stone, J. Comput. Phys. 205, 509 (2005)](https://doi.org/10.1016/j.jcp.2004.11.016)
- [Tóth, J. Comput. Phys. 161, 605 (2000)](https://doi.org/10.1006/jcph.2000.6519)
- [Sharma and Hammett, J. Comput. Phys. 227, 123 (2007)](https://doi.org/10.1016/j.jcp.2007.07.026)

Built from:

- `carafe.mhd.hlld_flux`

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L412-L1382)

### carafe.mhd.MHD2D.cfl

*attribute* · *instance attribute*

```python
cfl = float(cfl)
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L516-L516)

### carafe.mhd.MHD2D.conduction

*attribute* · *instance attribute*

```python
conduction = (float(conduction[0]), float(conduction[1]))
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L517-L517)

### carafe.mhd.MHD2D.gamma

*attribute* · *instance attribute*

```python
gamma = float(gamma)
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L512-L512)

### carafe.mhd.MHD2D.gravity

*attribute* · *instance attribute*

```python
gravity = (float(gravity[0]), float(gravity[1]))
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L518-L518)

### carafe.mhd.MHD2D.hierarchy

*attribute* · *instance attribute*

```python
hierarchy = hierarchy
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L511-L511)

### carafe.mhd.MHD2D.limiter

*attribute* · *instance attribute*

```python
limiter = limiter
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L515-L515)

### carafe.mhd.MHD2D.mean_field

*attribute* · *instance attribute*

```python
mean_field = (float(mean_field[0]), float(mean_field[1]))
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L513-L513)

### carafe.mhd.MHD2D.names

*attribute* · *instance attribute*

```python
names = {name: prefix + name for name in CONSERVED}
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L520-L520)

### carafe.mhd.MHD2D.period

*attribute* · *instance attribute*

```python
period = float('nan')
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L536-L536)

### carafe.mhd.MHD2D.periodic

*attribute* · *instance attribute*

```python
periodic = tuple(hierarchy.periodic)
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L531-L531)

### carafe.mhd.MHD2D.potential

*attribute* · *instance attribute*

```python
potential = prefix + 'az'
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L521-L521)

### carafe.mhd.MHD2D.register

*attribute* · *instance attribute*

```python
register = FluxRegister(hierarchy)
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L532-L532)

### carafe.mhd.MHD2D.resistivity

*attribute* · *instance attribute*

```python
resistivity = float(resistivity)
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L514-L514)

### carafe.mhd.MHD2D.steps

*attribute* · *instance attribute*

```python
steps = 0
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L534-L534)

### carafe.mhd.MHD2D.time

*attribute* · *instance attribute*

```python
time = 0.0
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L533-L533)

### carafe.mhd.MHD2D.walls

*attribute* · *instance attribute*

```python
walls = tuple((kinds[name] == 'wall' for name in 'xy'))
```

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L519-L519)

### carafe.mhd.MHD2D.alfven_wave

*method* · *classmethod*

```python
def alfven_wave(cells: int, *, amplitude: float = 0.1, **options: Any) -> tuple[MHD2D, xr.Dataset]
```

The oblique circularly polarized Alfvén wave (Tóth 2000), and its exact state.

A periodic box of ``2 cells x cells`` cells over ``[0, 2] x [0, 1]``; the
wave travels at the angle ``atan(2)`` to ``x`` with wavelength ``2 /
sqrt(5)``, density 1, pressure 0.1 and a parallel field of 1, so the
Alfvén speed is 1. The exact solution after a whole number of periods
(`period`) is the initial state, which the second item returns.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L540-L584)

### carafe.mhd.MHD2D.blast_wave

*method* · *classmethod*

```python
def blast_wave(cells: int, **options: Any) -> MHD2D
```

The magnetized blast wave, ``cells x 1.5 cells`` cells (Gardiner and Stone 2005).

Pressure 10 inside radius 0.1 and 0.1 outside, density 1, in a periodic box
``[-0.5, 0.5] x [-0.75, 0.75]`` with a uniform field of 1 at 45 degrees;
``gamma = 5/3``. The low plasma beta outside (0.2) makes the blast expand
along the field; the reference time is 0.2. The limiter is ``"minmod"`` by
default: with van Leer slopes at CFL 0.4 the pressure, the small difference of
the total energy and the magnetic energy there, turns negative early on.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L648-L674)

### carafe.mhd.MHD2D.composite_divergence

*method*

```python
def composite_divergence() -> float
```

The largest net magnetic flux out of a coarse leaf cell next to a finer patch.

The flux through a coarse face is the difference of ``A_z`` at its two
nodes; the fine faces over it add up to the difference at the same
nodes, which the fine patch shares (restricted). Returned relative to
the largest face flux: zero to round-off.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1289-L1326)

### carafe.mhd.MHD2D.current_tags

*method*

```python
def current_tags(threshold: float, levels: int) -> dict[int, np.ndarray]
```

Tag the cells where ``|J_z|`` times the cell size exceeds ``threshold``.

That is the change of the in-plane field across a cell. Levels ``0 .. levels -
1`` that exist are tagged (so at most ``levels`` refined levels, one more per
regrid), from the patches this rank holds; the result is for `regrid`.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1168-L1198)

### carafe.mhd.MHD2D.dataset

*method*

```python
def dataset(level: int = 0) -> xr.Dataset
```

The primitive variables of ``level`` as a dataset over its cell centres.

The patches of the level are gathered into one array of the level's
shape, NaN where the level has no patch. Collective.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1333-L1382)

### carafe.mhd.MHD2D.divergence

*method*

```python
def divergence() -> float
```

The largest ``|div B|`` times the cell size over the leaf cells of all patches.

The net flux out of each cell over its perimeter: zero to round-off by
construction, on each patch and (`composite_divergence`) across patches.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1270-L1287)

### carafe.mhd.MHD2D.leaf_values

*method*

```python
def leaf_values() -> dict[str, np.ndarray]
```

The primitive variables on the leaf cells of the hierarchy (collective).

One value per leaf cell, in the order of `patchwork.CompositeCells`: ``x``,
``y`` (the centres), ``level``, the variables of `dataset` and ``current_z``
(the mean of the corners).

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1215-L1267)

### carafe.mhd.MHD2D.orszag_tang

*method* · *classmethod*

```python
def orszag_tang(cells: int, **options: Any) -> MHD2D
```

The Orszag–Tang vortex on the periodic unit square, ``cells`` per side.

Density ``25 / (36 pi)``, pressure ``5 / (12 pi)``, velocity
``(-sin 2 pi y, sin 2 pi x)``, field ``(-sin 2 pi y, sin 4 pi x) / sqrt(4 pi)``
(Gardiner and Stone 2005), ``gamma = 5/3``.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L586-L613)

### carafe.mhd.MHD2D.rayleigh_taylor

*method* · *classmethod*

```python
def rayleigh_taylor(cells: int, *, field: float = 0.0, amplitude: float = 0.01, **options: Any) -> MHD2D
```

The single-mode Rayleigh–Taylor instability, ``cells x 3 cells`` cells.

Heavy gas (density 2) on light (density 1) over ``[-0.25, 0.25] x [-0.75,
0.75]``, periodic in ``x``, walls in ``y``, gravity ``-0.1`` along ``y``,
hydrostatic pressure ``2.5 - 0.1 rho y``, ``gamma = 1.4``, a velocity
perturbation ``v_y = amplitude (1 + cos 4 pi x)(1 + cos 3 pi y) / 4`` and a
uniform field ``field`` along ``x`` (the setup of Stone and Gardiner, *ApJS*
178, 137, 2008). A field along the interface stabilises the modes with
``k B^2 > (rho_h - rho_l) g`` roughly.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L676-L719)

### carafe.mhd.MHD2D.regrid

*method*

```python
def regrid(tags: dict[int, Any], **options: Any) -> None
```

Regrid on ``tags`` (`patchwork.AMRHierarchy.regrid`, which takes ``options``).

The conserved fields keep their integrals, ``A_z`` is interpolated (the field
stays divergence-free); the flux register is rebuilt for the new hierarchy.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1200-L1212)

### carafe.mhd.MHD2D.rotor

*method* · *classmethod*

```python
def rotor(cells: int, **options: Any) -> MHD2D
```

The MHD rotor (Balsara and Spicer 1999) on the unit square, ``cells`` per side.

A dense disc (density 10, radius 0.1, tapered to 1 at radius 0.115) spins at
speed 2 at its edge in gas of density 1, pressure 1, in a uniform field
``5 / sqrt(4 pi)`` along ``x``; ``gamma = 1.4``, outflow faces. Torsional
Alfvén waves carry its angular momentum away and squeeze it into an oval;
the reference time is 0.15.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L615-L646)

### carafe.mhd.MHD2D.run

*method*

```python
def run(duration: float, *, max_steps: int = 1000000) -> int
```

Advance by ``duration`` (the last step shortened to land on it); return the steps.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1153-L1165)

### carafe.mhd.MHD2D.set_state

*method*

```python
def set_state(density: Value, velocity: Value | tuple[Value, Value, Value], pressure: Value, *, vector_potential: Value = 0.0, bz: Value = 0.0) -> None
```

Set the state on every patch.

Each argument is a number, an array of the patch's shape (only for a
hierarchy of one patch) or a function of the cell-centre coordinates
``(x, y)`` (of the node coordinates for ``vector_potential``).
``velocity`` is a function returning the three components, or a tuple of
three values. The in-plane field is ``mean_field`` plus the curl of
``vector_potential``; ``bz`` is the out-of-plane field.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L737-L791)

### carafe.mhd.MHD2D.stable_step

*method*

```python
def stable_step() -> float
```

The largest stable step: ``cfl`` times the fast-wave crossing time of a cell.

With resistivity or conduction, also ``cfl`` times the explicit diffusion
limit ``1 / (2 D (dx^-2 + dy^-2))`` of the finest cells, ``D`` the largest of
``eta`` and ``(gamma - 1) kappa / rho``.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1089-L1124)

### carafe.mhd.MHD2D.step

*method*

```python
def step(dt: float | None = None) -> float
```

Advance by one step of Heun's method (SSP-RK2); return the step taken.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1126-L1151)

### carafe.mhd.MHD2D.totals

*method*

```python
def totals() -> dict[str, float]
```

Integrals of the conserved fields over the domain, from the finest cells.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1328-L1331)

## carafe.mhd.harris_sheets

*function*

```python
def harris_sheets(hierarchy: AMRHierarchy, *, width: float, beta: float = 0.2, perturbation: float = 0.001, noise: float = 0.0, seed: int = 0) -> dict[str, Any]
```

Two Harris current sheets at ``y = Ly / 4`` and ``3 Ly / 4`` of a periodic box.

Returns the arguments of `MHD2D.set_state` (functions of ``x, y``; pass them as
``model.set_state(**state)``), so a model can
take them again on a regridded hierarchy, whose patches then resolve the sheets
instead of interpolating them from the base level.

``B_x = tanh((y - y1) / w) - tanh((y - y2) / w) - 1`` (unit field, ``|B_x| = 1`` far
from the sheets, the sheets of opposite current), uniform density 1 and the pressure
of the balance ``p + B_x^2 / 2 = (1 + beta) / 2``, so the Alfvén speed is 1 and the
Lundquist number of a sheet of the box's length is ``S = Lx / eta``. The sheets are
perturbed by ``perturbation`` times the box's longest mode in the potential (one
X-point per sheet) and, with ``noise``, by random modes up to a tenth of the length
(a seed for plasmoids).

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1388-L1444)

## carafe.mhd.hlld_flux

*function*

```python
def hlld_flux(left: np.ndarray, right: np.ndarray, bn: np.ndarray, gamma: float) -> np.ndarray
```

The HLLD flux through faces between two states.

**Parameters**

- `left` (`np.ndarray`) — The state left of each face, ``(7, ...)``: density, normal velocity, the two tangential velocities, pressure and the two tangential field components.
- `right` (`np.ndarray`) — The state right of each face, the same way.
- `bn` (`np.ndarray`) — The normal field at each face, ``(...)``.
- `gamma` (`float`) — The adiabatic index.

**Returns**

- (`np.ndarray`) — The flux of (density, normal momentum, the two tangential momenta, energy,
- (`np.ndarray`) — the two tangential field components), ``(7, ...)``.

**Numerics**

*speeds*

$$
S_L = \min(u_L, u_R) - \max(c_{fL}, c_{fR}), \quad S_R = \max(u_L, u_R) + \max(c_{fL}, c_{fR}), \quad S_L^* = S_M - \frac{|B_n|}{\sqrt{\rho_L^*}}, \quad S_R^* = S_M + \frac{|B_n|}{\sqrt{\rho_R^*}}
$$

*contact*

$$
S_M = \frac{(S_R - u_R)\rho_R u_R - (S_L - u_L)\rho_L u_L - p_{TR} + p_{TL}}{(S_R - u_R)\rho_R - (S_L - u_L)\rho_L}
$$

*star*

$$
\rho^*_K = \rho_K\frac{S_K - u_K}{S_K - S_M}, \quad \mathbf v^*_{tK} = \mathbf v_{tK} - B_n\mathbf B_{tK}\frac{S_M - u_K}{\rho_K(S_K - u_K)(S_K - S_M) - B_n^2}, \quad \mathbf B^*_{tK} = \mathbf B_{tK}\frac{\rho_K(S_K - u_K)^2 - B_n^2}{\rho_K(S_K - u_K)(S_K - S_M) - B_n^2}
$$

*double star*

$$
\mathbf v^{**}_t = \frac{\sqrt{\rho_L^*}\mathbf v^*_{tL} + \sqrt{\rho_R^*}\mathbf v^*_{tR} + (\mathbf B^*_{tR} - \mathbf B^*_{tL})\operatorname{sgn}B_n}{\sqrt{\rho_L^*} + \sqrt{\rho_R^*}}
$$

Assumptions:

- ideal MHD, a gamma-law gas; the normal field is one value on both sides of the face
- where the star denominator vanishes (B_t = 0 and B_n^2 = rho (S - u)(S - S_M)) the tangential velocity and field keep their values

References:

- [Miyoshi and Kusano, J. Comput. Phys. 208, 315 (2005)](https://doi.org/10.1016/j.jcp.2005.02.017)

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L165-L264)

## carafe.mhd.sheet_diagnostics

*function*

```python
def sheet_diagnostics(model: MHD2D, leaf: Mapping[str, np.ndarray] | None = None) -> dict
```

The reconnected flux and the plasmoids of the lower sheet of `harris_sheets`.

Along the line ``y = Ly / 4``: the reconnected flux ``psi = (1/2) int |B_y| dx`` (per
unit length out of the plane), the number of O-points (where ``B_y`` changes sign
from positive to negative along ``x``: field lines close around them) and of
X-points, and the largest ``|J_z|`` in the box. ``leaf``: the `MHD2D.leaf_values`
already computed.

[View source](https://github.com/max-models/carafe/blob/devel/src/carafe/mhd.py#L1447-L1485)
