import os
from pathlib import Path

# --8<-- [start:code]
"""Loop resistance and inductance of a two-wire hairpin with ``jno.peec``: nothing but the metal is meshed.

The port is the pair of open ends, one volt across them. Two closed forms say what the answer must be:
R = ρ ℓ / A over the whole routed length (exact at DC), and the two-wire line's external inductance
L_ext = ℓ (μ0/π) acosh(D / 2a). ``sol.L`` is the total magnetic energy, so it also holds the flux inside the
copper, μ0 / 8π per unit length per wire at uniform DC current: compare it with external + internal.
"""

import jax

jax.config.update("jax_enable_x64", True)  # partial inductance is a difference of large numbers

import numpy as np

import jno

run = jno.setup(__file__)
CU, MU0 = 5.8e7, 4e-7 * np.pi  # copper conductivity (S/m), vacuum permeability
ELL, SEP, RAD = 0.100, 0.005, 5e-4  # leg length, wire spacing, wire radius (m)

route = [(0, 0, 0), (ELL, 0, 0), (ELL, SEP, 0), (0, SEP, 0)]  # out, across the far end, back
loop = jno.shape.line(route, r=RAD, size=2e-3).attach(sigma=CU).name("loop")
pads = jno.shape.sphere(0, 0, 0, 2 * RAD).name("A") + jno.shape.sphere(0, SEP, 0, 2 * RAD).name("B")
d = (loop + pads).domain()
i, v = d.peec_symbols()  # terminal current, nodal potential
at = lambda t: d.variable(t, split=True, sample=(4, None))[:3]

sol = jno.peec([v(*at("A")) - v(*at("B")) - 1.0], freq=0.0).solve()  # one volt across the open ends

length = 2 * ELL + SEP  # the far-end link is conductor too
R_closed = length / (CU * np.pi * RAD**2)
L_external = ELL * (MU0 / np.pi) * np.arccosh(SEP / (2 * RAD))
L_internal = 2 * ELL * MU0 / (8 * np.pi)  # both wires, uniform DC current

R, L = float(sol.R), float(sol.L)
print(f"elements {int(np.asarray(sol.i).size)}   (nothing else was meshed)")
print(f"R  {R * 1e3:8.4f} mOhm   vs rho*l/A {R_closed * 1e3:8.4f}   {100 * (R / R_closed - 1):+.4f} %")
print(f"L  {L * 1e9:8.2f} nH     vs external {L_external * 1e9:8.2f}   {100 * (L / L_external - 1):+.1f} %")
print(
    f"   {'':8}          vs ext+int  {(L_external + L_internal) * 1e9:8.2f}   {100 * (L / (L_external + L_internal) - 1):+.1f} %"
)

assert abs(R / R_closed - 1) < 1e-6, "the DC resistance is rho*l/A exactly"
assert abs(L / (L_external + L_internal) - 1) < 0.05, "within 5 % of the closed form, internal flux included"
assert L > L_external, "the total energy must exceed the external flux alone"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/two_wire_loop.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # the flux density the solved currents make in the plane of the loop
    gx, gy = np.arange(-0.02, 0.12 + 1e-9, 2.5e-4), np.arange(-0.02, SEP + 0.02 + 1e-9, 2.5e-4)
    X, Y = np.meshgrid(gx, gy)
    P = np.stack([X.ravel(), Y.ravel()], 1)
    a, b = np.array(route), np.array(route[1:] + route[:1])[:, :2]  # the legs; the last one is the open port
    a = a[:, :2]
    clear = np.ones(len(P), bool)  # keep a wire radius and a half away from every conductor
    for p0, p1 in zip(a[:3], b[:3]):
        t = np.clip(((P - p0) @ (p1 - p0)) / ((p1 - p0) @ (p1 - p0)), 0, 1)
        clear &= np.linalg.norm(P - (p0 + t[:, None] * (p1 - p0)), axis=1) > 1.5 * RAD
    Bz = np.full(len(P), np.nan)
    Bz[clear] = np.real(np.asarray(sol.field(np.c_[P[clear], np.zeros(clear.sum())])))[:, 2]
    np.savez_compressed(Path(out) / "two_wire_loop.npz", x=gx, y=gy, Bz=Bz.reshape(X.shape), route=a, radius=RAD)
