import os
from pathlib import Path

# --8<-- [start:code]
"""Bayesian inverse PINN in 2-D: a source field from a few noisy sensors, with a posterior that shows where it knows.

-Δu = f on the unit square, u = 0 on the boundary, f = Σ c_k φ_k a sum of 16 Gaussian bumps. One network learns the
16 solutions u_k of -Δu_k = φ_k from the physics alone; then it is frozen and NUTS samples the coefficients c from
14 noisy sensors that all sit in the left half of the square.
"""

import blackjax
import foundax
import jax
import numpy as np
import optax
from scipy.interpolate import LinearNDInterpolator

import jno

jax.config.update("jax_enable_x64", True)  # the sampler and the surrogate's last digits want float64
run = jno.setup(__file__)
exp = jno.np.exp
G, A, W, SIGMA, M, EPOCHS = 4, 20.0, 0.12, 0.01, 14, 3000  # bumps per side, height, width, sensor noise, sensors
K = G * G
centres = [((i + 0.5) / G, (j + 0.5) / G) for i in range(G) for j in range(G)]
bump = lambda k, px, py: A * exp(-((px - centres[k][0]) ** 2 + (py - centres[k][1]) ** 2) / (2 * W**2))
rng = np.random.default_rng(1)

# --8<-- [start:truth]
c_true = rng.normal(size=K)  # one draw from the prior N(0, 1)
sensors = np.column_stack([rng.uniform(0.08, 0.5, M), rng.uniform(0.08, 0.92, M)])  # left half only

ref = jno.shape.rect(0, 0, 1, 1, size=0.02).domain()  # the truth, by finite elements on its own mesh
xr, yr, _ = ref.variable("interior", split=True)
xb, yb, _ = ref.variable("boundary", split=True)
w = ref.unknown()
v = w.test()
grad = lambda q: jno.np.jacobian(q, [xr, yr])
f_true = sum(float(c) * bump(k, xr, yr) for k, c in enumerate(c_true))
u_fem = np.asarray(jno.fem([jno.np.inner(grad(w), grad(v)) - f_true * v, w(xb, yb) - 0.0], quad_degree=4).solve()).ravel()
nodes = np.asarray(ref.context["interior"]).reshape(-1, 2)
u_obs = LinearNDInterpolator(nodes, u_fem)(sensors) + SIGMA * rng.normal(size=M)  # noisy readings at the sensors
# --8<-- [end:truth]

# --8<-- [start:surrogate]
d = jno.domain.from_array({"interior": nodes, "sensors": sensors})  # collocation points and sensor positions
x, y = d.variable("interior", split=True)[:2]
xs, ys = d.variable("sensors", split=True)[:2]
bubble = lambda a, b: a * (1 - a) * b * (1 - b)  # hard u = 0 on the boundary

net = jno.nn(foundax.mlp(2, output_dim=K, hidden_dims=64, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(2e-3, 800, 0.6, end_value=1e-5)))
residuals = []
for k in range(K):  # output k solves -Δu_k = φ_k
    uk = (net(x, y)[..., k] * bubble(x, y)).scalar.bind(x=x, y=y)
    residuals.append((-(uk.xx + uk.yy) - bump(k, x, y)).mse)
jno.core(residuals, domain=d).solve(EPOCHS)
# --8<-- [end:surrogate]

# --8<-- [start:sample]
net.freeze()  # a fixed forward map: u(x, y) = Σ c_k u_k(x, y)
c = jno.np.parameter((K,), name="c").initialize(jax.nn.initializers.constant(0.0))
c.bayesian(
    blackjax.nuts,
    step_size=0.1,
    warmup=300,
    keep=500,
    num_chains=4,
    init_jitter=0.5,
    prior=jno.bayesian.priors.gaussian(sigma=1.0),  # c_k ~ N(0, 1)
    likelihood_scale=M / 2,  # the mean over M sensors becomes the sum of a Gaussian log-likelihood
)
reading = jno.np.sum(net(xs, ys) * bubble(xs, ys) * c, axis=-1, keepdims=True)
crux = jno.core([((reading - d.variable("u_obs", u_obs.reshape(1, -1, 1))) / SIGMA).mse], domain=d)
crux.solve(800)
# --8<-- [end:sample]

# --8<-- [start:check]
grid = jno.domain.from_array({"interior": nodes})  # the posterior on the reference mesh
xg, yg = grid.variable("interior", split=True)[:2]
u_expr = jno.np.sum(net(xg, yg) * bubble(xg, yg) * c, axis=-1, keepdims=True)  # u = Σ c_k u_k
f_expr = jno.np.sum(
    jno.np.concat([bump(k, xg, yg) for k in range(K)], axis=-1) * c, axis=-1, keepdims=True
)  # f = Σ c_k φ_k
u_post, f_post = (np.asarray(v).reshape(-1, len(nodes)) for v in crux.eval([u_expr, f_expr], domain=grid))  # every sample
u_mean, u_std, f_mean, f_std = u_post.mean(0), u_post.std(0), f_post.mean(0), f_post.std(0)
# --8<-- [end:check]

# --8<-- [start:reference]
# Reference checks, plain numpy: coverage of the truth, and the closed-form Gaussian posterior of this linear problem.
f_ref = np.asarray(crux.eval([sum(float(ck) * bump(k, xg, yg) for k, ck in enumerate(c_true))], domain=grid)[0]).ravel()
covered = lambda truth, mean, std: float(np.mean(np.abs(truth - mean) < 1.96 * std))  # share inside the 95 % band
cov_u, cov_f = covered(u_fem, u_mean, u_std), covered(f_ref, f_mean, f_std)
left = nodes[:, 0] < 0.5
print(f"u: mean std {u_std[left].mean():.4f} in the left half, {u_std[~left].mean():.4f} in the right half")
print(f"95 % band holds the truth at {cov_u:.1%} of the nodes for u, {cov_f:.1%} for f")

basis = np.asarray(crux.eval([net(xs, ys) * bubble(xs, ys)])[0]).reshape(M, K)  # u_k at the sensors
cov_c = np.linalg.inv(basis.T @ basis / SIGMA**2 + np.eye(K))  # N(0, I) prior, Gaussian noise
mean_c = cov_c @ basis.T @ u_obs / SIGMA**2
chain = np.asarray(c.posterior_samples).reshape(-1, K)
d_mean, d_std = np.abs(chain.mean(0) - mean_c).max(), chain.std(0).mean() / np.sqrt(np.diag(cov_c)).mean()
print(f"NUTS vs closed form: max |Δmean| = {d_mean:.3f}, std ratio {d_std:.3f}")

assert 0.85 <= cov_u <= 1.0 and 0.85 <= cov_f <= 1.0, (cov_u, cov_f)  # a calibrated 95 % band
assert u_std[~left].mean() > 3 * u_std[left].mean()  # the spread is large away from the sensors
assert d_mean < 0.15 and abs(d_std - 1) < 0.1  # the sampler found the right posterior
# --8<-- [end:reference]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/bayesian_poisson_source_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "bayesian_poisson_source_2d.npz",
        nodes=nodes,
        sensors=sensors,
        u_true=u_fem,
        u_mean=u_mean,
        u_std=u_std,
        f_true=f_ref,
        f_mean=f_mean,
        f_std=f_std,
        coverage=[cov_u, cov_f],
    )
