carafe.mhd
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 Twith :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 gof the momentum and :math:\rho\mathbf u\cdot\mathbf gof 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".
Attributes
| Name | Description |
|---|---|
CONSERVED | No description. |
Classes
| Name | Description |
|---|---|
MHD2D | MHD (2.5D) on the patches of a patchwork hierarchy; see the module docstring. |
Functions
| Name | Description |
|---|---|
harris_sheets | Two Harris current sheets at y = Ly / 4 and 3 Ly / 4 of a periodic box. |
hlld_flux | The HLLD flux through faces between two states. |
sheet_diagnostics | The reconnected flux and the plasmoids of the lower sheet of harris_sheets. |
CONSERVEDattributemodule attribute#
CONSERVED = ('density', 'momentum_x', 'momentum_y', 'momentum_z', 'energy', 'bz')MHD2Dclass#
class MHD2D(hierarchy: AMRHierarchy, *, gamma: float = 5.0 / 3.0, mean_field: tuple[float, float] = (0.0, 0.0), resistivity: float = 0.0, limiter: str = 'vanleer', cfl: float = 0.4, conduction: tuple[float, float] = (0.0, 0.0), gravity: tuple[float, float] = (0.0, 0.0), boundaries: dict[str, str] | None = None, prefix: str = 'mhd_')MHD (2.5D) on the patches of a patchwork hierarchy; see the module docstring.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
hierarchy | AMRHierarchy | required | The 2D Cartesian hierarchy the fields live on. Its periodic axes
are periodic; the faces of the others follow boundaries. |
gamma | float | 5.0 / 3.0 | The adiabatic index. |
mean_field | tuple[float, float] | (0.0, 0.0) | The uniform in-plane field (B0x, B0y) added to the curl of
A_z. |
resistivity | float | 0.0 | The uniform resistivity eta (a magnetic diffusivity); 0 for
ideal MHD. |
limiter | str | 'vanleer' | The slope limiter of the reconstruction (carafe.limiters):
"minmod", "vanleer" (default), "mc" or "none". |
cfl | float | 0.4 | The Courant number. |
conduction | tuple[float, float] | (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] | (0.0, 0.0) | The uniform acceleration (g_x, g_y). |
boundaries | dict[str, str] | None | None | The kind of the faces of each non-periodic axis, {"x": ..., "y": ...}: "outflow" (the default) or "wall". |
prefix | str | 'mhd_' | The prefix of the names of the fields the model allocates on the
hierarchy (prefix + "density", …, prefix + "az"). |
Numerics
mass
momentum
energy
field
resistive
conduction
gravity
walls
ct contact
Order of accuracy: 2.
Assumptions:
- MHD in the plane with three velocity and field components; Heaviside–Lorentz units (); uniform resistivity , explicit
- in-plane field from a nodal : 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 bilinearly
- uniform , and ; 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)
- Tóth, J. Comput. Phys. 161, 605 (2000)
- Sharma and Hammett, J. Comput. Phys. 227, 123 (2007)
Built from:
carafe.mhd.hlld_flux
cflattributeinstance attribute#
cfl = float(cfl)conductionattributeinstance attribute#
conduction = (float(conduction[0]), float(conduction[1]))gammaattributeinstance attribute#
gamma = float(gamma)gravityattributeinstance attribute#
gravity = (float(gravity[0]), float(gravity[1]))hierarchyattributeinstance attribute#
hierarchy = hierarchylimiterattributeinstance attribute#
limiter = limitermean_fieldattributeinstance attribute#
mean_field = (float(mean_field[0]), float(mean_field[1]))namesattributeinstance attribute#
names = {name: prefix + name for name in CONSERVED}periodattributeinstance attribute#
period = float('nan')periodicattributeinstance attribute#
periodic = tuple(hierarchy.periodic)potentialattributeinstance attribute#
potential = prefix + 'az'registerattributeinstance attribute#
register = FluxRegister(hierarchy)resistivityattributeinstance attribute#
resistivity = float(resistivity)stepsattributeinstance attribute#
steps = 0timeattributeinstance attribute#
time = 0.0wallsattributeinstance attribute#
walls = tuple((kinds[name] == 'wall' for name in 'xy'))alfven_wavemethodclassmethod#
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.
blast_wavemethodclassmethod#
def blast_wave(cells: int, **options: Any) -> MHD2DThe 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.
composite_divergencemethod#
def composite_divergence() -> floatThe 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.
current_tagsmethod#
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.
datasetmethod#
def dataset(level: int = 0) -> xr.DatasetThe 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.
divergencemethod#
def divergence() -> floatThe 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.
leaf_valuesmethod#
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).
orszag_tangmethodclassmethod#
def orszag_tang(cells: int, **options: Any) -> MHD2DThe 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.
rayleigh_taylormethodclassmethod#
def rayleigh_taylor(cells: int, *, field: float = 0.0, amplitude: float = 0.01, **options: Any) -> MHD2DThe 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.
regridmethod#
def regrid(tags: dict[int, Any], **options: Any) -> NoneRegrid 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.
rotormethodclassmethod#
def rotor(cells: int, **options: Any) -> MHD2DThe 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.
runmethod#
def run(duration: float, *, max_steps: int = 1000000) -> intAdvance by duration (the last step shortened to land on it); return the steps.
set_statemethod#
def set_state(density: Value, velocity: Value | tuple[Value, Value, Value], pressure: Value, *, vector_potential: Value = 0.0, bz: Value = 0.0) -> NoneSet 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.
stable_stepmethod#
def stable_step() -> floatThe 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.
stepmethod#
def step(dt: float | None = None) -> floatAdvance by one step of Heun’s method (SSP-RK2); return the step taken.
totalsmethod#
def totals() -> dict[str, float]Integrals of the conserved fields over the domain, from the finest cells.
harris_sheetsfunction#
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).
hlld_fluxfunction#
def hlld_flux(left: np.ndarray, right: np.ndarray, bn: np.ndarray, gamma: float) -> np.ndarrayThe HLLD flux through faces between two states.
Parameters
| Name | Type | Description |
|---|---|---|
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
contact
star
double star
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:
sheet_diagnosticsfunction#
def sheet_diagnostics(model: MHD2D, leaf: Mapping[str, np.ndarray] | None = None) -> dictThe 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.