import os
from pathlib import Path

# --8<-- [start:code]
"""A radar-absorbing coating cell on a metal ground plane, with ``jno.Rcwa``: the Salisbury screen, and a patterned sheet.

Wavelengths are in units of the design wavelength (lambda0 = 1) and impedances in units of the vacuum impedance
(eta0 = 1). A resistive sheet of sheet resistance rho sits a spacer d above the ground. The coating is
periodic, so ``jno.Rcwa`` solves it exactly in the Fourier basis; its reflectance, as a function of wavelength
and angle, is what the design minimises. E is along the surface (s polarisation), the case of the 2-D radar tutorial.
"""

import jax
import jax.numpy as jnp
import numpy as np
import optax

import jno

jax.config.update("jax_enable_x64", True)  # a metal half-space (eps = -1e6) and thin sheets need float64
run = jno.setup(__file__)
INF, K0 = np.inf, 2 * np.pi  # lambda0 = 1
PERIOD = 0.3  # the cell is smaller than half the shortest wavelength: no order but the 0th propagates, at any angle
T_SHEET, GROUND = 1e-3, -1e6 + 0j  # sheet thickness; the ground plane is a metal half-space, surface impedance 1e-3
assert 1 / 1.4 / PERIOD > 2  # grating equation: the +-1 orders are evanescent at every angle, for every f <= 1.4
Y_FORM = lambda rho, d: 1 / rho + 1j / np.tan(K0 * d)  # admittance of the sheet in parallel with the shorted spacer


def sheet(rho, f):
    """Permittivity of a conductive film of thickness T_SHEET whose sheet resistance is rho at every frequency."""
    return 1.0 + 1j / (rho * K0 * f * T_SHEET)


def cell(layers, period=PERIOD, orders=9):
    """One coating cell as a ``jno.Rcwa`` problem: layers = [(thickness, eps), ...] from air down to the metal."""
    return jno.Rcwa([(INF, 1.0), *layers, (INF, GROUND)], period=(period, period), orders=orders, wavelength=1.0,
                    assume_periodic=True, polarization="y")  # fmt: skip


def solve(rc, layers, f, theta):
    """The solution of a cell with the given layers (between air and metal) at frequency f and angle theta."""
    return rc.solve(wavelength=1 / f, k_in=(K0 * f * np.sin(theta), 0.0), layers=[(INF, 1.0), *layers, (INF, GROUND)])


reflectance = lambda *args: solve(*args).efficiency("R")
coefficient = lambda *args: solve(*args).jones("R")[1, 1]  # complex, at the top surface of the coating; normal incidence


# --- exact checks: a lossy slab against the transfer matrix, at oblique incidence, both polarisations ---
def transfer_matrix(layers, theta, pol):  # reference: Fresnel coefficients stacked from the bottom up
    kz = [K0 * np.sqrt(e - np.sin(theta) ** 2 + 0j) for _, e in layers]
    fresnel = lambda j, k: (kz[j] - kz[k]) / (kz[j] + kz[k]) if pol == "s" else (
        (layers[k][1] * kz[j] - layers[j][1] * kz[k]) / (layers[k][1] * kz[j] + layers[j][1] * kz[k]))  # fmt: skip
    g = fresnel(len(layers) - 2, len(layers) - 1)
    for j in range(len(layers) - 3, -1, -1):
        ph, r = np.exp(2j * kz[j + 1] * layers[j + 1][0]), fresnel(j, j + 1)
        g = (r + g * ph) / (1 + r * g * ph)
    return g


slab = [(INF, 1.0), (0.3, 4.0 + 0.5j), (0.2, 2.0), (INF, -30 + 5j)]
errs = []
for pol in "sp":  # s: E along y (the plane of incidence is x-z), p: E along x
    rc = jno.Rcwa(
        slab,
        period=(PERIOD, PERIOD),
        orders=9,
        wavelength=1.0,
        assume_periodic=True,
        polarization="y" if pol == "s" else "x",
    )
    for th in np.deg2rad([0.0, 20.0, 40.0, 60.0]):
        r_rcwa = float(rc.solve(k_in=(K0 * np.sin(th), 0.0)).efficiency("R"))
        errs.append(abs(r_rcwa - abs(transfer_matrix(slab, th, pol)) ** 2))
print(f"lossy slab, RCWA against the transfer matrix, s and p at 0..60 deg: largest |dR| = {max(errs):.1e}")
assert max(errs) < 1e-8

# --- the Salisbury screen: rho = 1 (the sheet equals the vacuum impedance) a quarter wave above the ground ---
rc = cell([(T_SHEET, 1.0), (0.25, 1.0)])
f_scan = np.linspace(0.5, 1.5, 101)
R_sal = np.array([float(reflectance(rc, [(T_SHEET, sheet(1.0, f)), (0.25, 1.0)], f, 0.0)) for f in f_scan])
print(
    f"Salisbury screen: R at the quarter-wave frequency = {R_sal[50]:.1e}; R <= 0.1 for f in "
    f"[{f_scan[R_sal <= 0.1].min():.2f}, {f_scan[R_sal <= 0.1].max():.2f}]"
)
assert R_sal[50] < 1e-4  # the exact zero (the sheet and the ground are not ideal: 2e-5 left)

