import os
from pathlib import Path

# --8<-- [start:code]
r"""h, r and p adaptivity on one L-shape problem: same coarse mesh, same reference, same energy functional."""

import jax
import numpy as np

import jno

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)]  # re-entrant corner at (0.5, 0.5)
CORNER, BUMP = (
    (0.5, 0.5),
    (0.74, 0.22, 0.17, 60.0),
)  # the bump: cx, cy, R, amplitude, compactly supported in the lower-right arm
H, MARGIN = 0.075, 0.04  # the common coarse mesh; the margin keeps relocated vertices off the boundary
LU = jno.solve.lu()  # sparse-direct for every solve: the reference reaches ~12k DOFs


def source(x, y, xp):  # a C^3 bump (1 - s)^4, s = |x - c|^2 / R^2
    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 movable(x, y):  # interior vertices: off the outer box and the two notch edges
    in_arm = ~((x > 0.5) & (y > 0.5))
    off_box = (x > MARGIN) & (x < 1 - MARGIN) & (y > MARGIN) & (y < 1 - MARGIN)
    off_notch = ~(((np.abs(x - 0.5) < MARGIN) & (y > 0.5 - MARGIN)) | ((np.abs(y - 0.5) < MARGIN) & (x > 0.5 - MARGIN)))
    return in_arm & off_box & off_notch


def build(size, space="Lagrange", relocate=False):
    d = jno.shape.polygon(L_SHAPE, size=size).domain()
    if relocate:  # .trainable() on a coordinate makes the mesh vertices a design variable
        xm, ym, _ = d.variable("mov", where=movable, split=True)
        xm.trainable(name="ix"), ym.trainable(name="iy")
    u = d.unknown.scalar(space=space)  # space="cover": a p-enriched field
    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]))  # -lap u = f, u = 0 on the boundary
    ui = u.bind(x=x, y=y)
    return d, jno.fem([stiff - source(x, y, jno.np) * v, u(*boundary) - 0.0]), stiff, jno.np.sqrt(ui.x**2 + ui.y**2)


def energy(fem, stiff, sol):  # E = 1/2 int |grad u_h|^2 = 1/2 u . (A u), read off the form: the same rule for every space
    return 0.5 * float(np.dot(np.asarray(sol).reshape(-1), np.asarray(fem.eval(stiff, sol)).reshape(-1)))


def active_dofs(d, fem):  # an unenriched cover node has its slots pinned: the padded size would hide the effect of p
    return int(fem.dofs) - len({int(i) for i, _ in getattr(d, "_fem_native_dirichlet_pairs", None) or []})


def mesh_of(d):
    return np.asarray(d.mesh.points)[:, :2], np.asarray(d.mesh.cells_dict["triangle"])


def min_angle(pts, cells):  # smallest angle in degrees: the quality that relocation can quietly destroy
    a, b, c = (np.linalg.norm(pts[cells[:, i]] - pts[cells[:, j]], axis=1) for i, j in ((1, 0), (2, 1), (0, 2)))
    cos = np.stack(
        [
            (b * b + c * c - a * a) / (2 * b * c),
            (a * a + c * c - b * b) / (2 * a * c),
            (a * a + b * b - c * c) / (2 * a * b),
        ]
    )
    return float(np.degrees(np.arccos(np.clip(cos, -1, 1))).min())


# the reference must out-resolve every run: fully enriched (third order) at h = 0.015, whose drift from 0.020 is 4.8e-06
d_ref, fem_ref, stiff_ref, _ = build(0.015, space="cover")
E_REF = energy(fem_ref, stiff_ref, LU(fem_ref.A, fem_ref.b))

d0, fem0, stiff0, _ = build(H)  # the coarse start
E0, n0 = energy(fem0, stiff0, LU(fem0.A, fem0.b)), active_dofs(d0, fem0)
pts0, tris0 = mesh_of(d0)

d_h, fem_h, stiff_h, _ = build(H)  # h: add elements, solve -> ZZ estimate -> Dorfler mark -> local remesh
fem_h.solve(adapt=jno.solve.remesh(theta=0.6, max_iters=4, refine_factor=1.7), linear=LU)
E_h, n_h = energy(fem_h, stiff_h, LU(fem_h.A, fem_h.b)), active_dofs(d_h, fem_h)
pts_h, tris_h = mesh_of(d_h)

# r: relocate a fixed node set down a mesh functional, through the differentiable solve (the default
# objective equidistributes arclength, which targets resolution and not this error)
d_r, fem_r, stiff_r, _ = build(H, relocate=True)
pts_r0 = mesh_of(d_r)[0].copy()
sol_r = np.asarray(fem_r.solve(adapt=jno.solve.relocate(max_iters=30, lr=5e-4), linear=LU)).reshape(-1)
E_r, n_r = energy(fem_r, stiff_r, sol_r), active_dofs(d_r, fem_r)
pts_r, tris_r = mesh_of(d_r)

