Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,3 @@ examples/input.optimized

# README figures, regenerated by docs/make_readme_figures.py
!docs/readme_*.png

# Generated tracing output stays local; compact reference data are committed.
.tmp/
examples/benchmarks/results/
!examples/benchmarks/references/*.json
!docs/_static/analytical_perturbations/*.png
# Vector copies are generated alongside the committed documentation images.
docs/_static/analytical_perturbations/*.svg
34 changes: 9 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,38 +206,22 @@ and its derivatives, together with the flux functions `G`, `I` and `iota`.

### Prescribed analytical Alfvén perturbations

Analytical modes supply `delta A = alpha B0` and an electric potential to the
existing guiding-centre equations, in Boozer coordinates or full VMEC geometry.
The corrections include magnetic flutter, induction and the parallel-force
correction, with constant magnetic moment and physical wave energy exchange.
Analytical modes supply `delta A = alpha B0` and a potential to the guiding-centre
equations, in Boozer coordinates (`trace_boozer(..., perturbation=...)`) or in full
VMEC geometry, with flutter, induction and constant magnetic moment:

```python
from essos.gc_perturbations import AnalyticalVmecAlfvenMode

wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4,
radial_center=.4, radial_width=.5)
tracing = Tracing(field=field, particles=particles,
model="GuidingCenterAdaptative", perturbation=wave,
maxtime=2e-7, times_to_trace=9, progress=False)
wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4, radial_center=.4, radial_width=.5)
tracing = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative",
perturbation=wave, maxtime=2e-7, times_to_trace=9, progress=False)
```

The [small CPU example](examples/particle_tracing/vmec_alfven_cpu_smoke.py)
traces two particles with and without a wave under a 120-second cap.
[Equations, conservation checks and reproduction commands](docs/analytical_perturbations.rst)
describe the model and its limits.
See [the equations, tests and the comparison with Paul et al. (2023)](docs/analytical_perturbations.rst);
[`alfven_perturbation.py`](examples/particle_tracing/alfven_perturbation.py) is a short example.

![Paul alpha-loss comparison: 100 particles per curve](docs/_static/analytical_perturbations/paul_loss_100.png)

The Paul comparison uses the same 100 initial particles for Boozer / Perfect QS
and VMEC / full equilibrium, without and with the m=15 wave. Weighted losses
are 12.25% / 21.53% for Boozer and 12.25% / 20.56% for VMEC. Published endpoints
are shown as crosses. This small comparison does not establish quantitative
paper reproduction. Compact saved data regenerate all documentation figures
without particle tracing:

```bash
python -m examples.benchmarks.plot_alfven_results
```
![Paul alpha-loss comparison](docs/_static/analytical_perturbations/paul_loss_100.png)

## Comparison with other codes

Expand Down
Binary file not shown.
Binary file modified docs/_static/analytical_perturbations/paul_loss_100.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
291 changes: 76 additions & 215 deletions docs/analytical_perturbations.rst

Large diffs are not rendered by default.

23 changes: 9 additions & 14 deletions essos/boozer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from jax.sharding import Mesh, NamedSharding, PartitionSpec

from essos.background_species import nu_D_ab, nu_par_ab, d_nu_par_ab, nu_s_ab, JOULE_PER_EV
from essos.perturbations import BoozerPerturbation

jax.config.update("jax_enable_x64", True)

Expand Down Expand Up @@ -601,22 +602,16 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim
stays below ``tolerance`` (in ``sqrt(s)`` and ``zeta`` units and relative to the
speed for ``v_par``); ``timestep`` is then only the first trial step.

``perturbation`` accepts a ``BoozerPerturbation`` from essos.perturbations.
``speed`` may be a positive scalar or one positive birth speed per marker
(needed to initialize sections at a common wave-frame invariant).
Every RK stage uses its own physical time. With modes, ``energy_error``
is None: physical wave work is reported as ``kinetic_energy_change``.
Check a wave-frame invariant in exact-QS single-mode benchmarks instead.
Modes plus collisions use a fixed RK orbit step followed by the existing
Boozer Euler-Maruyama speed/pitch kick. This is velocity-space collision
splitting, without GC spatial diffusion, using the main-branch collision
coefficients and operator.
A singular analytical mode can supply an inner boundary. Axis encounters
stop there and populate ``axis_stop_times``; ``lost`` retains LCFS exits.
``loss_fractions(include_axis=True)`` additionally counts axis stops.
``perturbation`` is a ``BoozerPerturbation`` (essos.perturbations); every RK stage uses its
own physical time. ``speed`` may be a scalar or one birth speed per marker. With a wave,
``energy_error`` is None and the physical wave work is ``kinetic_energy_change``; check a
wave-frame invariant in exact-QS single-mode cases instead. Waves plus collisions need a
fixed RK method and use the existing Euler-Maruyama speed/pitch kick (no GC spatial
diffusion). A singular mode supplies an inner boundary: axis encounters stop there and
fill ``axis_stop_times``, while ``lost`` keeps LCFS exits;
``loss_fractions(include_axis=True)`` counts both.
"""
if perturbation is not None:
from essos.perturbations import BoozerPerturbation
if not isinstance(perturbation, BoozerPerturbation):
raise TypeError("perturbation must implement BoozerPerturbation")
if species is not None and method.startswith("adaptive"):
Expand Down
25 changes: 4 additions & 21 deletions essos/gc_perturbations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,11 @@
import numpy as np

from essos.boozer import _evaluate, _spline
from essos.perturbations import AnalyticalAlfvenMode, BoozerPerturbation
from essos.perturbations import AnalyticalAlfvenMode, BoozerPerturbation, Perturbation


class GuidingCenterPerturbation(eqx.Module):
"""Return (alpha [m], Phi [V]) in the background's native coordinates."""

def potentials(self, field, point, t):
raise NotImplementedError

def axis_stop_threshold(self):
return None

def derivatives(self, field, point, t):
"""Potentials and their Jacobian in (x1,x2,x3,t), shape (2,4)."""
def evaluate(z):
value = self.potentials(field, z[:3], z[3])
return value, value

derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(point, t))
return value, derivative
class GuidingCenterPerturbation(Perturbation):
"""Potentials (alpha [m], Phi [V]) at the background's native point."""


class AnalyticalVmecAlfvenMode(GuidingCenterPerturbation):
Expand All @@ -59,9 +44,7 @@ def potentials(self, field, point, t):
s, theta, phi = point
mode = self.mode
harmonic = s**(mode.m/2)*jnp.sin(mode.m*theta-mode.n*phi+mode.omega*t+mode.phase)
envelope = (1. if mode.radial_width is None else
jnp.exp(-((s-mode.radial_center)/mode.radial_width)**2))
potential = mode.amplitude*envelope*harmonic
potential = mode.amplitude*mode.envelope(s)*harmonic
B = field.AbsB(point)
Bcontra = field.B_contravariant(point)
alpha = (mode.n*Bcontra[2]-mode.m*Bcontra[1])*potential/(mode.omega*B**2)
Expand Down
61 changes: 28 additions & 33 deletions essos/perturbations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,37 @@
import numpy as np


class BoozerPerturbation(eqx.Module):
"""Interface for a future computed-mode adapter, including FAX.
class Perturbation(eqx.Module):
"""Prescribed ``potentials(field, point, t) -> (alpha [m], Phi [V])``.

``potentials(field, xyz, t)`` returns ``(alpha [m], Phi [V])``;
xyz is the regular chart ``(sqrt(s) cos(theta), sqrt(s) sin(theta), zeta)``.
The equilibrium covariant field is ``I dtheta + G dzeta`` (K=0).
``axis_stop_threshold`` is an optional inner boundary in normalized toroidal
flux (None disables it); ``derivatives`` returns the potentials and their
Jacobian in (point, time), shape (2, 4).
"""

def potentials(self, field, xyz, t):
def potentials(self, field, point, t):
raise NotImplementedError

def axis_stop_threshold(self):
"""Optional inner boundary in normalized toroidal flux; None disables it."""
return None

def derivatives(self, field, xyz, t):
"""Potentials and their Jacobian in (u, w, zeta, time), shape (2, 4)."""
def derivatives(self, field, point, t):
def evaluate(z):
value = self.potentials(field, z[:3], z[3])
return value, value

derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(xyz, t))
derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(point, t))
return value, derivative


class BoozerPerturbation(Perturbation):
"""Perturbation of ``trace_boozer``; ``point`` is the regular chart
``(sqrt(s) cos(theta), sqrt(s) sin(theta), zeta)``. The equilibrium
covariant field is ``I dtheta + G dzeta`` (K=0). A computed-mode adapter,
including FAX, only needs to implement ``potentials``.
"""


class AnalyticalAlfvenMode(BoozerPerturbation):
"""Phi = amplitude * envelope(s) * sin(m theta - n zeta + omega t + phase).

Expand Down Expand Up @@ -68,36 +74,26 @@ class AnalyticalAlfvenMode(BoozerPerturbation):

def __init__(self, m, n, omega, amplitude, *, phase=0., regularize_axis=True,
radial_center=0.5, radial_width=None, axis_stop_s=1e-8):
for name, value in (("m", m), ("n", n)):
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)):
raise ValueError(f"{name} must be an integer")
if m < 0:
raise ValueError("m must be nonnegative")
for name, value in (("omega", omega), ("amplitude", amplitude),
("phase", phase), ("radial_center", radial_center)):
if isinstance(value, jax.core.Tracer):
if value.ndim:
raise ValueError(f"{name} must be a scalar")
continue
if np.ndim(value) or not np.isfinite(value):
raise ValueError(f"{name} must be a finite scalar")
if any(isinstance(v, (bool, np.bool_)) or not isinstance(v, (int, np.integer)) for v in (m, n)) or m < 0:
raise ValueError("m must be a nonnegative integer and n an integer")
if not isinstance(omega, jax.core.Tracer) and omega == 0:
raise ValueError("omega must be nonzero for the ideal Alfven relation")
if radial_width is not None and (np.ndim(radial_width) or not np.isfinite(radial_width)
or radial_width <= 0):
raise ValueError("radial_width must be positive and finite")
if not isinstance(regularize_axis, (bool, np.bool_)):
raise ValueError("regularize_axis must be boolean")
if axis_stop_s is not None and (np.ndim(axis_stop_s) or not np.isfinite(axis_stop_s)
or not 0 < axis_stop_s < 1):
raise ValueError("axis_stop_s must be None or a finite scalar strictly between 0 and 1")
if radial_width is not None and not radial_width > 0:
raise ValueError("radial_width must be positive")
if axis_stop_s is not None and not 0 < axis_stop_s < 1:
raise ValueError("axis_stop_s must be None or strictly between 0 and 1")
self.m, self.n = int(m), int(n)
self.omega, self.amplitude, self.phase = map(jnp.asarray, (omega, amplitude, phase))
self.regularize_axis = bool(regularize_axis)
self.radial_center = jnp.asarray(radial_center)
self.radial_width = None if radial_width is None else float(radial_width)
self.axis_stop_s = None if axis_stop_s is None else float(axis_stop_s)

def envelope(self, s):
if self.radial_width is None:
return 1.
return jnp.exp(-((s-self.radial_center)/self.radial_width)**2)

def axis_stop_threshold(self):
if self.regularize_axis or self.m == 0 or self.axis_stop_s is None:
return None
Expand All @@ -112,8 +108,7 @@ def potentials(self, field, xyz, t):
if not self.regularize_axis and self.m:
harmonic = jnp.where(s > 0, harmonic / jnp.where(s > 0, s, 1.)**(self.m/2),
jnp.where(self.amplitude == 0, 0., jnp.nan))
envelope = 1. if self.radial_width is None else jnp.exp(-((s-self.radial_center)/self.radial_width)**2)
phi = self.amplitude * envelope * harmonic
phi = self.amplitude * self.envelope(s) * harmonic
(iota, G, I), _ = field.profiles(s)
alpha = (self.n - self.m*iota) * phi / (self.omega*(G+iota*I))
return jnp.stack([alpha, phi])
Expand Down
Loading
Loading