"""Draw the worked adjoint examples and verify their gradients.

Run from the course root after activating env. No notebook is executed.
Figures are SVG with a fixed background for light and dark site themes.
"""
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
from matplotlib.patches import Circle, FancyArrowPatch, FancyBboxPatch
import numpy as np
from scipy.integrate import quad
from scipy.sparse import coo_matrix, diags
from scipy.sparse.linalg import spsolve


OUT = Path(__file__).resolve().parents[1]
BG, FG, MUTED = "#101318", "#edf0f5", "#b7c1cf"
ORANGE, PURPLE, GREEN, PINK = "#f39a53", "#b29aff", "#79d7ad", "#ee91b1"
plt.rcParams.update({
    "font.family": "DejaVu Sans", "font.size": 12,
    "figure.facecolor": BG, "axes.facecolor": BG, "savefig.facecolor": BG,
    "text.color": FG, "axes.labelcolor": FG, "xtick.color": MUTED,
    "ytick.color": MUTED, "axes.edgecolor": "#596272",
    "axes.spines.top": False, "axes.spines.right": False,
    "svg.fonttype": "none", "svg.hashsalt": "adjoint-worked-examples",
})
REPORT = []


def record(name, value):
    REPORT.append(f"{name} = {value}")


def save(fig, name):
    fig.savefig(OUT / f"{name}.svg", bbox_inches="tight", pad_inches=.25,
                metadata={"Date": None})
    # PNG previews are generated locally for inspection, outside the repository.
    fig.savefig(Path("/tmp") / f"{name}.png", dpi=140, bbox_inches="tight", pad_inches=.25)
    plt.close(fig)


def arrow(ax, start, end, color=MUTED, width=1.8):
    ax.add_patch(FancyArrowPatch(start, end, arrowstyle="-|>",
                                mutation_scale=15, lw=width, color=color))


def box(ax, x, y, w, h, title, detail, color):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02",
                               facecolor="#1c222c", edgecolor=color, lw=1.5))
    ax.text(x+w/2, y+h*.68, title, ha="center", va="center", color=color, fontsize=13)
    ax.text(x+w/2, y+h*.28, detail, ha="center", va="center", fontsize=11)


def fd(fun, x, eps=1e-5):
    eye = np.eye(len(x))
    return np.array([(fun(x+eps*v)-fun(x-eps*v))/(2*eps) for v in eye])


def room_matrix(k):
    k1, k2, k3 = k
    return np.array([[k1+k2, -k2], [-k2, k2+k3]])


K_DERIVATIVES = np.array([[[1., 0.], [0., 0.]],
                          [[1., -1.], [-1., 1.]],
                          [[0., 0.], [0., 1.]]])
k = np.ones(3)
K = room_matrix(k)
u = np.linalg.solve(K, [30., 0.])
e = np.array([0., u[1]-15.])
adj = np.linalg.solve(K.T, e)
g = -np.einsum("i,pij,j->p", adj, K_DERIVATIVES, u)
du = np.column_stack([np.linalg.solve(K, -Ki@u) for Ki in K_DERIVATIVES])
room_loss = lambda p: .5*(np.linalg.solve(room_matrix(p), [30., 0.])[1]-15.)**2
np.testing.assert_allclose(u, [20, 10])
np.testing.assert_allclose(adj, [-5/3, -10/3])
np.testing.assert_allclose(g, [100/3, -50/3, 100/3])
np.testing.assert_allclose(e@du, g)
np.testing.assert_allclose(fd(room_loss, k), g, rtol=1e-7)
k_new = k-.005*g
np.testing.assert_allclose(k_new, [5/6, 13/12, 5/6])
np.testing.assert_allclose(np.linalg.solve(room_matrix(k_new), [30., 0.]), [23, 13])
np.testing.assert_allclose(room_loss(k_new), 2.)
for name, value in [("room state", u), ("room direct state sensitivities", du),
                    ("room adjoint", adj), ("room gradient", g),
                    ("room finite difference", fd(room_loss, k)),
                    ("room initial loss", room_loss(k)), ("room updated conductances", k_new),
                    ("room updated state", np.linalg.solve(room_matrix(k_new), [30., 0.])),
                    ("room updated loss", room_loss(k_new))]:
    record(name, value)


