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
52 changes: 39 additions & 13 deletions essos/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ def AbsB(self, points):
def dB_by_dX(self, points):
return jacfwd(self.B)(points)

@jit
def B_and_dB_by_dX(self, points):
jacobian, value = jacfwd(lambda x: (self.B(x),) * 2, has_aux=True)(jnp.asarray(points))
return value, jacobian

@jit
def dAbsB_by_dX(self, points):
return grad(self.AbsB)(points)
Expand Down Expand Up @@ -100,32 +105,44 @@ def _gc_from_jacobian(field, jacobian):


def _cartesian_gc_quantities(field, points):
"""``gc_quantities`` of a Cartesian field (sqrtg = 1) from one forward-mode Jacobian of ``field.B``."""
jacobian, value = jacfwd(lambda x: (field.B(x),) * 2, has_aux=True)(jnp.asarray(points))
return _gc_from_jacobian(value, jacobian)
"""``gc_quantities`` of a Cartesian field (sqrtg = 1) from ``field.B_and_dB_by_dX``."""
return _gc_from_jacobian(*field.B_and_dB_by_dX(jnp.asarray(points)))


def _biot_savart(points, gamma, gamma_dash, currents, chunk=8):
def _biot_savart(points, gamma, gamma_dash, currents, chunk=8, gradient=False):
"""Biot-Savart field at one point, summed ``chunk`` coils at a time with ``lax.scan``.

Only chunk x quadrature points are live at once (also in reverse mode, via ``checkpoint``),
so temporaries do not grow with the number of coils. The last chunk is filled with zero-current copies.
so temporaries do not grow with the number of coils. The last chunk is filled with zero-current copies,
and a set smaller than ``chunk`` runs as one step. With ``gradient=True`` the same pass also sums
dB_i/dx_j = mu0 I/4pi [(dl x e_j)_i / r^3 - 3 (dl x r)_i r_j / r^5] and returns ``(B, dB/dx)``.
"""
chunk = min(chunk, gamma.shape[0])
pad = -gamma.shape[0] % chunk
fill = lambda a, v=None: jnp.concatenate([a, jnp.repeat(a[-1:] if v is None else v, pad, axis=0)])
xs = [fill(a).reshape(-1, chunk, *a.shape[1:]) for a in (gamma, gamma_dash)]
xs.append(fill(currents, jnp.zeros(1, currents.dtype)).reshape(-1, chunk))
x = jnp.asarray(points)

@jax.checkpoint
def step(B, c):
def step(acc, c):
g, gd, i = c
dif = (x - g).T
dB = jnp.cross(gd.T, dif, axisa=0, axisb=0, axisc=0) / jnp.linalg.norm(dif, axis=0)**3
return B + jnp.einsum("i,bai->b", i, dB, optimize="greedy"), None

B0 = jnp.zeros(3, jnp.result_type(x, gamma, currents))
return 1e-7 * lax.scan(step, B0, xs)[0] / gamma.shape[1]
r = x - g
r2 = jnp.sum(r**2, axis=-1, keepdims=True)
w = i[:, None, None] / jnp.sqrt(r2)**3
cross = w * jnp.cross(gd, r)
terms = [cross]
if gradient: # S = sum w dl gives the (dl x e_j)/r^3 part, the rest is -3 (dl x r) r^T / r^2
terms += [w * gd, (-3 / r2 * cross)[..., :, None] * r[..., None, :]]
terms[1:] = [t.reshape(*t.shape[:2], -1) for t in terms[1:]]
total = jnp.sum(jnp.concatenate(terms, axis=-1), axis=(0, 1))
return acc + total, None

acc0 = jnp.zeros(15 if gradient else 3, jnp.result_type(x, gamma, currents))
out = (step(acc0, [a[0] for a in xs])[0] if xs[0].shape[0] == 1 else lax.scan(step, acc0, xs)[0]) * (1e-7 / gamma.shape[1])
if not gradient:
return out
return out[:3], jnp.cross(out[3:6], jnp.eye(3)).T + out[6:].reshape(3, 3)


