From 74afb895f2e1fe91263175898c6ccffb2b59beff Mon Sep 17 00:00:00 2001 From: rogeriojorge Date: Wed, 7 Oct 2026 12:11:18 -0500 Subject: [PATCH 1/2] Add physical section flux and filament vector potential --- README.md | 10 +++++++ essos/fields.py | 50 ++++++++++++++++++++++++++++++++++ tests/test_fields.py | 65 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+) diff --git a/README.md b/README.md index 7caa2e66..05400b65 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,16 @@ tracing.poincare_plot(shifts=[0.0]) More in [`examples/fieldline_tracing`](examples/fieldline_tracing). +For a resolved polygon on a fixed toroidal section, +`essos.fields.section_flux(field, vertices, phi, order=4)` integrates the +physical measure `B_phi dR dZ` using Cartesian `field.B`, without an extra +radius factor. Its derivatives include the field and polygon vertices. +`BiotSavart.A(xyz)` supplies the filament vector potential for independent +closed-loop Stokes checks. Counterclockwise vertices give positive planar +flux; the corresponding action for the `+e_phi` normal follows the clockwise +boundary in `(R,Z)`. These primitives require separate boundary, quadrature, +branch and transversality checks before use as a turnstile objective. + ## VMEC MGRID fields Run [`examples/simple_examples/mgrid_from_coils.py`](examples/simple_examples/mgrid_from_coils.py) diff --git a/essos/fields.py b/essos/fields.py index 4c00f982..263bfca1 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -132,6 +132,19 @@ def B(self, points): dB_sum = jnp.einsum("i,bai", self.coils.currents*1e-7, dB, optimize="greedy") return jnp.mean(dB_sum, axis=0) + @jit + def A(self, points): + """Cartesian filament vector potential in tesla metres, away from coils. + + Uses the same periodic coil quadrature as ``B``. Open-path integrals + depend on this gauge; only closed contractible loops have the usual + gauge-independent Stokes interpretation. Refine coil quadrature as + well as any path or surface quadrature before using a flux derivative. + """ + distance = jnp.linalg.norm(jnp.asarray(points) - self.coils.gamma, axis=-1) + potential = self.coils.gamma_dash / distance[..., None] + return jnp.mean(jnp.einsum("c,cqi->qi", self.coils.currents * 1e-7, potential), axis=0) + @jit def b_cyl(self, R, phi, Z): """Return ``(B_R, B_phi, B_Z)`` on broadcast cylindrical arrays. @@ -176,6 +189,43 @@ def _tree_unflatten(cls, aux_data, children): tree_util.register_pytree_node(BiotSavart, BiotSavart._tree_flatten, BiotSavart._tree_unflatten) + + +def section_flux(field, vertices, phi=0.0, *, order=4): + """Integrate physical ``B_phi dR dZ`` over a simple section polygon. + + ``field.B(xyz)`` must return Cartesian components in tesla; ``vertices`` + is an unclosed ``(n, 2)`` array of physical ``(R, Z)`` coordinates in + metres. Counterclockwise vertex order gives the positive planar integral; + reversing it changes the sign. For a +e_phi section normal, the equivalent + vector-potential circulation follows the *clockwise* boundary in R,Z. + There is no extra R in this surface integral. + + Signed fan triangles and a tensor Gauss rule on each Duffy-transformed + triangle include both field and vertex derivatives. ``order`` is static. + The polygon must be simple, and the field must be regular on its entire + fan, including any signed triangles outside a concave polygon. Boundary + resolution, self-intersections and lobe/branch identity are caller-owned + gates; this quadrature does not locate or qualify a turnstile. + """ + vertices = jnp.asarray(vertices) + if vertices.ndim != 2 or vertices.shape[1] != 2 or vertices.shape[0] < 3: + raise ValueError("vertices must have shape (n, 2), with n >= 3") + if not isinstance(order, int) or order < 1: + raise ValueError("order must be a positive integer") + nodes, weights = np.polynomial.legendre.leggauss(order) + nodes, weights = jnp.asarray((nodes + 1) / 2), jnp.asarray(weights / 2) + center = jnp.mean(vertices, axis=0) + first, second = vertices - center, jnp.roll(vertices, -1, axis=0) - center + cross = first[:, 0] * second[:, 1] - first[:, 1] * second[:, 0] + points = center + nodes[None, :, None, None] * ( + first[:, None, None, :] + nodes[None, None, :, None] * (second - first)[:, None, None, :] + ) + R, Z = points[..., 0], points[..., 1] + xyz = jnp.stack((R * jnp.cos(phi), R * jnp.sin(phi), Z), axis=-1) + magnetic = vmap(field.B)(xyz.reshape((-1, 3))).reshape(xyz.shape) + toroidal = -magnetic[..., 0] * jnp.sin(phi) + magnetic[..., 1] * jnp.cos(phi) + return jnp.einsum("e,euv,u,u,v->", cross, toroidal, nodes, weights, weights) @jit def d_dtheta_fft(f_theta): diff --git a/tests/test_fields.py b/tests/test_fields.py index 0f033ad4..e7699e72 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -46,6 +46,71 @@ def test_biot_savart_cylindrical_interface_matches_cartesian_and_differentiates( derivative = jax.grad(lambda radius: jnp.sum(field.b_cyl(radius, phi, Z)[0]))(R) assert jnp.all(jnp.isfinite(derivative)) + +def test_section_flux_physical_measure_orientation_and_shape_derivative(): + from essos.fields import section_flux + + class Toroidal: + def B(self, xyz): + return 2.3 * jnp.array([-xyz[1], xyz[0], 0.0]) / (xyz[0]**2 + xyz[1]**2) + + polygon = jnp.array([[0.8, -0.2], [1.4, -0.2], [1.4, 0.5], [0.8, 0.5]]) + expected = 2.3 * np.log(1.4 / 0.8) * 0.7 + evaluate = jax.jit(lambda vertices: section_flux(Toroidal(), vertices, 0.37, order=12)) + np.testing.assert_allclose(evaluate(polygon), expected, rtol=2e-13) + np.testing.assert_allclose(evaluate(polygon[::-1]), -expected, rtol=2e-13) + # Move the two right vertices: the shape term is B_phi(R2) * height. + direction = jnp.array([[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [0.0, 0.0]]) + _, derivative = jax.jvp(evaluate, (polygon,), (direction,)) + np.testing.assert_allclose(derivative, 2.3 * 0.7 / 1.4, rtol=2e-12) + np.testing.assert_allclose(jnp.sum(jax.grad(evaluate)(polygon) * direction), derivative, rtol=2e-12) + np.testing.assert_allclose(jax.vmap(evaluate)(jnp.stack([polygon, polygon[::-1]])), [expected, -expected], rtol=2e-13) + for invalid in (jnp.zeros((2, 2)), jnp.zeros((3, 3))): + with pytest.raises(ValueError, match='vertices'): + section_flux(Toroidal(), invalid) + with pytest.raises(ValueError, match='order'): + section_flux(Toroidal(), polygon, order=0) + + +def test_section_flux_concave_polygon_and_field_scaling(): + from essos.fields import section_flux + + polygon = jnp.array([[1., 0.], [3., 0.], [3., 1.], [2., 1.], [2., 2.], [1., 2.]]) + + def flux(scale): + class ConstantToroidal: + def B(self, xyz): + phi = jnp.arctan2(xyz[1], xyz[0]) + return scale * jnp.array([-jnp.sin(phi), jnp.cos(phi), 0.0]) + return section_flux(ConstantToroidal(), polygon, 0.63) + + np.testing.assert_allclose(jax.jit(jax.value_and_grad(flux))(2.0), [6.0, 3.0], atol=1e-13) + np.testing.assert_allclose(flux(-2.0), -6.0, atol=1e-13) + + +def test_filament_potential_curl_and_closed_section_stokes(): + from essos.fields import section_flux + # A tilted circular coil, away from the entire section polygon. + dofs = jnp.zeros((1, 3, 3)).at[0, 0, 2].set(2.0).at[0, 2, 1].set(2.0) + field = BiotSavart(Coils(Curves(dofs, n_segments=128, stellsym=False), jnp.array([1.0e5]))) + point = jnp.array([0.8, 0.2, 0.1]) + da = jax.jacfwd(field.A)(point) + curl = jnp.array([da[2, 1]-da[1, 2], da[0, 2]-da[2, 0], da[1, 0]-da[0, 1]]) + np.testing.assert_allclose(curl, field.B(point), rtol=2e-13, atol=1e-14) + polygon = jnp.array([[0.6, -0.2], [1.0, -0.2], [1.0, 0.2], [0.6, 0.2]]) + nodes, weights = np.polynomial.legendre.leggauss(16) + first, delta = polygon, jnp.roll(polygon, -1, axis=0)-polygon + locations = first[:, None, :] + (jnp.asarray(nodes)+1)[None, :, None] * delta[:, None, :] / 2 + xyz = jnp.stack([locations[..., 0], jnp.zeros_like(locations[..., 0]), locations[..., 1]], -1) + potential = jax.vmap(field.A)(xyz.reshape(-1, 3)).reshape(xyz.shape) + # CCW in R,Z has physical normal -e_phi, so the action has opposite sign. + circulation = jnp.einsum('eqi,ei,q->', potential[..., jnp.array([0, 2])], delta, jnp.asarray(weights)/2) + np.testing.assert_allclose(section_flux(field, polygon, order=12), -circulation, rtol=2e-12, atol=1e-14) + # A smooth single-valued gauge chi=x^2*z+0.7*y^2 has zero closed circulation. + gauge = jnp.stack([2*xyz[..., 0]*xyz[..., 2], 1.4*xyz[..., 1], xyz[..., 0]**2], -1) + gauged = jnp.einsum('eqi,ei,q->', (potential+gauge)[..., jnp.array([0, 2])], delta, jnp.asarray(weights)/2) + np.testing.assert_allclose(gauged, circulation, atol=1e-14) + # def test_biot_savart_B(): # coils = MockCoils() # biot_savart = BiotSavart(coils) From 0411397bc56191a945838302cefc4a1b968cb9e1 Mon Sep 17 00:00:00 2001 From: Rogerio Jorge Date: Mon, 19 Oct 2026 11:36:45 -0500 Subject: [PATCH 2/2] Test surface toroidal_flux with BiotSavart.A --- tests/test_fields.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/test_fields.py b/tests/test_fields.py index 05643e8a..dda0e945 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -767,3 +767,14 @@ def f(s): return _radial_interp(s, grid, table, jnp.array([0]), half_grid=True)[0] for s in (0.994, 0.996, 0.999, 1.0): assert jnp.isclose(f(s), 1 + s, rtol=1e-12) and jnp.isclose(jax.grad(f)(s), 1.0, rtol=1e-9) + + +def test_surface_toroidal_flux_uses_filament_potential(): + from essos.fields import section_flux + from essos.surfaces import surfacerzfourier_from_boundary, toroidal_flux + dofs = jnp.zeros((1, 3, 3)).at[0, 0, 2].set(2.0).at[0, 2, 1].set(2.0) + field = BiotSavart(Coils(Curves(dofs, n_segments=128, stellsym=False), jnp.array([1.0e5]))) + surface = surfacerzfourier_from_boundary([[0.8, 0.15]], [[0.0, 0.15]], 1, ntheta=64, nphi=4) + gamma = surface.gamma[0] + section = jnp.stack([jnp.hypot(gamma[:, 0], gamma[:, 1]), gamma[:, 2]], -1) + np.testing.assert_allclose(toroidal_flux(surface, field), -section_flux(field, section), rtol=5e-3)