# The original constrained-distance example remains as a short geometric introduction.
geometry = np.linalg.solve([[2., 0., -1.], [0., 2., -1.], [1., 1., 0.]], [0., 0., 1.])
np.testing.assert_allclose(geometry, [.5, .5, 1.])
record("geometry minimizer and multiplier", geometry)
record("geometry objective", geometry[:2]@geometry[:2])
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), gridspec_kw={"width_ratios": [1, 1.35]})
ax = axes[0]
t = np.linspace(0, 2*np.pi, 500)
for radius in [.45, np.sqrt(.5), .95]:
    ax.plot(radius*np.cos(t), radius*np.sin(t), color=ORANGE,
            lw=2 if np.isclose(radius, np.sqrt(.5)) else 1, alpha=.9)
x = np.linspace(-.2, 1.2, 100)
ax.plot(x, 1-x, color=PURPLE, lw=2)
ax.scatter([.5], [.5], color=GREEN, s=65, zorder=4)
arrow(ax, (0, 0), (.5, .5), GREEN)
ax.text(.58, .58, r"$(1/2,1/2)$", fontsize=12)
ax.set(xlim=(-.2, 1.2), ylim=(-.2, 1.2), xlabel="$x$", ylabel="$y$")
ax.set_aspect("equal")
ax.set_title("Minimum on the constraint", loc="left", pad=15)
ax = axes[1]
ax.axis("off")
ax.text(.04, .84, r"$f=x^2+y^2,\qquad g=x+y-1=0$", fontsize=17)
ax.text(.04, .59, r"$\nabla f=(2x,2y),\qquad \nabla g=(1,1)$", fontsize=17)
ax.text(.04, .34, r"$\nabla f=\lambda\nabla g$", fontsize=20, color=GREEN)
ax.text(.04, .10, "At the constrained minimum, the gradients are parallel.", fontsize=12)
fig.tight_layout(w_pad=3)
save(fig, "adjoint-constraint-geometry")


# Forward state, adjoint state, and signed conductance derivatives on the same graph.
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
for ax in axes:
    ax.set(xlim=(-.45, 3.45), ylim=(-1, 1.8))
    ax.axis("off")
for ax, title, values, color in zip(axes[:2],
        ["Forward temperatures", "Adjoint values"],
        [["0", "20", "10", "0"], ["0", r"$-5/3$", r"$-10/3$", "0"]],
        [ORANGE, PURPLE]):
    ax.set_title(title, fontsize=18, pad=12, color=color)
    for j in range(3):
        ax.plot([j+.16, j+.84], [0, 0], color=MUTED, lw=2)
        ax.text(j+.5, -.4, f"$k_{j+1}$", ha="center")
    for j, value in enumerate(values):
        ax.add_patch(Circle((j, 0), .17, facecolor=color if j in [1, 2] else BG,
                            edgecolor=color, lw=2))
        ax.text(j, .38, value, ha="center", color=color, fontsize=15)
        ax.text(j, -.78, ["Outside", "Room A", "Room B", "Outside"][j],
                ha="center", fontsize=10)
    j = 1 if ax is axes[0] else 2
    arrow(ax, (j, 1.15), (j, .65), color)
    ax.text(j, 1.35, "$Q=30$ W" if j == 1 else "$e_B=-5$", ha="center", fontsize=13)
axes[0].text(1.5, -1, "Temperature above the outdoor value, in K", ha="center", fontsize=11)
axes[1].text(1.5, -1, r"$K^T\lambda=(0,-5)^T$", ha="center", fontsize=13)
ax = axes[2]
ax.set_title("Loss sensitivities", color=GREEN, fontsize=18, pad=12)
for y, label, formula, color in [(1.12, "$k_1$", r"$-\lambda_Au_A=+100/3$", ORANGE),
        (.32, "$k_2$", r"$-(\lambda_A-\lambda_B)(u_A-u_B)=-50/3$", GREEN),
        (-.48, "$k_3$", r"$-\lambda_Bu_B=+100/3$", ORANGE)]:
    ax.text(-.3, y, label, fontsize=14, color=color)
    ax.text(.22, y, formula, fontsize=12, color=color)
