import os
from pathlib import Path

# --8<-- [start:code]
r"""Soft p-enrichment on the L-shape: the order distribution as a differentiable variable, against greedy marking."""

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

import jno
from jno.utils.solver.fem_soft_cover import (
    cover_dof_index,
    hierarchical_indicator,
    operator_diagonal,
    ritz_energy,
    soft_solve,
)

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L_SHAPE = [(0, 0), (1, 0), (1, 0.5), (0.5, 0.5), (0.5, 1), (0, 1)]
BUMP = (0.74, 0.22, 0.17, 60.0)  # cx, cy, R, amplitude
H, H_REF = 0.075, 0.015  # the coarse mesh and the fully enriched (third-order) reference, as in the adaptivity tutorial
STEPS, CHUNK, SIMP_P = 300, 5, 3.0  # projected-gradient steps per budget, snapshot every CHUNK steps
LU = jno.solve.lu()


def source(x, y, xp):
    cx, cy, R, A = BUMP
    s = ((x - cx) ** 2 + (y - cy) ** 2) / R**2
    return A * xp.where(s < 1.0, 1.0 - s, 0.0) ** 4


def build(size):  # -lap u = f on the L-shape, u = 0 on the boundary, one scalar space="cover" field
    d = jno.shape.polygon(L_SHAPE, size=size).domain()
    u = d.unknown.scalar(space="cover")
    v = u.test()
    x, y, _ = d.variable("interior", split=True)
    boundary = d.variable("boundary", split=True)
    stiff = jno.np.inner(jno.np.jacobian(u, [x, y]), jno.np.jacobian(v, [x, y]))
    return d, jno.fem([stiff - source(x, y, jno.np) * v, u(*boundary) - 0.0]), u.bind(x=x, y=y)


compiles = [0]  # XLA compilations, to compare the greedy loop with the whole soft optimisation
jax.monitoring.register_event_duration_secs_listener(
    lambda name, *_a, **_k: compiles.__setitem__(0, compiles[0] + ("backend_compile" in name))
)

d_ref, fem_ref, _ = build(H_REF)
A_ref, b_ref = fem_ref.operator
PI_REF = float(ritz_energy(A_ref, b_ref, LU(A_ref, b_ref)))

d0, fem0, _ = build(H)
A, b = fem0.operator
b = jnp.asarray(b).reshape(-1)
pts, tris = np.asarray(d0.mesh.points)[:, :2], np.asarray(d0.mesh.cells_dict["triangle"])
N = len(pts)
IDX = cover_dof_index(N, 2)
C = operator_diagonal(A, IDX)
pi = lambda w: ritz_energy(A, b, soft_solve(A, b, IDX, C, w))  # Pi(w) = 1/2 u.Au - b.u, 2 (Pi - Pi_exact) = |u - u_exact|^2
err = lambda w: float(pi(jnp.asarray(w, dtype=float))) - PI_REF  # energy error of the softly enriched solution
pinned = {int(i) for i, _ in d0._fem_native_dirichlet_pairs}
free_cover = np.array(
    [[int(k) not in pinned for k in row] for row in IDX]
)  # a boundary node's covers are partly pinned already
active_dofs = lambda mask: (
    sum(int(IDX[i, 0] - 1) not in pinned for i in range(N)) + int(free_cover[np.asarray(mask, bool)].sum())
)


def top_k(score, k):
    m = np.zeros(N, dtype=bool)
    m[np.argsort(-np.asarray(score))[:k]] = True
    return m


# the greedy loop: jno.solve.enrich, whose rounds fix the budgets every comparison uses
d_g, fem_g, ui_g = build(H)
c0 = compiles[0]
fem_g.solve(adapt=jno.solve.enrich(criterion=jno.np.sqrt(ui_g.x**2 + ui_g.y**2), theta=0.5, max_iters=6), linear=LU)
compiles_greedy = compiles[0] - c0
masks = [np.asarray(r["enriched"], bool) for r in fem_g.adapt_history] + [np.asarray(d_g._fem_enriched_nodes, bool)]
masks = [m for i, m in enumerate(masks) if m.sum() > 0 and (i == 0 or m.sum() != masks[i - 1].sum())]
budgets = [int(m.sum()) for m in masks]
A_m, b_m = fem_g.operator  # the loop leaves fem_g bound to its final mask: the hard-mask energy checks the soft one
E_hard, E_soft = float(ritz_energy(A, b, LU(A_m, b_m))) - PI_REF, err(masks[-1].astype(float))

# the AD indicator -dPi/dw at w = 0 against its closed form, sum r^2 / A_kk (Bank & Smith 1993)
g0 = np.asarray(jax.jit(jax.grad(pi))(jnp.zeros(N)))
h0 = np.asarray(hierarchical_indicator(A, b, IDX, C, soft_solve(A, b, IDX, C, jnp.zeros(N))))
live = np.abs(h0) > 1e-10 * np.abs(h0).max()


def project(v_, k):  # Euclidean projection onto {0 <= w <= 1, sum w = k}: bisection on the shift
    lo, hi = jnp.min(v_) - 1.0, jnp.max(v_)

    def body(_, lh):
        mid = 0.5 * (lh[0] + lh[1])
        up = jnp.sum(jnp.clip(v_ - mid, 0.0, 1.0)) > k
        return jnp.where(up, mid, lh[0]), jnp.where(up, lh[1], mid)

    lo, hi = jax.lax.fori_loop(0, 60, body, (lo, hi))
    return jnp.clip(v_ - 0.5 * (lo + hi), 0.0, 1.0)


