From 058360fdacc04f3f09e0d70a6b8daea230f4acc3 Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Wed, 7 Oct 2026 11:59:46 -0500 Subject: [PATCH] DescField, NearAxisField, and full orbits in toroidal fields DescField evaluates a DESC equilibrium as DESC writes it: Fourier-Zernike series for R, Z and lambda (Jacobi recurrence), iota tabulated on 1025 radii with cubic Hermite interpolation, and B^theta, B^phi from the toroidal flux, lambda and iota. On precise QA it matches DESC's own B to 4e-13 (2e-9 at 2.5% beta). from_desc reads a DESC Equilibrium or file, or the .npz that save writes, which needs no DESC install. NearAxisField traces a pyQSC_JAX near-axis field in its Boozer coordinates with the expansion's own components, |B| and Jacobian; to_xyz is first order like the field. Full orbits move in Cartesian space, so Tracing now traces full-orbit models in a toroidal field through field.cartesian() (B at Cartesian points), from the Cartesian position of each guiding center. Before, the Lorentz force read (s, theta, phi) as (x, y, z). The minor radius from the boundary cross-sections moves to ToroidalField, shared by MRXField and DescField. --- essos/dynamics.py | 15 +++- essos/fields.py | 190 +++++++++++++++++++++++++++++++++++++++++-- tests/test_fields.py | 62 ++++++++++++++ 3 files changed, 261 insertions(+), 6 deletions(-) diff --git a/essos/dynamics.py b/essos/dynamics.py index 64869fed..be3eb9f1 100644 --- a/essos/dynamics.py +++ b/essos/dynamics.py @@ -1,4 +1,5 @@ from pyexpat import model +import copy import os import jax jax.config.update("jax_enable_x64", True) @@ -22,7 +23,7 @@ import diffrax import optimistix as optx from essos.coils import Coils -from essos.fields import BiotSavart, ExternalField, MagneticField, is_toroidal +from essos.fields import BiotSavart, ExternalField, MagneticField, NearAxisField, is_toroidal from essos.surfaces import SurfaceClassifier from essos.electric_field import Electric_field_flux, Electric_field_zero from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY,ELEMENTARY_CHARGE,SPEED_OF_LIGHT @@ -943,6 +944,18 @@ def __init__(self, trajectories_input=None, initial_conditions=None, times_to_tr else: self.electric_field=electric_field + full_orbit = model is not None and model.startswith('FullOrbit') + if full_orbit and isinstance(getattr(field, "fields", (field,))[0], NearAxisField): + raise ValueError("full orbits need B at Cartesian points, which a near-axis field does not invert to") + if full_orbit and is_toroidal(field): + # Full orbits move in Cartesian space: trace them in the Cartesian view of the field, from the + # Cartesian position of each guiding center given in (s, theta, phi), up to the boundary s = 1. + toroidal, particles = field, copy.copy(particles) + particles.initial_xyz = vmap(field.to_xyz)(particles.initial_xyz) + field = field.cartesian() + particles.to_full_orbit(field) + if condition is None and stopping_criteria is None: + condition = lambda t, y, args, **kwargs: 1.0 - toroidal.flux_coordinates(y[:3])[0][0] if isinstance(field, Coils): self.field = BiotSavart(field) else: diff --git a/essos/fields.py b/essos/fields.py index 3296f4fe..ddb0c9d2 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -112,6 +112,10 @@ def difference(point): return jnp.linalg.norm(B - other.B_xyz(self.to_xyz(point))) / jnp.linalg.norm(B) return vmap(difference)(points) + def cartesian(self): + """This field in Cartesian coordinates, B(x) = :meth:`B_xyz`: the field full orbits move in.""" + return ExternalField(lambda xyz: vmap(self.B_xyz)(xyz)) + def __add__(self, other): return CombinedField(self, other) @@ -389,6 +393,13 @@ def d(f): values = vmap(lambda t: jnp.stack([rz(t), d(rz)(t), d(d(rz))(t)]))(jnp.ravel(theta)) return tuple(values[:, i, j].reshape(jnp.shape(theta)) for i in range(3) for j in range(2)) + def _minor_radius(self): + """Radius of the circle with the mean area of the boundary cross-sections of one field period.""" + theta = jnp.linspace(0, 2 * jnp.pi, 128, endpoint=False) + R, Z, dR, dZ = vmap(lambda phi: jnp.stack(self._boundary_rz(theta, phi)[:4]), out_axes=1)( + jnp.linspace(0, 2 * jnp.pi / self.nfp, 8, endpoint=False)) + return jnp.sqrt(jnp.abs(jnp.mean(R * dZ - Z * dR))) + @jit def boundary_distance(self, xyz): """Signed distance [m] from a Cartesian point to the LCFS, in its phi = const plane. @@ -718,11 +729,8 @@ class MRXField(ToroidalField): def __init__(self, raw, basis, Phi, nfp, Aminor_p=None): self.raw, self.basis, self.Phi, self.nfp, self.Aminor_p = raw, basis, Phi, int(nfp), Aminor_p - if Aminor_p is None: # radius of the circle with the mean boundary cross-section area - theta = jnp.linspace(0, 2 * jnp.pi, 128, endpoint=False) - R, Z, dR, dZ = vmap(lambda phi: jnp.stack(self._boundary_rz(theta, phi)[:4]), out_axes=1)( - jnp.linspace(0, 2 * jnp.pi / self.nfp, 8, endpoint=False)) - self.Aminor_p = jnp.sqrt(jnp.abs(jnp.mean(R * dZ - Z * dR))) + if Aminor_p is None: + self.Aminor_p = self._minor_radius() @classmethod def from_mrx(cls, geometry, checkpoint=None, resolution=(12, 16, 16), degree=3): @@ -810,6 +818,123 @@ def _tree_unflatten(cls, aux_data, children): tree_util.register_pytree_node(MRXField, MRXField._tree_flatten, MRXField._tree_unflatten) +def _hermite(x, values): + """Cubic Hermite interpolation of ``values`` given on a uniform grid of [0, 1], with centred-difference slopes.""" + n = len(values) - 1 + slope = jnp.gradient(values) + i = jnp.clip(jnp.floor(x * n).astype(int), 0, n - 1) + t = x * n - i + return ((1 + 2 * t) * (1 - t)**2 * values[i] + t * (1 - t)**2 * slope[i] + + t * t * (3 - 2 * t) * values[i + 1] + t * t * (t - 1) * slope[i + 1]) + + +def _fourier_zernike(c, modes, rho, theta, zeta, nfp): + """sum_k c_k R_k(rho) F(m_k theta) F(n_k nfp zeta) of a DESC Fourier-Zernike series with modes (l, m, n). + + R_k = (-1)^j rho^|m| P_j^(|m|, 0)(1 - 2 rho^2), j = (l - |m|) / 2, with the + Jacobi polynomial from its three-term recurrence (stable at high l), and + F(k x) = cos(k x) for k >= 0, sin(|k| x) for k < 0, as in DESC. + """ + l, m, n = (np.asarray(modes)[:, i] for i in range(3)) + a, j = np.abs(m), (l - np.abs(m)) // 2 + x = 1 - 2 * rho**2 + P_prev, P = 0. * a, 1. + 0. * a + radial = jnp.where(j == 0, P, 0.) + for k in range(int(j.max(initial=0))): + if k == 0: + P_prev, P = P, (a + 1) + (a + 2) * (x - 1) / 2 + else: + b = 2 * k + a + P_prev, P = P, ((b + 1) * (b * (b + 2) * x + a**2) * P - 2 * k * (k + a) * (b + 2) * P_prev) / ( + 2 * (k + 1) * (k + a + 1) * b) + radial = jnp.where(j == k + 1, P, radial) + angle = lambda k, x: jnp.where(k >= 0, jnp.cos(np.abs(k) * x), jnp.sin(np.abs(k) * x)) + return jnp.sum(c * (-1.)**j * rho**a * radial * angle(m, theta) * angle(n, nfp * zeta)) + + +@tree_util.register_static +class DescField(ToroidalField): + """A DESC equilibrium (https://github.com/PlasmaControl/DESC) in the coordinates of :class:`ToroidalField`. + + DESC writes R, Z and the stream function lambda as Fourier-Zernike + series in (rho, theta, zeta), with zeta the cylindrical angle. Here + (s, theta, phi) = (rho^2, theta, zeta). With the toroidal flux ``Psi`` and + sqrt(g) the Jacobian of ``to_xyz`` in (s, theta, phi), + + B^s = 0, B^theta = Psi (iota - d_phi lambda) / (2 pi sqrt(g)), + B^phi = Psi (1 + d_theta lambda) / (2 pi sqrt(g)). + + The series are evaluated as DESC writes them, so the field is exact on + the axis. ``iota`` holds the rotational transform on a uniform grid in rho + from 0 to 1, interpolated by cubic Hermite polynomials (continuous + derivative, as guiding centers need). :meth:`from_desc` builds the field from a DESC + equilibrium or file, or from the ``.npz`` that :meth:`save` writes, which + needs no DESC install. + """ + + def __init__(self, R_lmn, Z_lmn, L_lmn, R_modes, Z_modes, L_modes, Psi, nfp, iota): + self.coefficients = tuple(jnp.asarray(c) for c in (R_lmn, Z_lmn, L_lmn)) + self.modes = tuple(np.asarray(m, dtype=int) for m in (R_modes, Z_modes, L_modes)) + self.Psi, self.nfp, self.iota = float(Psi), int(nfp), jnp.asarray(iota) + self.Aminor_p = self._minor_radius() + + @classmethod + def from_desc(cls, source): + """The field of a DESC ``Equilibrium``, of a DESC output file (both need DESC), or of an ``.npz`` from :meth:`save`.""" + if isinstance(source, str) and source.endswith(".npz"): + data = np.load(source) + return cls(*(data[k] for k in ("R_lmn", "Z_lmn", "L_lmn", "R_modes", "Z_modes", "L_modes", "Psi", "nfp", "iota"))) + if isinstance(source, str): + import desc.io + source = desc.io.load(source) + source = source[-1] if hasattr(source, "__len__") else source # the last of a solve sequence + from desc.grid import LinearGrid + grid = LinearGrid(rho=np.linspace(0, 1, 1025), M=source.M_grid, N=source.N_grid, NFP=source.NFP) + iota = grid.compress(source.compute("iota", grid=grid)["iota"]) + return cls(source.R_lmn, source.Z_lmn, source.L_lmn, source.R_basis.modes, source.Z_basis.modes, + source.L_basis.modes, source.Psi, source.NFP, iota) + + def save(self, path): + """Write the field to an ``.npz`` that :meth:`from_desc` reads without DESC.""" + np.savez(path, **dict(zip(("R_lmn", "Z_lmn", "L_lmn"), self.coefficients)), + **dict(zip(("R_modes", "Z_modes", "L_modes"), self.modes)), Psi=self.Psi, nfp=self.nfp, iota=self.iota) + + def _series(self, i, points): + s, theta, phi = points + return _fourier_zernike(self.coefficients[i], self.modes[i], jnp.sqrt(s), theta, phi, self.nfp) + + @jit + def to_xyz(self, points): + R, Z = self._series(0, points), self._series(1, points) + return jnp.array([R * jnp.cos(points[2]), R * jnp.sin(points[2]), Z]) + + def _frame(self, points): + e = jacfwd(self.to_xyz)(points) + sqrtg = jnp.linalg.det(e) + dlambda = jax.grad(lambda p: self._series(2, p))(points) + iota = _hermite(jnp.sqrt(points[0]), self.iota) + B_con = self.Psi / (2 * jnp.pi * sqrtg) * jnp.array([0., iota - dlambda[2], 1 + dlambda[1]]) + return e, sqrtg, B_con + + @jit + def sqrtg(self, points): + return self._frame(points)[1] + + @jit + def B_contravariant(self, points): + return self._frame(points)[2] + + @jit + def B(self, points): + e, _, B_con = self._frame(points) + return e @ B_con + + @jit + def B_covariant(self, points): + e, _, B_con = self._frame(points) + return e.T @ (e @ B_con) + + class PointDipoleField(MagneticField): """Point dipoles, such as permanent magnets, in Cartesian coordinates. @@ -846,6 +971,61 @@ def _unflatten_dipoles(_, children): # without __init__: transforms put non-arr tree_util.register_pytree_node(PointDipoleField, lambda f: ((f.positions, f.moments), None), _unflatten_dipoles) +@tree_util.register_static +class NearAxisField(MagneticField): + """A first-order near-axis field from pyQSC_JAX, in its Boozer coordinates (r, theta, varphi). + + ``qsc`` is a ``pyqsc_jax.near_axis.near_axis``. Its covariant and + contravariant components, |B| and Jacobian are used as they are, so + guiding centers and field lines follow the expansion exactly. ``to_xyz`` + places a point at r X n + r Y b off the axis in its Frenet frame at the + axis angle phi0(varphi); it is first order in r like the field, so the + Cartesian ``B`` agrees with the components to O(r). (r, theta) is + singular on the axis, so orbits must stay off it, and full orbits, which + need B at Cartesian points, are not available. + """ + + def __init__(self, qsc): + self.qsc, self.nfp = qsc, int(qsc.nfp) + + @jit + def B_covariant(self, points): + return self.qsc.B_covariant(points) + + @jit + def B_contravariant(self, points): + return self.qsc.B_contravariant(points) + + @jit + def AbsB(self, points): + return self.qsc.AbsB(points) + + @jit + def sqrtg(self, points): + return self.qsc.jacobian(points) + + @jit + def to_xyz(self, points): + r, theta, varphi = points + q, period = self.qsc, 2 * jnp.pi / self.nfp + + def at(a, x): # periodic linear interpolation of a quantity on the axis grid + return jnp.interp(x, jnp.append(q.phi, period), jnp.append(a, a[0]), period=period) + shift = period * jnp.floor(varphi / period) # phi0 - varphi is periodic, phi0 itself is not + phi0 = shift + jnp.interp(varphi - shift, jnp.append(q.varphi, period), jnp.append(q.phi, period)) + X, Y = (r * (at(c1, phi0) * jnp.cos(theta) + at(s1, phi0) * jnp.sin(theta)) + for c1, s1 in ((q.X1c_untwisted, q.X1s_untwisted), (q.Y1c_untwisted, q.Y1s_untwisted))) + R = at(q.R0, phi0) + X * at(q.normal_R, phi0) + Y * at(q.binormal_R, phi0) + P = X * at(q.normal_phi, phi0) + Y * at(q.binormal_phi, phi0) # displacement along phi-hat + Z = at(q.Z0, phi0) + X * at(q.normal_z, phi0) + Y * at(q.binormal_z, phi0) + c, s = jnp.cos(phi0), jnp.sin(phi0) + return jnp.array([R * c - P * s, R * s + P * c, Z]) + + @jit + def B(self, points): + return jacfwd(self.to_xyz)(points) @ self.B_contravariant(points) + + class near_axis: def __init__(self, *args, **kwargs): raise ImportError( diff --git a/tests/test_fields.py b/tests/test_fields.py index 88638049..73852121 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -631,3 +631,65 @@ def test_sum_of_coils_and_dipoles_traces_field_lines(): tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=jnp.array([[1.0, 0., 0.]]), maxtime=1e-6, times_to_trace=5) assert jnp.all(jnp.isfinite(tracing.trajectories)) + + +def test_fourier_zernike_radial_polynomials_match_closed_forms(): + from essos.fields import _fourier_zernike + rho = jnp.linspace(0.05, 1.0, 7) + for l, m, closed in ((4, 2, lambda r: 4 * r**4 - 3 * r**2), (5, -1, lambda r: 10 * r**5 - 12 * r**3 + 3 * r), + (6, 0, lambda r: 20 * r**6 - 30 * r**4 + 12 * r**2 - 1)): + value = vmap(lambda r: _fourier_zernike(jnp.ones(1), [[l, m, 0]], r, 0.3, 0.0, 1))(rho) + angle = jnp.cos(abs(m) * 0.3) if m >= 0 else jnp.sin(abs(m) * 0.3) + assert jnp.allclose(value, closed(rho) * angle, rtol=1e-12) + + +def _synthetic_desc(tmp_path=None): + from essos.fields import DescField + R_modes, R = [[0, 0, 0], [1, 1, 0], [2, 2, 1]], [1.0, 0.2, 0.02] + Z_modes, Z = [[1, -1, 0], [2, -2, -1]], [0.25, 0.02] + L_modes, L = [[2, 2, 1], [3, -1, -1]], [0.01, -0.005] + iota = 0.4 + 0.1 * jnp.linspace(0, 1, 65)**2 + return DescField(R, Z, L, R_modes, Z_modes, L_modes, Psi=0.1, nfp=3, iota=iota) + + +def test_desc_field_components_are_consistent_and_divergence_free(tmp_path): + from essos.fields import DescField, _hermite, is_toroidal + field = _synthetic_desc() + p = jnp.array([[0.3, 0.4, 0.2], [0.7, 2.0, 1.5], [0.05, 5.0, 4.0]]) + e = vmap(jax.jacfwd(field.to_xyz))(p) + B = vmap(field.B)(p) + assert jnp.allclose(jnp.einsum("nij,nj->ni", e, vmap(field.B_contravariant)(p)), B, rtol=1e-12) + assert jnp.allclose(jnp.einsum("nij,ni->nj", e, B), vmap(field.B_covariant)(p), rtol=1e-12) + divergence = vmap(lambda q: jnp.trace(jax.jacfwd(lambda x: field.sqrtg(x) * field.B_contravariant(x))(q)))(p) + assert jnp.max(jnp.abs(divergence)) < 1e-12 * jnp.max(jnp.abs(vmap(field.sqrtg)(p) * B[:, 0])) + assert jnp.isclose(_hermite(jnp.sqrt(0.49), field.iota), 0.4 + 0.1 * 0.49, rtol=1e-6) + assert is_toroidal(field) and jnp.isclose(field.Aminor_p, 0.25 * jnp.sqrt(0.2 / 0.25), rtol=0.1) + field.save(tmp_path / "desc.npz") + again = DescField.from_desc(str(tmp_path / "desc.npz")) + assert jnp.allclose(vmap(again.B)(p), B) + + +def test_full_orbits_in_toroidal_fields_trace_in_the_cartesian_view(): + from essos.dynamics import Tracing, Particles + vmec = Vmec(WOUT_FILE) + x0 = jnp.array([[0.3, 0.2, 0.1], [0.5, 1.0, 0.4]]) + particles = Particles(initial_xyz=x0, field=vmec) + tracing = Tracing(field=vmec, model="FullOrbit_Boris", particles=particles, maxtime=1e-7, timestep=1e-10, + times_to_trace=10) + xyz = tracing.trajectories[:, :, :3] + # The orbits start one gyroradius off their guiding centers, given in (s, theta, phi), and stay near them. + assert jnp.all(jnp.linalg.norm(xyz[:, 0] - vmap(vmec.to_xyz)(x0), axis=1) < 0.2) + energy = tracing.energy() + assert jnp.allclose(energy[:, -1], energy[:, 0], rtol=1e-6) + + +def test_near_axis_field_is_consistent_to_first_order(): + pytest.importorskip("pyqsc_jax") + from pyqsc_jax.near_axis import near_axis + from essos.fields import NearAxisField + field = NearAxisField(near_axis(rc=[1, 0.155, 0.0102], zs=[0, 0.154, 0.0111], etabar=0.64, nfp=2, nphi=61)) + errors = [] + for r in (0.02, 0.08): + p = jnp.stack([jnp.full(32, r), jnp.linspace(0, 6.28, 32), jnp.linspace(0, 6.28, 32)], 1) + errors.append(jnp.max(jnp.abs(jnp.linalg.norm(vmap(field.B)(p), axis=1) / vmap(field.AbsB)(p) - 1))) + assert errors[1] < 0.1 and errors[1] > errors[0] # first order: the mismatch grows with r