import os
from pathlib import Path

# --8<-- [start:code]
"""A Halbach cylinder: 2-D magnetostatics of a ring of permanent magnets, with a vector potential.

The field B = curl(A_z e_z) = (A_y, -A_x) of magnets with remanence Br obeys curl H = 0, H = (B - Br) / mu0.
With mu_r = 1 everywhere (mu0 scaled out, B in tesla) the weak form is

    int grad A . grad v - (Br_x v_y - Br_y v_x) = 0 ,

the magnets entering as a source. A ring of N segments whose magnetisation rotates twice as fast as the
segment's position, phi_M = 2 theta, makes a uniform dipole field in the bore and almost none outside.
Reference: B = Br ln(ro / ri) * sin(2 pi / N) / (2 pi / N) for N segments (Halbach 1980), the continuous
ring at N -> infinity.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the potential is tiny against its gradient
run = jno.setup(__file__)
BR, RI, RO, RFAR = 1.2, 0.02, 0.05, 0.2  # remanence [T], bore and outer radius, truncation radius [m]
H = 0.0006  # element size in the magnets and the bore; the air outside is coarser


def halbach(n):
    """The domain of an n-segment ring and the magnetisation angle of each segment."""
    phi = 2 * np.pi * (np.arange(n) + 0.5) / n  # segment centres; segment j is magnetised along 2 phi_j
    wedge = lambda a: jno.shape.polygon(
        [(0, 0)] + [(3 * RO * np.cos(a + s), 3 * RO * np.sin(a + s)) for s in (-np.pi / n, np.pi / n)]
    )
    ring = jno.shape.disk(0, 0, RO, size=H) - jno.shape.disk(0, 0, RI)
    segments = {f"m{j}": ring & wedge(a) for j, a in enumerate(phi)}
    air = {"bore": jno.shape.disk(0, 0, RI, size=H), "air": jno.shape.disk(0, 0, RFAR, size=10 * H)}
    return jno.shape.regions({**segments, **air}).domain(), phi


def solve(n, turn=0.0):
    """A_z of the n-segment ring, and B = (A_y, -A_x) as nodal averages (L2 projection, lumped mass).
    `turn` rotates every magnetisation by the same angle."""
    d, phi = halbach(n)
    A = d.unknown()
    v = A.test()
    terms = []
    for tag in [f"m{j}" for j in range(n)] + ["bore", "air"]:
        x, y, _ = d.variable(tag, split=True)
        a, w = A.bind(x=x, y=y), v.bind(x=x, y=y)
        terms.append(a.x * w.x + a.y * w.y)  # curl H = 0 in every region
    for j, p in enumerate(phi):  # the magnets' source: remanence BR along 2 phi_j + turn
        x, y, _ = d.variable(f"m{j}", split=True)
        w = v.bind(x=x, y=y)
        terms.append(-BR * (np.cos(2 * p + turn) * w.y - np.sin(2 * p + turn) * w.x))
    fem = jno.fem([*terms, A(*d.variable("boundary", split=True)) - 0.0])
    A_h = fem.solve(linear=jno.solve.cg(), precond=jno.precond.jacobi())
    x, y, _ = d.variable("interior", split=True)
    a, w = A.bind(x=x, y=y), v.bind(x=x, y=y)
    mass = fem.eval(w, A_h)
    Bx, By = fem.eval(a.y * w, A_h) / mass, -fem.eval(a.x * w, A_h) / mass
    return d, fem, A_h, Bx, By


ideal = BR * np.log(RO / RI)  # the continuous ring, N -> infinity
solved = {n: solve(n) for n in (8, 16, 32)}
for n, (d, fem, A_h, Bx, By) in solved.items():
    pts = np.asarray(fem.points)
    bore = np.hypot(*pts.T) < 0.8 * RI  # the field is read well inside the bore
    B_bore = np.hypot(Bx[bore], By[bore])
    ref = ideal * np.sin(2 * np.pi / n) / (2 * np.pi / n)  # n segments of constant magnetisation
    print(
        f"N = {n:2d} ({fem.dofs} DOFs): B in the bore {B_bore.mean():.4f} T (spread {B_bore.std() / B_bore.mean():.1e}), "
        f"segment formula {ref:.4f} T, continuous ring {ideal:.4f} T"
    )
    assert abs(B_bore.mean() / ref - 1) < 1e-3  # the segment formula, to the mesh
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    d, fem, A_h, Bx, By = solved[16]
    _, _, A_q, Bx_q, By_q = solve(16, turn=np.pi / 2)  # every magnet turned by 90 degrees: with the first
    # solve it gives the field for any common turn, cos(turn) * first + sin(turn) * second (the problem is linear)
    np.savez_compressed(
        Path(out) / "halbach_magnets.npz",
        points=np.asarray(fem.points),
        triangles=np.asarray(d.mesh.cells_dict["triangle"]),
        A=np.asarray(A_h).ravel(),
        Bx=np.asarray(Bx),
        By=np.asarray(By),
        A_quarter=np.asarray(A_q).ravel(),
        Bx_quarter=np.asarray(Bx_q),
        By_quarter=np.asarray(By_q),
        phi=halbach(16)[1],
        geometry=[BR, RI, RO, RFAR],
        ideal=ideal,
    )