def optimiser(p):  # CHUNK projected-gradient steps from step i0, the gate w -> w^p
    vg = jax.value_and_grad((lambda w: pi(w**p)) if p != 1.0 else pi)

    @jax.jit
    def chunk(w, k, i0):
        def step(i, w):
            g = vg(w)[1]
            return project(w - (0.3 * (1.0 - (i0 + i) / STEPS) + 0.01) * g / (jnp.max(jnp.abs(g)) + 1e-300), k)

        return jax.lax.fori_loop(0, CHUNK, step, w)

    def run(w, k, record=None):
        for i0 in range(0, STEPS, CHUNK):
            w = chunk(w, float(k), i0)
            if record is not None:
                record.append(np.asarray(w))
        return np.asarray(w)

    return run


opt_lin, opt_simp = optimiser(1.0), optimiser(SIMP_P)
c0, rows, frames = compiles[0], [], []
k_show = budgets[len(budgets) // 2]
for m_g, k in zip(masks, budgets):
    w0 = jnp.full(N, k / N)
    w_lin, w_simp = opt_lin(w0, k, frames if k == k_show else None), opt_simp(w0, k)
    rows.append(
        dict(
            k=k,
            dofs=active_dofs(top_k(w_lin, k)),
            greedy=err(m_g.astype(float)),
            ad=err(top_k(-g0, k).astype(float)),
            lin=err(top_k(w_lin, k).astype(float)),
            simp=err(top_k(w_simp, k).astype(float)),
        )
    )
rng = np.random.default_rng(0)
starts = [project(jnp.asarray(rng.random(N)), float(k_show)) for _ in range(3)]  # random starts at the middle budget
spread = {
    n: [err(top_k(opt(w, k_show), k_show).astype(float)) for w in starts]
    for n, opt in (("lin", opt_lin), ("SIMP", opt_simp))
}
compiles_soft = compiles[0] - c0

# uniform P1 on finer meshes at the same active DOFs: P1 is the cover space with every weight 0
p1 = []
for f in (1.0, 0.85, 0.75, 0.65, 0.55):
    d_f, fem_f, _ = build(H * f)
    A_f, b_f = fem_f.operator
    n_f, idx_f = len(np.asarray(d_f.mesh.points)), cover_dof_index(len(np.asarray(d_f.mesh.points)), 2)
    pin_f = {int(i) for i, _ in d_f._fem_native_dirichlet_pairs}
    sol = soft_solve(A_f, jnp.asarray(b_f).reshape(-1), idx_f, operator_diagonal(A_f, idx_f), jnp.zeros(n_f))
    p1.append(
        (sum(3 * i not in pin_f for i in range(n_f)), float(ritz_energy(A_f, jnp.asarray(b_f).reshape(-1), sol)) - PI_REF)
    )
p1_dofs, p1_err = (np.array(a) for a in zip(*sorted(p1)))
uniform = lambda t: float(np.exp(np.interp(np.log(t), np.log(p1_dofs), np.log(p1_err))))

print(
    f"L-shape, H={H}: {N} nodes, {A.shape[0]} padded DOFs; Pi_ref={PI_REF:.8f}; errors P1 {err(np.zeros(N)):.4e}, full cover {err(np.ones(N)):.4e}"
)
print(
    f"hard mask vs soft w in {{0,1}}: {E_hard:.6e} vs {E_soft:.6e}; AD gradient vs closed form: {np.max(np.abs(g0 - h0)[live] / np.abs(h0[live])):.1e}"
)
print(f"{'k':>4} {'DOFs':>5} {'greedy':>11} {'AD 1x':>11} {'opt lin':>11} {'opt SIMP':>11} {'uniform P1':>11}")
for r in rows:
    print(
        f"{r['k']:>4} {r['dofs']:>5} {r['greedy']:>11.4e} {r['ad']:>11.4e} {r['lin']:>11.4e} {r['simp']:>11.4e} {uniform(r['dofs']):>11.4e}"
    )
print(
    f"random starts at k={k_show}: opt lin {min(spread['lin']):.4e}..{max(spread['lin']):.4e}, "
    f"opt SIMP {min(spread['SIMP']):.4e}..{max(spread['SIMP']):.4e}; "
    f"XLA compilations: greedy loop {compiles_greedy}, soft optimisation {compiles_soft}"
)

assert abs(E_hard - E_soft) <= 1e-5 * abs(E_hard)  # soft weights in {0, 1} reproduce the hard mask
assert np.max(np.abs(g0 - h0)[live] / np.abs(h0[live])) < 1e-3  # the AD indicator is its closed form
assert all(
    r["lin"] <= r["greedy"] and r["lin"] < uniform(r["dofs"]) for r in rows
)  # the optimum beats greedy marking and uniform P1
assert compiles_soft < compiles_greedy  # and compiles fewer programs
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "soft_enrichment_l_shape.npz",
        points=pts,
        cells=tris,
        weights=np.stack(frames),
        steps=np.arange(CHUNK, STEPS + 1, CHUNK),
        budget=k_show,
        greedy_mask=masks[budgets.index(k_show)],
        final_mask=top_k(frames[-1], k_show),
        errors=np.array([[r["k"], r["greedy"], r["lin"], r["dofs"]] for r in rows]),
    )
