import os
from pathlib import Path

# --8<-- [start:code]
"""Mixed boundary conditions by finite differences: Dirichlet, Neumann and Robin at once.

Steady conduction on the unit square, -Δu = -2, with the manufactured field u*(x, y) = y²:

    bottom (y = 0)  Dirichlet  u = 0
    top    (y = 1)  Robin      ∂u/∂n + (u - 3) = 0     (u* gives 2 + (1 - 3) = 0)
    left, right     Neumann    ∂u/∂n = 0               (insulated)

A flux condition is written with the edge's own tags: bind the field to the edge and take its normal
derivative ``ur.d(nr)``. The term is that boundary node's equation; there are no BC objects.
"""

import jax

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

import numpy as np

import jno

run = jno.setup(__file__)
d = jno.shape.rect(0, 0, 1, 1, size=0.025).domain()
x, y, _ = d.variable("interior", split=True)
xb, yb, _ = d.variable("bottom", split=True)
xl, yl, _ = d.variable("left", split=True)
xr, yr, _ = d.variable("right", split=True)
xt, yt, _ = d.variable("top", split=True)
nl, nr, nt = (d.variable(side, normals=True) for side in ("left", "right", "top"))  # outward normals

u = d.unknown()
ui, ul, ur, ut = u.bind(x=x, y=y), u.bind(x=xl, y=yl), u.bind(x=xr, y=yr), u.bind(x=xt, y=yt)

sol = np.asarray(
    jno.fdm(
        [
            -ui.xx - ui.yy + 2.0,  # -Δu = -2
            u(xb, yb) - 0.0,  # Dirichlet, bottom
            ul.d(nl) - 0.0,  # Neumann, left
            ur.d(nr) - 0.0,  # Neumann, right
            ut.d(nt) + 1.0 * (ut - 3.0),  # Robin, top: convection to u_inf = 3 with alpha = 1
        ]
    ).solve()
).ravel()

p = np.asarray(d.mesh_connectivity["points"])[:, :2]
exact = p[:, 1] ** 2
rel_l2 = float(np.linalg.norm(sol - exact) / np.linalg.norm(exact))
print(f"Mixed Dirichlet+Neumann+Robin via jno.fdm: nodes={p.shape[0]}  rel_L2={rel_l2:.3e}")
assert rel_l2 < 5e-2, f"relative L2 error too large: {rel_l2:.3e}"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/mixed_bc_fdm.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    tri = np.asarray(d.mesh_connectivity["triangles"])
    np.savez_compressed(Path(out) / "mixed_bc_fdm.npz", points=p, triangles=tri, u=sol)
