# --8<-- [start:code]
"""A transformer: a ferrite ring, two windings, and an open secondary.

A region that declares ``mu_r`` instead of (or as well as) ``sigma`` is a MAGNETIC material and is solved
for: the core becomes a second family of elements carrying magnetisation currents that couple back into
the circuit (Torchio et al., IEEE Trans. MTT 66(5), 2018). What a region carries decides what it is.

**An open terminal has a voltage.** The secondary carries no current, so its induced voltage lives in
the nodal potentials and ``sol.voltage`` reads it. With one turn on each limb the ideal-transformer
law appears on its own: V_sec / V_pri -> 1, closer as the permeability rises. No turns ratio is imposed.

**A complex permeability is a lossy core.** The imaginary part of chi = mu_r - 1 is the lossy part of
the magnetisation, as a complex permittivity carries dielectric loss; ``dissipation()`` returns it under
``.mu_r``, the ohmic loss under ``.sigma``. The check is power balance: driven by one volt a passive
network takes in Re(1/Z), and that leaves as copper loss plus core loss and nothing else.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
box, CU = jno.shape.box, 5.8e7
OUT, WIN, DEP, P = 0.024, 0.006, 0.008, 0.002  # outer size, window inset, depth, cell pitch


def ring(mu_r):  # a square core: a solid block with its window cut out
    r = box(0, 0, 0, OUT, OUT, DEP, size=(P,) * 3) - box(WIN, WIN, -P, OUT - WIN, OUT - WIN, DEP + P)
    return r.attach(mu_r=mu_r).name("core")


def turn(x_outer, x_inner, name):  # one rectangular turn: down the outside, under, up through the window, over the top
    y0, y1, s = 0.010, 0.012, (P,) * 3
    lo, hi = min(x_outer, x_inner), max(x_outer, x_inner)
    w = (
        box(x_outer, y0, -0.004, x_outer + P, y1, 0.012, size=s)
        | box(x_inner, y0, -0.004, x_inner + P, y1, 0.012, size=s)
        | box(lo, y0, -0.004, hi + P, y1, -0.002, size=s)
        | box(lo, y0, 0.010, hi + P, y1, 0.012, size=s)
    )
    return (w - box(x_outer - 0.001, y0 - 0.001, 0.002, x_outer + 0.003, y1 + 0.001, 0.004)).attach(sigma=CU).name(name)


PRI, SEC = turn(-0.004, 0.008, "pri"), turn(0.026, 0.014, "sec")  # around the left and right limbs


def solve(mu_r, freq=1e5):
    d = (ring(mu_r) + PRI + SEC).domain()
    i, v = d.peec_symbols()
    pad = lambda tag, where: d.variable(tag, where=where, split=True, sample=(2, None))
    P0 = pad("P0", lambda x, y, z: (x < -0.0021) & (z < 0.0021) & (z > 0.0001))  # the primary's two pads
    P1 = pad("P1", lambda x, y, z: (x < -0.0021) & (z > 0.0039) & (z < 0.0059))
    S0 = pad("S0", lambda x, y, z: (x > 0.0269) & (z < 0.0021) & (z > 0.0001))  # the secondary's two pads
    S1 = pad("S1", lambda x, y, z: (x > 0.0269) & (z > 0.0039) & (z < 0.0059))
    return jno.peec(
        [
            v(*P0) - v(*P1) - 1.0,  # drive the primary with one volt
            i(*S0) - 0.0,  # the secondary is OPEN: no current
            v(*S1) - 0.0,  # and a reference to measure the induced volts against
        ],
        freq=freq,
    ).solve()


# 1. the turns ratio emerges from the geometry
sols = {mu: solve(mu) for mu in (200.0, 2000.0, 20000.0)}
ratios = [abs(complex(s.voltage("S0", "S1"))) for s in sols.values()]
print("mu_r      L_pri        V_sec / V_pri")
for (mu, s), r in zip(sols.items(), ratios):
    print(f"{mu:6.0f}  {float(np.real(s.L)) * 1e9:9.1f} nH   {r:.4f}")
assert ratios[0] < ratios[1] < ratios[2] < 1.0, "the ratio must rise toward 1 and never exceed it"
assert ratios[-1] > 0.99, "at mu_r = 20000 the core should couple almost all of the flux"

# 2. a complex mu_r is a lossy core, and the energy balances: whatever the port takes in and the copper
# does not dissipate is the core (zero for a real permeability, dominant for a lossy one)
for mu in (2000.0, 2000.0 - 200.0j):
    s = solve(mu)
    copper, p_in = float(s.joule), float(np.real(1.0 / complex(s.Z)))
    core, density = p_in - copper, float(np.real(s.dissipation().mu_r["core"]))
    print(
        f"mu_r = {mu!s:>13}   in {p_in:.4e} W   copper {copper:.4e} W   core {core:.4e} W   mu_r loss {density:.4e} W/m^3"
    )
    if np.imag(mu) == 0:
        assert abs(copper / p_in - 1) < 1e-4 and density == 0.0, "a lossless core: all of it comes out of the copper"
    else:
        assert core > 10 * copper and density > 0.0, "the lossy core dominates, and the readout attributes it"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/cored_transformer.py), only when asked ----
import os  # noqa: E402
import tempfile  # noqa: E402
from pathlib import Path  # noqa: E402

import meshio  # noqa: E402

if out := os.environ.get("JNO_FIGURE_DATA"):
    with tempfile.TemporaryDirectory() as tmp:  # the windings' solved currents, as the solution exports them
        meshes = [meshio.read(s.export_vtk(f"{tmp}/{k}.vtk")) for k, s in enumerate(sols.values())]
    np.savez_compressed(
        Path(out) / "cored_transformer.npz",
        nodes=meshes[0].points,
        bars=meshes[0].cells_dict["line"],
        density=np.stack([m.cell_data["current_density"][0] for m in meshes]),
        mu_r=np.array(list(sols)),
        ratio=np.array(ratios),
        core=np.array([OUT, WIN, DEP]),
    )