d_p, fem_p, stiff_p, grad_p = build(
    H, space="cover"
)  # p: raise the order on the same mesh, where the covers are switched on
fem_p.solve(
    adapt=jno.solve.enrich(criterion=grad_p, theta=0.8, max_iters=5), linear=LU
)  # returns the vertex view: re-solve on the final space
E_p, n_p = energy(fem_p, stiff_p, LU(fem_p.A, fem_p.b)), active_dofs(d_p, fem_p)
mask_p, pts_p = np.asarray(d_p._fem_enriched_nodes, dtype=bool), mesh_of(d_p)[0]

# hp: refine the mesh, then enrich on it (a fresh enrich starts from plain P1, so the active count goes down at that call)
d_hp, fem_hp, stiff_hp, grad_hp = build(H, space="cover")
fem_hp.solve(adapt=jno.solve.remesh(theta=0.6, max_iters=3, refine_factor=1.7), linear=LU)
fem_hp.solve(adapt=jno.solve.enrich(criterion=grad_hp, theta=0.8, max_iters=4), linear=LU)
E_hp, n_hp = energy(fem_hp, stiff_hp, LU(fem_hp.A, fem_hp.b)), active_dofs(d_hp, fem_hp)
mask_hp = np.asarray(d_hp._fem_enriched_nodes, dtype=bool)

err = lambda E: E_REF - E  # the energy rises toward the truth, so the error E_ref - E is non-negative
print(f"E_ref = {E_REF:.6f}  (cover, {active_dofs(d_ref, fem_ref)} dofs)")
print(f"  coarse start : {err(E0):.3e}  ({n0} dofs)")
print(f"  h            : {err(E_h):.3e}  ({n_h} dofs)  {err(E0) / err(E_h):5.1f}x lower")
print(f"  r            : {err(E_r):.3e}  ({n_r} dofs, +0)  {err(E0) / err(E_r):5.1f}x")
print(f"  p            : {err(E_p):.3e}  ({n_p} dofs, {mask_p.mean():.0%} enriched)  {err(E0) / err(E_p):5.1f}x lower")
print(f"  h then p     : {err(E_hp):.3e}  ({n_hp} dofs, {mask_hp.mean():.0%} enriched)  {err(E0) / err(E_hp):5.1f}x lower")

# where did each method spend its DOFs: at the corner, in the bump, elsewhere
near = lambda p, c, rad: np.hypot(p[:, 0] - c[0], p[:, 1] - c[1]) < rad
corner_p, bump_p = near(pts_p, CORNER, 0.22), near(pts_p, BUMP[:2], BUMP[2])
cent = pts_h[tris_h].mean(axis=1)
e1, e2 = pts_h[tris_h[:, 1]] - pts_h[tris_h[:, 0]], pts_h[tris_h[:, 2]] - pts_h[tris_h[:, 0]]
size_h = np.sqrt(0.5 * np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0]))
corner_h, bump_h = near(cent, CORNER, 0.22), near(cent, BUMP[:2], BUMP[2])
print(
    f"p put its covers:    corner {mask_p[corner_p].mean():4.0%} | bump {mask_p[bump_p].mean():4.0%} | elsewhere {mask_p[~(corner_p | bump_p)].mean():4.0%}"
)
print(
    f"h put its elements:  corner {size_h[corner_h].mean():.4f} | bump {size_h[bump_h].mean():.4f} | elsewhere {size_h[~(corner_h | bump_h)].mean():.4f}  (mean cell size)"
)
print(f"smallest angle: start {min_angle(pts0, tris0):.1f} deg -> after relocation {min_angle(pts_r, tris_r):.1f} deg")

assert err(E0) > 0 and err(E_p) > 0  # the reference bounds every run
assert err(E_h) < 0.25 * err(E0) and err(E_p) < err(E_h) and err(E_hp) < err(E_p) and 0.0 < mask_p.mean() < 1.0
assert min_angle(pts_r, tris_r) > 0.6 * min_angle(pts0, tris0)  # relocation does not wreck the mesh
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    from jno.utils.solver.fem_soft_cover import cover_dof_index

    ref_pts, ref_cells = mesh_of(d_ref)
    ref_u = np.asarray(LU(fem_ref.A, fem_ref.b)).reshape(-1)[
        cover_dof_index(len(ref_pts), 2)[:, 0] - 1
    ]  # the vertex values
    h_seq = [(hh["points"], hh["cells"]) for hh in fem_h.adapt_history] + [(pts_h, tris_h)]
    np.savez_compressed(
        Path(out) / "adaptive_l_shape.npz",
        start_points=pts0,
        start_cells=tris0,
        h_points=np.concatenate([p for p, _ in h_seq]),
        h_cells=np.concatenate([c for _, c in h_seq]),
        h_n_points=[len(p) for p, _ in h_seq],
        h_n_cells=[len(c) for _, c in h_seq],
        r_points=np.stack([pts_r0] + [hh["points"] for hh in fem_r.adapt_history] + [pts_r]),
        r_cells=tris_r,
        p_points=pts_p,
        p_cells=mesh_of(d_p)[1],
        p_masks=np.stack([np.asarray(hh["enriched"], dtype=bool) for hh in fem_p.adapt_history] + [mask_p]),
        ref_points=ref_pts,
        ref_cells=ref_cells,
        ref_u=ref_u,
        corner=CORNER,
        bump=BUMP,
    )
