# --8<-- [start:code]
"""Recover a hidden diffusivity field k(x) from measured responses:  -div(k grad u) = f.

The hidden field writes "jNO" in a material 2.5 times as conductive as the plate around it. Three
experiments see it from different sides: a heat source in the plate, and a flow driven left to right
and bottom to top by the boundary values. A total-variation prior keeps the edges sharp.
"""

import os
from pathlib import Path

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

import jno

run = jno.setup(__file__)

d = jno.shape.rect(0, 0, 2, 1, size=0.0125).domain()
x, y, _ = d.variable("interior", split=True)
b = d.variable("boundary", split=True)
xb, yb, _ = b
u = d.unknown()
v = u.test()
grad = lambda w: jno.np.jacobian(w, [x, y])
dot = jno.np.inner


def forward(k, f, g):
    return jno.fem([k * dot(grad(u), grad(v)) - f * v, u(*b) - g], quad_degree=3).solve(linear=jno.solve.lu())


def letters(x, y, s=0.01):
    """1 on the plate and 2.5 inside the strokes of "jNO", the edges smoothed over a width s."""
    box = lambda cx, cy, hx, hy: jnp.maximum(abs(x - cx) - hx, abs(y - cy) - hy)  # signed distances
    disc = lambda cx, cy, r: jnp.hypot(x - cx, y - cy) - r
    band = lambda x0, y0, x1, y1, w: abs((x - x0) * (y1 - y0) - (y - y0) * (x1 - x0)) / jnp.hypot(x1 - x0, y1 - y0) - w
    j = [box(0.49, 0.45, 0.045, 0.2), box(0.40, 0.25, 0.13, 0.045), box(0.30, 0.31, 0.045, 0.1), disc(0.49, 0.76, 0.055)]
    n = [box(0.80, 0.5, 0.045, 0.27), box(1.20, 0.5, 0.045, 0.27)]
    n += [jnp.maximum(band(0.80, 0.77, 1.20, 0.23, 0.045), box(1.0, 0.5, 0.2, 0.27))]  # the diagonal
    o = [abs(jnp.hypot((x - 1.58) / 0.22, (y - 0.5) / 0.27) - 1) * 0.22 - 0.045]
    return 1.0 + 1.5 * jax.nn.sigmoid(-jnp.min(jnp.stack(j + n + o), axis=0) / s)


experiments = [(10.0, 0.0), (0.0, xb / 2), (0.0, yb)]  # (source f, boundary value g)
k_true = jno.np.parameter(v).initialize(letters).freeze()
data = [(f, g, jnp.asarray(forward(k_true, f, g))) for f, g in experiments]  # the measurements

k = jno.np.parameter(v, name="k").initialize(jax.nn.initializers.constant(1.0)).optimizer(optax.adam(2e-2))
misfit = sum(((forward(k, f, g) - u_obs) / jnp.std(u_obs)).mse for f, g, u_obs in data)
crux = jno.core([misfit, 2e-4 * k.regularize("tv", eps=1e-3).mean])
path = [np.ravel(crux.eval([k]))]
for _ in range(150):  # 1500 Adam steps, with a snapshot every 10 for the animation
    crux.solve(10, log=False)
    path.append(np.ravel(crux.eval([k])))

nodes = np.asarray(d.built_mesh.points)[:, :2]
true, rec = np.asarray(letters(*nodes.T)), path[-1]
rel = float(np.linalg.norm(rec - true) / np.linalg.norm(true))
print(f"{len(nodes)} nodes, 3 experiments:  k(x) rel_L2 = {rel:.3e},  range {rec.min():.2f} .. {rec.max():.2f}")
assert rel < 0.1
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    cells = np.asarray(d.built_mesh.cells_dict["triangle"])
    np.savez_compressed(Path(out) / "inverse_diffusivity_field.npz", points=nodes, triangles=cells, true=true, path=path)
