# --8<-- [start:code]
"""Where the current goes at frequency: a busbar pair from 1 kHz to 10 MHz.

A DC-link busbar is two flat conductors carrying equal and opposite current. At low frequency the
current spreads evenly; at high frequency it retreats to the surface of each bar (skin effect) and
crowds onto the FACING edges, where the return is closest and the loop encloses least flux (proximity
effect). The resistance climbs while the inductance falls and then flattens.

Nothing is imposed: no skin-depth formula, no assumed profile. The bars are cut into filaments across
their width, each free to carry what it likes, and the redistribution is what the circuit solves for.
That is also the limit: each filament carries one current, so the skin effect WITHIN a filament is not
represented (each bar is one cell thick, where ``jno.peec`` takes the exact surface impedance).
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
CU, mm = 5.8e7, 1e-3
LB, WB, TB, GAP = 60 * mm, 6 * mm, 1 * mm, 2 * mm  # length, bar width, thickness, gap between the bars
cells = (1 * mm, 0.25 * mm, TB)  # one cell through the thickness; the resolution goes across the width

# a coplanar go/return pair, shorted at the far end
go = jno.shape.box(0, 0, 0, LB, WB, TB, size=cells).attach(sigma=CU).name("go")
ret = jno.shape.box(0, WB + GAP, 0, LB, 2 * WB + GAP, TB, size=cells).attach(sigma=CU).name("return")
link = jno.shape.box(LB - 2 * mm, 0, 0, LB, 2 * WB + GAP, TB, size=cells).attach(sigma=CU).name("link")
d = (go + ret + link).domain()

i, v = d.peec_symbols()
pad = lambda tag, where: v(*d.variable(tag, where=where, split=True, sample=(4, None)))
A = pad("A", lambda x, y, z: (x < 1.1 * mm) & (y < WB))
B = pad("B", lambda x, y, z: (x < 1.1 * mm) & (y > WB + GAP))

freqs = np.logspace(3, 7, 81)  # 20 per decade
sol = jno.peec([A - B - 1.0], freq=freqs).solve()  # one volt across the pads, every frequency in one solve

R, L = np.real(np.asarray(sol.R)), np.real(np.asarray(sol.L))
delta = 1 / np.sqrt(np.pi * freqs * CU * 4e-7 * np.pi)  # skin depth
print(f"{np.asarray(sol.i).shape[-1]} elements, {len(freqs)} frequencies, one solve")
for f, r, ind, dl in zip(freqs[::20], R[::20], L[::20], delta[::20]):
    print(f"{f:8.0e} Hz  R = {r * 1e6:9.1f} uOhm  L = {ind * 1e9:7.3f} nH  skin depth {dl * 1e3:6.3f} mm")
print(
    f"R rises {R[-1] / R[0]:.0f}x while L falls {100 * (1 - L[-1] / L[0]):.1f} % ({100 * (1 - L[-1] / L[-21]):.1f} % in the last decade)"
)

assert np.all(np.diff(R) > 0), "resistance rises monotonically as the current crowds"
assert np.all(np.diff(L) < 0), "and inductance falls monotonically as the loop tightens"
assert L[-1] / L[0] > 0.5 and L[-1] / L[-21] > 0.98, "the inductance flattens: under 2 % in the last decade"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/busbar_frequency.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 solved filament currents, as the solution exports them
        meshes = [meshio.read(sol.export_vtk(f"{tmp}/{j}.vtk", freq_index=j)) for j in range(len(freqs))]
    np.savez_compressed(
        Path(out) / "busbar_frequency.npz",
        nodes=meshes[0].points,
        bars=meshes[0].cells_dict["line"],
        density=np.stack([m.cell_data["current_density"][0] for m in meshes]).astype(np.float32),
        freq=freqs,
        impedance=np.asarray(sol.Z),
        R=R,
        L=L,
        geometry=np.array([LB, WB, GAP, TB]),
    )