ax.text(1.5, -1, r"Descent decreases $k_1,k_3$ and increases $k_2$", ha="center", fontsize=11)
fig.subplots_adjust(wspace=.2, bottom=.18, top=.82)
save(fig, "adjoint-room-network")


# Count linear systems, distinguishing their right-hand sides and contractions.
fig, axes = plt.subplots(2, 1, figsize=(13, 5))
for ax in axes:
    ax.set(xlim=(0, 13), ylim=(0, 2.1))
    ax.axis("off")
ax = axes[0]
ax.text(.1, 1.85, "Direct state sensitivities", color=ORANGE, fontsize=17)
box(ax, .15, .45, 2.5, .9, "Forward solve", "$Ku=q$", ORANGE)
box(ax, 3.6, .45, 4.5, .9, "$P$ sensitivity solves", r"$K u_{,i}=-K_i u$", ORANGE)
box(ax, 9.0, .45, 3.6, .9, "Scalar contractions", r"$g_i=e^T u_{,i}$", GREEN)
arrow(ax, (2.7, .9), (3.5, .9))
arrow(ax, (8.2, .9), (8.9, .9))
ax.text(5.85, .08, "One right-hand side for each parameter", ha="center", fontsize=11)
ax = axes[1]
ax.text(.1, 1.85, "Adjoint gradient of one scalar objective", color=PURPLE, fontsize=17)
box(ax, .15, .45, 2.5, .9, "Forward solve", "$Ku=q$", ORANGE)
box(ax, 3.6, .45, 4.5, .9, "One adjoint solve", r"$K^T\lambda=e$", PURPLE)
box(ax, 9.0, .45, 3.6, .9, "Parameter contractions", r"$g_i=-\lambda^T K_i u$", GREEN)
arrow(ax, (2.7, .9), (3.5, .9))
arrow(ax, (8.2, .9), (8.9, .9))
ax.text(10.8, .08, "Assembly still depends on the parameter count", ha="center", fontsize=10)
fig.tight_layout(h_pad=1)
save(fig, "adjoint-solve-comparison")


# Source identification on the two-interior-node rod.
b = np.array([3., 0.])
rod_u = np.linalg.solve(K, b)
rod_e = np.array([0., rod_u[1]-4.])
rod_adj = np.linalg.solve(K.T, rod_e)
rod_loss = lambda p: .5*(np.linalg.solve(K, p)[1]-4.)**2
np.testing.assert_allclose(rod_u, [2, 1])
np.testing.assert_allclose(rod_adj, [-1, -2])
np.testing.assert_allclose(fd(rod_loss, b), rod_adj, rtol=1e-7)
b_new = b-.5*rod_adj
np.testing.assert_allclose(np.linalg.solve(K, b_new), [8/3, 11/6])
np.testing.assert_allclose(rod_loss(b_new), 169/72)
for name, value in [("rod scaled source", b), ("rod state", rod_u),
                    ("rod source gradient", rod_adj), ("rod finite difference", fd(rod_loss, b)),
                    ("rod initial loss", rod_loss(b)), ("rod updated source", b_new),
                    ("rod updated state", np.linalg.solve(K, b_new)),
                    ("rod updated loss", rod_loss(b_new))]:
    record(name, value)
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
ax = axes[0]
ax.set(xlim=(-.15, 1.15), ylim=(-.85, 1.55))
ax.axis("off")
ax.set_title("Two interior source parameters", color=ORANGE, loc="left", pad=12)
ax.plot([0, 1], [0, 0], color=MUTED, lw=5)
for x, val, lab in [(0, "0", "$0$"), (1/3, "2", "$1/3$"),
                    (2/3, "1", "$2/3$"), (1, "0", "$1$")]:
    ax.scatter([x], [0], s=140, color=ORANGE, zorder=3)
    ax.text(x, -.28, lab, ha="center")
    ax.text(x, .25, "$u="+val+"$", ha="center", fontsize=12)
for x, val in [(1/3, "3"), (2/3, "0")]:
    arrow(ax, (x, 1.0), (x, .38), ORANGE)
    ax.text(x, 1.15, "$b="+val+"$", ha="center")
