# --8<-- [start:code]
"""Recover a source amplitude through a finite-difference solve:  -Δu = s f,  u = 0 on the boundary."""

import os
from pathlib import Path

import jax
import numpy as np
import optax

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
π = jno.np.pi

d = jno.shape.rect(0, 0, 1, 1, size=0.025).domain()
x, y, _ = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
u = d.unknown()
ui = u.bind(x=x, y=y)
f = 2 * π**2 * jno.np.sin(π * x) * jno.np.sin(π * y)
forward = lambda s: jno.fdm([-ui.xx - ui.yy - s * f, u(xb, yb) - 0.0]).solve()

observed = np.asarray(forward(1.0)).reshape(-1)  # the data: the solve at the true amplitude

s = jno.np.parameter((1,), name="s").initialize(jax.nn.initializers.constant(2.5)).optimizer(optax.sgd(1.0))
crux = jno.core([(forward(s) - observed).mse])  # forward(s) is a trace node; the domain is inferred
path = [2.5]
for _ in range(150):
    crux.solve(1, log=False)
    path.append(float(np.ravel(crux.eval([s]))[0]))

rec = path[-1]
print(f"Recovered source amplitude s = {rec:.4f}  (true 1.0)")
assert abs(rec - 1.0) < 1e-2
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    points = np.asarray(d.mesh_connectivity["points"])[:, :2]
    triangles = np.asarray(d.mesh_connectivity["triangles"])
    f_nodes = np.asarray(2 * π**2 * np.sin(np.pi * points[:, 0]) * np.sin(np.pi * points[:, 1]))
    np.savez_compressed(Path(out) / "inverse_source_fdm.npz", points=points, triangles=triangles, f=f_nodes, s=path)
