import os
from pathlib import Path

# --8<-- [start:code]
"""2-D Poisson equation, -Δu = f on the unit square with u = 0 on the boundary, four ways.

Manufactured solution u*(x, y) = sin(2πx) sin(3πy), so f = 13π² u*. Finite elements solve the weak form;
finite differences, finite volumes and the spectral method read one and the same strong-form term list.
Each method runs at two resolutions: the mesh methods converge at second order, the spectral method
geometrically.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)
KX, KY = 2, 3  # half-waves of the solution along x and y
exact = lambda x, y: np.sin(KX * np.pi * x) * np.sin(KY * np.pi * y)
source = lambda x, y: (KX**2 + KY**2) * np.pi**2 * jno.np.sin(KX * np.pi * x) * jno.np.sin(KY * np.pi * y)


def square(**kw):
    """The unit square, its interior and boundary points."""
    d = jno.shape.rect(0, 0, 1, 1, **kw).domain()
    return d, d.variable("interior", split=True)[:2], d.variable("boundary", split=True)[:2]


# --8<-- [start:fem]
def fem(h):
    d, (x, y), b = square(size=h)
    u = d.unknown()
    v = u.test()
    grad = lambda w: jno.np.jacobian(w, [x, y])
    prob = jno.fem([jno.np.inner(grad(u), grad(v)) - source(x, y) * v, u(*b) - 0.0])  # the weak form
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.points)[:, :2]


# --8<-- [end:fem]


# --8<-- [start:strong]
def strong(method, d, x, y, b, u):
    """FDM, FVM and spectral: the same strong form, -Δu = f, with u = 0 on the boundary."""
    ui = u.bind(x=x, y=y)
    return method([-(ui.xx + ui.yy) - source(x, y), u(*b) - 0.0])


def fdm(h):
    d, (x, y), b = square(size=h)
    sol = strong(jno.fdm, d, x, y, b, d.unknown()).solve()  # values at the mesh nodes
    return d, np.asarray(sol).ravel(), np.asarray(d.mesh_connectivity["points"])[:, :2]


def fvm(h):
    d, (x, y), b = square(size=h)
    prob = strong(jno.fvm, d, x, y, b, d.unknown())  # one value per triangle, its cell average
    return d, np.asarray(prob.solve()).ravel(), np.asarray(prob.centroids)[:, :2]


def spectral(n):
    d = jno.shape.rect(0, 0, 1, 1).domain()  # geometry only: no mesh
    u = d.unknown(space="spectral", order=(n, n))  # Chebyshev on both axes: the walls are not periodic
    (x, y), b = d.variable("interior", split=True)[:2], d.variable("boundary", split=True)[:2]
    sol = strong(jno.spectral, d, x, y, b, u).solve()  # values at the Chebyshev-Gauss-Lobatto nodes
    return u, np.asarray(sol).ravel(), np.asarray(u.basis.nodes).reshape(-1, 2)


# --8<-- [end:strong]


rel_l2 = lambda sol, p: float(np.linalg.norm(sol - exact(*p.T)) / np.linalg.norm(exact(*p.T)))
runs = {"FEM": (fem, (0.1, 0.05)), "FDM": (fdm, (0.1, 0.05)), "FVM": (fvm, (0.1, 0.05)), "spectral": (spectral, (12, 24))}
results = {}
for name, (solve, sizes) in runs.items():
    out_ = [solve(s) for s in sizes]
    errs = [rel_l2(sol, p) for _, sol, p in out_]
    results[name] = (out_[-1], errs, [len(sol) for _, sol, _ in out_])
    print(f"{name:8s}: unknowns {' -> '.join(str(len(s)) for _, s, _ in out_)}   rel_L2 {errs[0]:.2e} -> {errs[1]:.2e}")
for name in ("FEM", "FDM", "FVM"):
    errs = results[name][1]
    assert errs[1] < 3e-2 and errs[0] / errs[1] > 3.0, name  # second order: half the mesh size, a quarter the error
assert results["spectral"][1][1] < 1e-9  # geometric: 24 nodes per axis reach round-off scale
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/poisson_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    (d_fem, s_fem, p_fem), (d_fdm, s_fdm, p_fdm), (d_fvm, s_fvm, _), (u_sp, s_sp, p_sp) = (
        results[k][0] for k in ("FEM", "FDM", "FVM", "spectral")
    )
    xq = np.linspace(0, 1, 241)
    X, Y = np.meshgrid(xq, xq, indexing="ij")
    fine = np.asarray(u_sp.basis(s_sp, X.ravel(), Y.ravel())).reshape(X.shape)  # the spectral interpolant
    tri = lambda d: np.asarray(d.mesh_connectivity["triangles"])
    np.savez_compressed(
        Path(out) / "poisson_2d.npz",
        fem_points=p_fem, fem_tri=tri(d_fem), fem_u=s_fem,
        fdm_points=p_fdm, fdm_u=s_fdm,
        fvm_points=np.asarray(d_fvm.mesh_connectivity["points"])[:, :2], fvm_tri=tri(d_fvm), fvm_u=s_fvm,
        sp_nodes=p_sp, sp_fine=fine, sp_grid=xq,
        errors=np.array([results[k][1] for k in runs]), unknowns=np.array([results[k][2] for k in runs]),
    )  # fmt: skip