ax.text(2/3, -.7, "Sensor target 4; error −3", ha="center", fontsize=11)
ax = axes[1]
ax.bar([1, 2], rod_adj, color=PURPLE, width=.5)
ax.axhline(0, color=MUTED, lw=1)
for j, val in enumerate(rod_adj, 1):
    ax.text(j, val-.13, f"{val:.0f}", ha="center", va="top", fontsize=16)
ax.set(xticks=[1, 2], xticklabels=["Source at node 1", "Source at node 2"],
       ylim=(-2.6, .3), ylabel=r"$\partial J/\partial b_i=\lambda_i$")
ax.set_title("Loss decreases when either source increases", loc="left", color=PURPLE, pad=12, fontsize=13)
fig.tight_layout(w_pad=3)
save(fig, "adjoint-discrete-rod")


# Analytic full-field rod example and its functional gradient.
x = np.linspace(0, 1, 401)
state = x*(1-x)
target = 2*state
lam_fun = lambda z: z**3/6-z**4/12-z/12
lam = lam_fun(x)
loss_a = lambda a: (a-4)**2/240
np.testing.assert_allclose(quad(lambda z: .5*(z*(1-z))**2, 0, 1)[0], 1/60)
np.testing.assert_allclose(lam_fun(.5), -5/192)
np.testing.assert_allclose(quad(lam_fun, 0, 1)[0], -1/60)
np.testing.assert_allclose(fd(lambda a: loss_a(a[0]), np.array([2.])), [-1/60], rtol=1e-8)
record("continuous source initial loss", 1/60)
record("continuous midpoint source gradient", lam_fun(.5))
record("constant-source derivative by adjoint integration", quad(lam_fun, 0, 1)[0])
record("constant-source finite difference", fd(lambda a: loss_a(a[0]), np.array([2.])))
fig, axes = plt.subplots(1, 3, figsize=(14, 3.8))
axes[0].plot(x, target, color=MUTED, ls="--", label="Target")
axes[0].plot(x, state, color=ORANGE, lw=2.5, label="Current state")
axes[0].set_title("Forward state", loc="left", color=ORANGE, pad=12)
axes[0].legend(frameon=False, labelcolor=FG, fontsize=11)
axes[0].set_ylabel("Temperature")
axes[1].fill_between(x, state-target, 0, color=PURPLE, alpha=.3)
axes[1].plot(x, state-target, color=PURPLE, lw=2.5)
axes[1].set_title("Distributed error", loc="left", color=PURPLE, pad=12)
axes[1].set_ylabel(r"$u-u_{\mathrm{target}}$")
axes[2].fill_between(x, lam, 0, color=GREEN, alpha=.25)
axes[2].plot(x, lam, color=GREEN, lw=2.5)
axes[2].scatter([.5], [-5/192], color=GREEN, zorder=4)
axes[2].annotate(r"$\lambda(1/2)=-5/192$", (.5, -5/192), xytext=(.1, -.018), fontsize=11,
                 arrowprops={"arrowstyle": "-", "color": MUTED})
axes[2].set_title("Adjoint = source gradient", loc="left", color=GREEN, pad=12)
axes[2].set_ylabel(r"$\delta J/\delta s$")
for ax in axes:
    ax.set_xlabel("Position $x$")
    ax.axhline(0, color=MUTED, lw=.7)
    ax.set_xlim(0, 1)
fig.tight_layout(w_pad=2)
save(fig, "adjoint-continuous-rod")


# A conservative 2D diffusion discretization for the conductivity illustration.
# k is nodal; each edge uses the arithmetic mean of its endpoint coefficients.
# B contains oriented differences, including edges to zero Dirichlet boundaries.
n = 11
edges = []
for row in range(n):
    for col in range(n):
        i = row*n+col
        if col < n-1:
            edges.append((i, i+1))
        if row < n-1:
            edges.append((i, i+n))
        for boundary in (col == 0, col == n-1, row == 0, row == n-1):
            if boundary:
                edges.append((i, -1))
rows, cols, data = [], [], []
for edge, (i, j) in enumerate(edges):
    rows.append(edge)
    cols.append(i)
    data.append(1.)
    if j >= 0:
        rows.append(edge)
        cols.append(j)
        data.append(-1.)
B = coo_matrix((data, (rows, cols)), shape=(len(edges), n*n)).tocsr()


