# --8<-- [start:code]
"""Full-waveform inversion: the wave speed from a seismogram, through a second-order solve.

u_tt = c² Δu,   u = 0 on the boundary,   u(0) = sin(πx) sin(πy),   u_t(0) = 0
"""

import os
from pathlib import Path

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

import jno

jax.config.update("jax_enable_x64", True)  # second-order soft modes need float64
run = jno.setup(__file__)
π = jno.np.pi
c2_true, c2_guess = 2.0, 1.0  # the speed² to recover, and a deliberately wrong start

d = jno.shape.rect(0, 0, 1, 1, size=0.05).domain(time=(0.0, 1.5, 60))
x, y, t = d.variable("interior", split=True)
b = d.variable("boundary", split=True)
x0, y0, t0 = d.variable("initial", split=True)
u = d.unknown()
v = u.test()
ub, vb = u.bind(x=x, y=y, t=t), v.bind(x=x, y=y, t=t)
grad = lambda w: jno.np.jacobian(w, [x, y])

c2 = jno.np.parameter((1,), name="c2")
fem = jno.fem(
    [
        ub.tt * vb + c2 * jno.np.inner(grad(u), grad(v)),
        u(*b) - 0.0,
        u(x0, y0) - jno.np.sin(π * x0) * jno.np.sin(π * y0),
        u.bind(x=x0, y=y0, t=t0).t - 0.0,
    ]
)
u_obs = np.asarray(fem.solve(c2=jnp.array([c2_true])))  # the seismogram: the wave at the true speed

c2.initialize(jax.nn.initializers.constant(c2_guess)).optimizer(optax.adam(5e-2))
crux = jno.core([(fem.solve() - u_obs).mse])
path = [c2_guess]
for _ in range(110):
    crux.solve(2, log=False)
    path.append(float(np.ravel(crux.eval([c2]))[0]))

rec = path[-1]
print(
    f"Recovered c² = {rec:.4f}  (truth {c2_true}),  started at {c2_guess}:  rel. error {abs(rec - c2_true) / c2_true:.2%}"
)
assert abs(rec - c2_true) / c2_true < 0.02
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    n, pts = fem.offsets[1], np.asarray(fem.points)
    rx = int(np.argmin(np.sum((pts - 0.5) ** 2, axis=1)))  # a receiver at the antinode (0.5, 0.5)
    runs = [np.asarray(fem.solve(c2=jnp.array([c])))[:, :n] for c in path]  # the wave at each recovered speed
    np.savez_compressed(
        Path(out) / "inverse_wave_speed_2d.npz",
        points=pts[:, :2],
        triangles=np.asarray(d.built_mesh.cells_dict["triangle"]),
        t=np.linspace(0.0, 1.5, 60),
        c2=path,
        c2_true=c2_true,
        field=np.array([r.astype(np.float32) for r in runs]),
        receiver=rx,
    )
