import os
from pathlib import Path

# --8<-- [start:code]
"""Bayesian inverse PINN: the reaction coefficient k in  -λ u'' + k u = f  on (0, 1), u(0) = u(1) = 0, from noisy sensors.

Phase 1 fits a neural surrogate of u to the data; phase 2 freezes it, so NUTS samples a fixed-target posterior of
the single scalar k through the physics residual. SIGMA_PHYS budgets for the surrogate's model error as well as the
sensor noise: that is what keeps the truth inside the credible interval.
"""

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

import jno

run = jno.setup(__file__)
π = jno.np.pi
LAMBDA, K_TRUE, SIGMA_U, SIGMA_PHYS = 1.0, 2.0, 0.02, 0.05  # known diffusivity, the truth, sensor noise, physics scale

d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.02).domain()
x, _ = d.variable("interior")
x_np = np.asarray(d.context["interior"]).reshape(-1, 1)
u_obs = jnp.asarray(np.sin(π * x_np) + SIGMA_U * np.random.default_rng(0).normal(size=x_np.shape))  # u* = sin(πx)
f = (LAMBDA * π**2 + K_TRUE) * jno.np.sin(π * x)  # the known forcing that makes u* the solution

# Phase 1: a surrogate fitted to the noisy sensors.
u_net = jno.nn(foundax.mlp(1, output_dim=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
u_net.optimizer(optax.adam(2e-3))
u_fit = u_net(x) * x * (1 - x)  # hard u(0) = u(1) = 0
fit = jno.core([(u_fit - u_obs).mse])
fit.solve(5000)

u_hat, u_star = fit.eval([u_fit, jno.np.sin(π * x)])
fit_err = float(jnp.linalg.norm(u_hat - u_star) / jnp.linalg.norm(u_star))
print(f"surrogate rel-L2 vs sin(πx): {fit_err:.3e}")

# Phase 2: freeze the surrogate, then NUTS on k.
u_net.freeze()
k = jno.np.parameter((1,), name="k").initialize(jax.nn.initializers.constant(1.0))
k.bayesian(blackjax.nuts, step_size=1e-2, warmup=300, keep=600, num_chains=4, init_jitter=0.5)

u = (u_net(x) * x * (1 - x)).scalar.bind(x=x)
jno.core([((-LAMBDA * u.xx + k * u - f) / SIGMA_PHYS).mse]).solve(900)  # -λ u'' + k u - f = 0

chain = k.posterior_samples  # (num_chains, keep, 1)
mean, std = float(jnp.mean(chain)), float(jnp.std(chain))
lo, hi = (float(q) for q in jnp.quantile(chain.reshape(-1), jnp.array([0.05, 0.95])))
rhat, ess = (float(m(chain).reshape(-1)[0]) for m in (jno.bayesian.rhat, jno.bayesian.ess))
print(
    f"k = {mean:.4f} ± {std:.4f}   90% CI = [{lo:.4f}, {hi:.4f}]   truth = {K_TRUE}   R-hat = {rhat:.4f}   ESS = {ess:.0f}"
)

assert fit_err < 0.03, f"surrogate fit poor: rel-L2 = {fit_err:.3e}"
assert abs(mean - K_TRUE) / K_TRUE < 0.08, f"posterior-mean k off: {mean:.4f}"
assert rhat < 1.1, f"chains not mixed: R-hat = {rhat:.4f}"
assert ess > 100, f"effective sample size too low: {ess:.0f}"
assert lo <= K_TRUE <= hi, f"truth {K_TRUE} outside the 90% CI [{lo:.4f}, {hi:.4f}]"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/bayesian_inverse_coefficient.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "bayesian_inverse_coefficient.npz",
        x=x_np.ravel(),
        u_obs=np.asarray(u_obs).ravel(),
        u_hat=np.asarray(u_hat).ravel(),
        chain=np.asarray(chain)[..., 0],
        k_true=K_TRUE,
        ci=[lo, hi],
    )