def plate_matrix(coeff):
    weights = np.array([.5*(coeff[i]+(coeff[j] if j >= 0 else 1.)) for i, j in edges])
    return B.T@diags(weights)@B


coeff = np.ones(n*n)
source, sensor = 8*n+2, 2*n+8
q = np.zeros(n*n)
q[source] = 30.
A = plate_matrix(coeff)
plate_u = spsolve(A, q)
observed = 2*plate_u[sensor]
error = np.zeros(n*n)
error[sensor] = plate_u[sensor]-observed
plate_lam = spsolve(A.T, error)
edge_gradient = -(B@plate_u)*(B@plate_lam)
plate_g = np.zeros(n*n)
for value, (i, j) in zip(edge_gradient, edges):
    plate_g[i] += .5*value
    if j >= 0:
        plate_g[j] += .5*value


def plate_loss(p):
    pred = spsolve(plate_matrix(p), q)[sensor]
    return .5*(pred-observed)**2


# Independent perturbations verify every plotted conductivity derivative.
plate_fd = fd(plate_loss, coeff)
np.testing.assert_allclose(plate_fd, plate_g, rtol=2e-6, atol=1e-10)
record("plate interior grid", f"{n} x {n}")
record("plate predicted and observed sensor values", [plate_u[sensor], observed])
record("plate conductivity gradient range", [plate_g.min(), plate_g.max()])
record("plate maximum gradient finite-difference error", np.max(np.abs(plate_fd-plate_g)))
record("plate forward residual norm", np.linalg.norm(A@plate_u-q))
record("plate adjoint residual norm", np.linalg.norm(A.T@plate_lam-error))
orange_map = LinearSegmentedColormap.from_list("heat", ["#17191c", "#a84721", ORANGE])
purple_map = LinearSegmentedColormap.from_list("adjoint", [PURPLE, "#6543b1", "#17191c"])
signed_map = LinearSegmentedColormap.from_list("signed", [PINK, "#17191c", GREEN])
fig, axes = plt.subplots(1, 3, figsize=(14, 4.8))
limit = np.max(np.abs(plate_g))
panels = [(plate_u, orange_map, None, "Forward field", "$u$", ORANGE),
          (plate_lam, purple_map, None, "Adjoint field", r"$\lambda$", PURPLE),
          (plate_g, signed_map, TwoSlopeNorm(vmin=-limit, vcenter=0, vmax=limit),
           "Conductivity sensitivity", r"$\partial J/\partial k_i$", GREEN)]
for ax, (field, cmap, norm, title, label, color) in zip(axes, panels):
    im = ax.imshow(field.reshape(n, n), origin="lower", cmap=cmap, norm=norm,
                   interpolation="nearest", extent=(0, 1, 0, 1))
    ax.set_title(title, color=color, fontsize=17, pad=16)
    ax.set(xticks=[], yticks=[])
    for tick in np.linspace(0, 1, n+1):
        ax.axhline(tick, color=FG, alpha=.16, lw=.6)
        ax.axvline(tick, color=FG, alpha=.16, lw=.6)
    cb = fig.colorbar(im, ax=ax, orientation="horizontal", fraction=.05, pad=.08)
    cb.set_label(label, fontsize=13)
    cb.ax.tick_params(labelsize=10)
for ax, index, label, color in [(axes[0], source, "Heat source", ORANGE),
                                 (axes[1], sensor, "Error at sensor", PURPLE)]:
    row, col = divmod(index, n)
    xy = ((col+.5)/n, (row+.5)/n)
    ax.scatter(*xy, facecolors="none", edgecolors=FG, s=150, linewidths=2)
    ax.text(.5, -.035, label, transform=ax.transAxes, ha="center", va="top", fontsize=11)
axes[2].text(.5, -.035, "Positive / negative derivative", transform=axes[2].transAxes,
             ha="center", va="top", fontsize=11)
fig.text(.5, .015, r"Conductivity gradient density $=-\nabla u\cdot\nabla\lambda$"
         r"     |     Source gradient density $=\lambda$", ha="center", fontsize=14)
fig.subplots_adjust(wspace=.28, bottom=.23, top=.85)
save(fig, "adjoint-conductivity-fields")

(OUT / "src" / "generate_adjoint_figures-report.txt").write_text("\n".join(REPORT)+"\n")
print("\n".join(REPORT))
