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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,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)
Expand Down
40 changes: 39 additions & 1 deletion essos/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ def A(self, points):
"""Cartesian filament vector potential [T m] at a point [m].

Uses the same periodic coil quadrature and currents as :meth:`B`,
so ``curl(A) = B`` and shape/current derivatives remain traceable.
so ``curl(A) = B``. Open-path integrals depend on this gauge. Refine both
coil and path quadrature before using a flux derivative.
"""
distance = jnp.linalg.norm(jnp.asarray(points) - self.coils.gamma, axis=-1)
tangent_over_distance = self.coils.gamma_dash / distance[..., None]
Expand Down Expand Up @@ -199,6 +200,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):
Expand Down
76 changes: 76 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -741,6 +806,17 @@ def f(s):
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)


def test_external_field_params_are_differentiable_and_share_one_compile():
import jax
import jax.numpy as jnp
Expand Down
Loading