# --- the coating as a surface impedance: Z_s = (1 + r)/(1 - r), against the sheet in parallel with the spacer ---
cells = [(1.0, 0.25), (0.5, 0.20), (2.0, 0.15), (0.7, 0.32)]  # (rho, d) of a few coatings
z_err = []
for rho, d in cells:
    r = coefficient(rc, [(T_SHEET, sheet(rho, 1.0)), (d, 1.0)], 1.0, 0.0)
    y_rcwa = (1 - r) / (1 + r)
    z_err.append(abs(y_rcwa - Y_FORM(rho, d)) / abs(Y_FORM(rho, d)))
    print(f"  rho = {rho:.1f}, d = {d:.2f}: Y_s RCWA {y_rcwa.real:+.3f}{y_rcwa.imag:+.3f}i, "
          f"sheet || spacer {Y_FORM(rho, d).real:+.3f}{Y_FORM(rho, d).imag:+.3f}i")  # fmt: skip
assert max(z_err) < 3e-2  # the thin film is not the ideal sheet: the error is of the order of T_SHEET

# --- the same cell at oblique incidence against the surface-impedance condition of the 2-D tutorial ---
leontovich = lambda y, th: (np.cos(th) - y) / (np.cos(th) + y)  # reflection coefficient of  dE/dn = -i k y E
deg = np.arange(0, 61, 15)
cell_vs_angle = [
    [float(reflectance(rc, [(T_SHEET, sheet(rho, 1.0)), (d, 1.0)], 1.0, np.deg2rad(a))) for a in deg]
    for rho, d in cells[:2]
]
leont_vs_angle = [[abs(leontovich(Y_FORM(rho, d), np.deg2rad(a))) ** 2 for a in deg] for rho, d in cells[:2]]
print(
    "R of the first cell at 0..60 deg:  cell",
    np.round(cell_vs_angle[0], 3),
    " surface impedance",
    np.round(leont_vs_angle[0], 3),
)
# --- the patterned sheet: ink density on a 32 x 32 grid, optimised for the band 0.7..1.3 and 0, 30, 50 degrees ---
# --- the patterned sheet: ink density on a 32 x 32 grid, optimised for the band 0.8..1.2 and 0, 30, 45 degrees ---
NG, RHO_INK, D, EPS_S = 32, 0.25, 0.2, 1.5  # grid; solid-ink sheet resistance; spacer; foam
BAND, ANGLES = np.linspace(0.7, 1.3, 5), np.deg2rad([0.0, 30.0, 50.0])
pat = cell([(T_SHEET, jnp.ones((NG, NG), complex)), (D, EPS_S)], PERIOD, orders=49)


def band_reflectance(density, freqs=BAND, angles=ANGLES):
    """Mean reflectance of the ink pattern ``density`` (NG x NG, 0..1) over the band and the angles."""
    layers = lambda f: [(T_SHEET, 1.0 + (sheet(RHO_INK, f) - 1.0) * density), (D, EPS_S)]
    return jnp.mean(jnp.stack([reflectance(pat, layers(f), f, th) for f in freqs for th in angles]))


mirror = lambda q: (lambda top: jnp.concatenate([top[:, ::-1], top], axis=1))(jnp.concatenate([q[::-1], q]))  # 4 mirrors
dummy = jno.domain.from_array({"_": np.zeros((1, 1))})  # jno.core wants a domain; the physics is in jno.Rcwa
# baseline: the best uniform sheet at the same spacer (ink fraction by scan), what a Salisbury screen can do here
scan = np.linspace(0.05, 1.0, 20)
R_uniform = [float(band_reflectance(jnp.full((NG, NG), u))) for u in scan]
u_best = scan[int(np.argmin(R_uniform))]

# the design starts from that sheet (plus a little noise) and may take any ink density from 0 to 1 in each pixel
noise = 0.05 * np.random.default_rng(0).standard_normal((NG // 2, NG // 2))
start = lambda key, shape, dtype=None: jnp.asarray(np.log(u_best / (1 - u_best)) + noise)
logits = (
    jno.np.parameter((NG // 2, NG // 2), name="ink")
    .initialize(start)
    .optimizer(optax.adam(optax.cosine_decay_schedule(0.12, 200)))
)
logits.dtype(jnp.float64)
density_of = lambda z: mirror(jax.nn.sigmoid(z))
objective = jno.fn(lambda z: band_reflectance(density_of(z)), [logits]).name("R")
crux = jno.core([objective], domain=dummy)
frames = []
for _ in range(40):  # 200 Adam steps, a snapshot every 5
    crux.solve(5, log=False)
    frames.append(np.asarray(density_of(jnp.asarray(crux.eval([logits])))))
density = frames[-1]
R_pat = float(band_reflectance(jnp.asarray(density)))
print(f"mean reflectance over the band and angles: uniform sheet {min(R_uniform):.4f} (ink fraction {u_best:.2f}), "
      f"patterned {R_pat:.4f}")  # fmt: skip
assert R_pat < min(R_uniform)  # the pattern buys something over any uniform sheet at this spacer
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/radar_absorber_cell.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    f_map, th_map = np.linspace(0.6, 1.4, 41), np.deg2rad(np.arange(0, 61, 5))
    maps = {}
    for name, dens in (("uniform", np.full((NG, NG), u_best)), ("patterned", density)):
        lay = lambda f, dens=dens: [(T_SHEET, 1.0 + (sheet(RHO_INK, f) - 1.0) * dens), (D, EPS_S)]
        maps[name] = np.array([[float(reflectance(pat, lay(f), f, th)) for f in f_map] for th in th_map])
    np.savez_compressed(
        Path(out) / "radar_absorber_cell.npz",
        f_scan=f_scan, R_salisbury=R_sal, f_map=f_map, theta_map=np.rad2deg(th_map),
        R_uniform=maps["uniform"], R_patterned=maps["patterned"], density=density, frames=np.array(frames),
        u_best=u_best, period=PERIOD, spacer=D, angles_deg=deg, cell_vs_angle=cell_vs_angle, leontovich_vs_angle=leont_vs_angle,
    )  # fmt: skip
