From a04f52353af3dd18f5dc9c7a81a21d15e2182b16 Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Fri, 13 Nov 2026 12:58:20 -0600 Subject: [PATCH 1/4] Accumulate dB/dx in the Biot-Savart scan so B and its gradient come from one pass --- essos/fields.py | 52 +++++++++++++++++++++++++++++++++----------- tests/test_fields.py | 36 +++++++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 14 deletions(-) diff --git a/essos/fields.py b/essos/fields.py index fd2253a3..b1ff4be2 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -39,6 +39,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) @@ -98,17 +103,19 @@ 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)] @@ -116,14 +123,24 @@ def _biot_savart(points, gamma, gamma_dash, currents, chunk=8): 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 + w = i[:, None] * jnp.sum(r**2, axis=-1)**-1.5 + cross = jnp.cross(gd, r) + B = acc[0] + jnp.einsum("ca,cai->i", w, cross, optimize="greedy") + if not gradient: + return (B,), None + S = jnp.einsum("ca,cai->i", w, gd, optimize="greedy") + r2 = jnp.sum(r**2, axis=-1) + J = jnp.cross(S, jnp.eye(3)).T - 3 * jnp.einsum("ca,cai,caj->ij", w / r2, cross, r, optimize="greedy") + return (B, acc[1] + J), None + + dtype = jnp.result_type(x, gamma, currents) + acc0 = (jnp.zeros(3, dtype),) + ((jnp.zeros((3, 3), dtype),) if gradient else ()) + out = lax.scan(step, acc0, xs)[0] + scale = 1e-7 / gamma.shape[1] + return tuple(scale * o for o in out) if gradient else scale * out[0] class BiotSavart(MagneticField): @@ -149,7 +166,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. @@ -160,6 +177,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 b_cyl(self, R, phi, Z): """Return ``(B_R, B_phi, B_Z)`` on broadcast cylindrical arrays. diff --git a/tests/test_fields.py b/tests/test_fields.py index 149bcf5a..f17bbda6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -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 @@ -786,3 +786,37 @@ 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 = BiotSavart(Coils.from_json(str(Path(__file__).resolve().parents[1] / "examples" / "input_files" + / "ESSOS_biot_savart_LandremanPaulQA.json"))) + 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()) From c6819e1d24f34c6939254ea51978b5a21332e8ce Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Fri, 13 Nov 2026 14:57:04 -0600 Subject: [PATCH 2/4] Reduce B and dB/dx channels in one sum --- essos/fields.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/essos/fields.py b/essos/fields.py index b1ff4be2..d920ea49 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -126,21 +126,21 @@ def _biot_savart(points, gamma, gamma_dash, currents, chunk=8, gradient=False): def step(acc, c): g, gd, i = c r = x - g - w = i[:, None] * jnp.sum(r**2, axis=-1)**-1.5 - cross = jnp.cross(gd, r) - B = acc[0] + jnp.einsum("ca,cai->i", w, cross, optimize="greedy") - if not gradient: - return (B,), None - S = jnp.einsum("ca,cai->i", w, gd, optimize="greedy") - r2 = jnp.sum(r**2, axis=-1) - J = jnp.cross(S, jnp.eye(3)).T - 3 * jnp.einsum("ca,cai,caj->ij", w / r2, cross, r, optimize="greedy") - return (B, acc[1] + J), None - - dtype = jnp.result_type(x, gamma, currents) - acc0 = (jnp.zeros(3, dtype),) + ((jnp.zeros((3, 3), dtype),) if gradient else ()) - out = lax.scan(step, acc0, xs)[0] - scale = 1e-7 / gamma.shape[1] - return tuple(scale * o for o in out) if gradient else scale * out[0] + r2 = jnp.sum(r**2, axis=-1, keepdims=True) + w = i[:, None, None] * r2**-1.5 + 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): From 6256a73e6c8215322fefb714bad0e564394a20aa Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Fri, 13 Nov 2026 17:48:34 -0600 Subject: [PATCH 3/4] Merge perf/biot-savart-scan; reuse _coil_field in the gradient test --- tests/test_fields.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_fields.py b/tests/test_fields.py index 4e9a658c..e8270831 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -833,8 +833,7 @@ def test_fused_gc_quantities_gradient_matches_autodiff_path(): points = jnp.array([[1.0, 0.2, 0.1], [0.8, -0.3, 0.2]]) def loss(dofs, fused): - f = BiotSavart(Coils.from_json(str(Path(__file__).resolve().parents[1] / "examples" / "input_files" - / "ESSOS_biot_savart_LandremanPaulQA.json"))) + 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))) From 900c3a7d29cf2fb20ecfd2c5f45dfb8b96cfa592 Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Mon, 16 Nov 2026 18:16:45 -0600 Subject: [PATCH 4/4] Use 1/sqrt(r2)**3 in the Biot-Savart kernel: faster on GPU --- essos/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/essos/fields.py b/essos/fields.py index 5f4754c3..6753ba42 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -129,7 +129,7 @@ def step(acc, c): g, gd, i = c r = x - g r2 = jnp.sum(r**2, axis=-1, keepdims=True) - w = i[:, None, None] * r2**-1.5 + 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