class BiotSavart(MagneticField):
Expand All @@ -151,7 +168,7 @@ def gc_quantities(self, points):
"""Guiding-center field quantities from one pass over the coils.

The separate methods each rebuild B and its Jacobian (``kappa`` even
recomputes ``curl_b``). Here a single forward-mode Jacobian yields B
recomputes ``curl_b``). Here one analytic pass over the coils yields B
and dB/dX together, and in Cartesian coordinates (sqrtg = 1)
grad|B| = (dB/dX)^T b, curl b = curl B/|B| + B x grad|B|/|B|^2 and
kappa = -B x curl b / |B| follow algebraically.
Expand All @@ -162,6 +179,15 @@ def gc_quantities(self, points):
def B(self, points):
return _biot_savart(points, self.coils.gamma, self.coils.gamma_dash, self.coils.currents)

@jit
def B_and_dB_by_dX(self, points):
"""B and its Cartesian Jacobian dB_i/dx_j from one pass over the coils."""
return _biot_savart(points, self.coils.gamma, self.coils.gamma_dash, self.coils.currents, gradient=True)

@jit
def dB_by_dX(self, points):
return self.B_and_dB_by_dX(points)[1]

@jit
def A(self, points):
"""Cartesian filament vector potential [T m] at a point [m].
Expand Down
35 changes: 34 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import numpy as np
from pathlib import Path
from essos.coils import Coils, Curves
from essos.fields import BiotSavart, BiotSavart_from_gamma, _biot_savart, Vmec, VMEC_WOUT_ARRAYS
from essos.fields import BiotSavart, BiotSavart_from_gamma, _biot_savart, _gc_from_jacobian, Vmec, VMEC_WOUT_ARRAYS
import jax
import jax.numpy as jnp
from jax import random, vmap
Expand Down Expand Up @@ -823,3 +823,36 @@ def test_combined_field_fused_gc_quantities_match_generic_path():
assert jnp.allclose(a, b, rtol=1e-9, atol=1e-12)
assert all(jnp.allclose(a, b, rtol=1e-9, atol=1e-12) for a, b in zip(combined.gc_quantities(x), generic))
assert all(jnp.allclose(a, b, rtol=1e-9, atol=1e-12) for a, b in zip(ext.gc_quantities(x), MagneticField.gc_quantities(ext, x)))


def _coil_field():
path = Path(__file__).resolve().parents[1] / "examples" / "input_files" / "ESSOS_biot_savart_LandremanPaulQA.json"
return BiotSavart(Coils.from_json(str(path)))


def test_biot_savart_gradient_matches_autodiff_and_maxwell():
"""dB/dx from the fused pass equals jacfwd(B); off the coils div B = tr(dB/dx) = 0 and curl B = 0 (Ampere)."""
field = _coil_field()
for point in (jnp.array([1.0, 0.2, 0.1]), jnp.array([1.2, -0.1, 0.05])):
B, J = field.B_and_dB_by_dX(point)
assert jnp.allclose(B, field.B(point), rtol=1e-12)
assert jnp.allclose(J, jax.jacfwd(field.B)(point), rtol=1e-12, atol=1e-12 * jnp.abs(J).max())
assert jnp.abs(jnp.trace(J)) < 1e-7 * jnp.abs(J).max()
curl = jnp.array([J[2, 1] - J[1, 2], J[0, 2] - J[2, 0], J[1, 0] - J[0, 1]])
assert jnp.abs(curl).max() < 1e-7 * jnp.abs(J).max()


def test_fused_gc_quantities_gradient_matches_autodiff_path():
"""A loss through gc_quantities has the same coil gradient as the jacfwd-of-B path it replaces."""
field = _coil_field()
points = jnp.array([[1.0, 0.2, 0.1], [0.8, -0.3, 0.2]])

def loss(dofs, fused):
f = _coil_field()
f.dofs = dofs
q = (f.gc_quantities if fused else
lambda p: _gc_from_jacobian(f.B(p), jax.jacfwd(f.B)(p)))
return sum(jnp.sum(jnp.concatenate([jnp.ravel(jnp.asarray(a)) for a in q(p)[2:6]])) for p in points)

g_new, g_old = jax.grad(loss)(field.dofs, True), jax.grad(loss)(field.dofs, False)
assert jnp.allclose(g_new, g_old, rtol=1e-8, atol=1e-8 * jnp.abs(g_old).max())
Loading