diff --git a/README.md b/README.md index 0a6bff6b..a40e39c7 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ pip install essos (RK4, Dopri5, Dopri8) or adaptive Dormand-Prince stepping and optional collisions. - **Field-line tracing.** Adaptive, arclength and toroidal-angle models, with Poincare sections. -- **Fields.** Biot-Savart from coils, VMEC equilibria (stellarator-symmetric or +- **Fields.** Biot-Savart from coils, point dipoles (permanent magnets), VMEC equilibria (stellarator-symmetric or not, analytic derivatives, optional `mode_tolerance` truncation) and near-axis expansions. Fields combine as vectors (`coils + other`, `2.0 * field`), and `field.compare(other, points)` measures two fields at the same physical diff --git a/essos/fields.py b/essos/fields.py index 45db939f..869ef6bc 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -755,6 +755,42 @@ def series(c, s): # sum c cos + s sin, and its first two theta derivatives (R, dR, d2R), (Z, dZ, d2Z) = series(rc, rs), series(zc, zs) return R, Z, dR, dZ, d2R, d2Z +class PointDipoleField(MagneticField): + """Point dipoles, such as permanent magnets, in Cartesian coordinates. + + B(x) = mu0 / (4 pi) sum_j [3 (m_j . r_j) r_j / |r_j|^5 - m_j / |r_j|^3], + r_j = x - x_j, for dipoles at ``positions`` (n, 3) [m] with ``moments`` + (n, 3) [A m^2]. The moments are the optimization ``dofs``. + """ + + def __init__(self, positions, moments): + self.positions, self.moments = jnp.asarray(positions), jnp.asarray(moments) + + @property + def dofs(self): + return self.moments + + @dofs.setter + def dofs(self, moments): + self.moments = jnp.asarray(moments) + + @jit + def B(self, points): + r = points - self.positions + r2 = jnp.sum(r * r, axis=1, keepdims=True) + mr = jnp.sum(self.moments * r, axis=1, keepdims=True) + return 1e-7 * jnp.sum((3 * mr * r - r2 * self.moments) / r2**2.5, axis=0) + + +def _unflatten_dipoles(_, children): # without __init__: transforms put non-array leaves here + field = PointDipoleField.__new__(PointDipoleField) + field.positions, field.moments = children + return field + + +tree_util.register_pytree_node(PointDipoleField, lambda f: ((f.positions, f.moments), None), _unflatten_dipoles) + + class near_axis: def __init__(self, *args, **kwargs): raise ImportError( diff --git a/examples/particle_tracing/trace_particles_interpolated_dipoles.py b/examples/particle_tracing/trace_particles_interpolated_dipoles.py index c454afc9..422fd594 100644 --- a/examples/particle_tracing/trace_particles_interpolated_dipoles.py +++ b/examples/particle_tracing/trace_particles_interpolated_dipoles.py @@ -12,11 +12,11 @@ import jax import jax.numpy as jnp import numpy as np -from jax import tree_util, vmap +from jax import vmap from essos.coils import Coils from essos.constants import ALPHA_PARTICLE_CHARGE, ALPHA_PARTICLE_MASS, ONE_EV from essos.dynamics import Particles, Tracing -from essos.fields import BiotSavart, CombinedField, InterpolatedField, MagneticField +from essos.fields import BiotSavart, CombinedField, InterpolatedField, PointDipoleField from essos.surfaces import SurfaceClassifier, SurfaceRZFourier args = sys.argv[1:] + ["4000", "32", "48", "2e-5"][len(sys.argv) - 1:] @@ -28,28 +28,6 @@ classifier = SurfaceClassifier(boundary, h=0.03) -@tree_util.register_pytree_node_class -class Dipoles(MagneticField): - """Point dipoles: B = 1e-7 sum (3 r (m.r)/r^5 - m/r^3).""" - def __init__(self, positions, moments): - self.positions, self.moments = positions, moments - - def B(self, point): - r = point - self.positions - d = jnp.linalg.norm(r, axis=1, keepdims=True) - return 1e-7 * jnp.sum(3 * r * jnp.sum(self.moments * r, 1, keepdims=True) / d**5 - self.moments / d**3, 0) - - def sqrtg(self, point): - return 1. - - def tree_flatten(self): - return (self.positions, self.moments), None - - @classmethod - def tree_unflatten(cls, aux, children): - return cls(*children) - - # Magnets 0.15 m outside the plasma boundary, along its normal, copied to all 2*nfp symmetric images. nfp, rng = coils.nfp, np.random.default_rng(0) shell = SurfaceRZFourier(boundary.rc, boundary.zs, nfp, boundary.mpol, boundary.ntor, ntheta=256, nphi=256) @@ -65,7 +43,7 @@ def tree_unflatten(cls, aux, children): angles = 2 * np.pi * np.arange(nfp) / nfp rotations = [np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) for a in angles] pos, mom = (np.concatenate([x @ r.T for r in rotations]) for x in (pos, mom)) -field = CombinedField(BiotSavart(coils), Dipoles(jnp.array(pos), jnp.array(mom))) +field = CombinedField(BiotSavart(coils), PointDipoleField(jnp.array(pos), jnp.array(mom))) time0 = time() interp = InterpolatedField(field, R=(0.58, 1.33), Z=(-0.42, 0.42), nr=grid, nz=grid, nphi=2 * grid, nfp=nfp, diff --git a/tests/test_fields.py b/tests/test_fields.py index d1798f84..c9d029e1 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -759,6 +759,26 @@ def test_field_algebra_and_comparison(): assert jnp.allclose(total.compare(coils, p), 2. / 3.) # |3B - B| / |3B| +def test_dipole_field_matches_the_axis_formula_and_is_curl_and_divergence_free(): + from essos.fields import PointDipoleField + m = 2.0e3 + field = PointDipoleField(jnp.zeros((1, 3)), jnp.array([[0., 0., m]])) + assert jnp.allclose(field.B(jnp.array([0., 0., 0.5])), jnp.array([0., 0., 1e-7 * 2 * m / 0.5**3])) + J = field.dB_by_dX(jnp.array([0.3, -0.2, 0.4])) + assert jnp.abs(jnp.trace(J)) < 1e-12 * jnp.abs(J).max() and jnp.allclose(J, J.T, atol=1e-12 * jnp.abs(J).max()) + assert jnp.allclose(jax.grad(lambda d: field.__class__(field.positions, d).B(jnp.array([0., 0., 0.5]))[2])(field.dofs), + jnp.array([[0., 0., 1e-7 * 2 / 0.5**3]])) + + +def test_sum_of_coils_and_dipoles_traces_field_lines(): + from essos.dynamics import Tracing + from essos.fields import PointDipoleField + field = _coil_field() + PointDipoleField(jnp.array([[2.0, 0., 0.]]), jnp.array([[0., 0., 1e2]])) + 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_full_orbits_in_toroidal_fields_trace_in_the_cartesian_view(): from essos.dynamics import Tracing, Particles vmec = Vmec(WOUT_FILE)