# --8<-- [start:code]
"""An inverse problem: how much copper has the busbar lost?

Run the PEEC model backwards. A busbar has corroded over a known stretch; its terminal resistance is
the only measurement; the unknown is the fraction of copper gone. The measurement here is synthetic,
generated by the same model at a known answer, so the recovered number has something to be wrong against.
"""

import os
from pathlib import Path

import jax
import numpy as np
import optax

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
CU, mm, P = 5.8e7, 1e-3, 0.8e-3
LOSS_TRUE = 0.65  # the answer we pretend not to know: 65 % of the copper gone in the stretch


def busbar(sigma):
    """A 24 mm bar driven end to end at DC; its resistance is the measurement."""
    d = jno.shape.box(0, 0, 0, 24 * mm, 4 * mm, P, size=(P,) * 3).attach(sigma=sigma).name("bar").domain()
    i, v = d.peec_symbols()
    a, b = (d.variable(side, split=True, sample=(2, None))[:3] for side in ("left", "right"))  # the two end faces
    return jno.peec([v(*a) - v(*b) - 1.0], freq=0.0)


# which lattice cells lie in the corroded stretch (9 to 15 mm): geometry, decided once on the host
lat = busbar(CU).fil.lattice
n, lo, h = (np.asarray(lat[k]) for k in ("n", "lo", "d"))
cells = np.stack(np.meshgrid(*[np.arange(m) for m in n], indexing="ij"), -1).reshape(-1, 3)
x_c = lo[0] + (cells[:, 0] + 0.5) * h[0]
corroded = ((x_c > 9 * mm) & (x_c < 15 * mm)).astype(float)

R_healthy = float(np.real(busbar(CU).solve().R))
R_measured = float(np.real(busbar(CU * (1.0 - LOSS_TRUE * corroded)).solve().R))
print(
    f"{corroded.size} cells, {int(corroded.sum())} corroded:  R healthy {R_healthy * 1e6:.3f} uOhm,  measured {R_measured * 1e6:.3f} uOhm"
)

# the unknown: a parameter in the conductivity, so the solve's R is a trace node
loss = jno.np.parameter((1,), name="loss").initialize(jax.nn.initializers.constant(0.2)).optimizer(optax.adam(0.03))
residual = ((busbar(CU * (1.0 - loss * corroded)).solve().R - R_measured) / R_measured) ** 2
crux = jno.core([residual])
objective, path = [float(np.ravel(crux.eval([residual]))[0])], [0.2]
for _ in range(125):
    crux.solve(2, log=False)
    objective.append(float(np.ravel(crux.eval([residual]))[0]))
    path.append(float(np.ravel(crux.eval([loss]))[0]))

print(
    f"objective {objective[0]:.3e} -> {objective[-1]:.3e};  recovered {path[-1]:.4f}  (truth {LOSS_TRUE}, error {abs(path[-1] - LOSS_TRUE):.2e})"
)
assert abs(path[-1] - LOSS_TRUE) < 1e-3 and objective[-1] < 1e-9 * objective[0]

# the same machinery on a field: one density per cell, bounded by construction, as a design variable
theta = jno.np.parameter((int(corroded.size),), name="theta").initialize(jax.nn.initializers.constant(0.0))
theta.optimizer(optax.adam(0.2))
rho = 0.5 * (1.0 + jno.np.tanh(theta))  # in (0, 1): minimising R cannot beat solid copper
design = (busbar(CU * rho**3).solve().R * 1e6).name("R")
crux = jno.core([design])
R_start = float(np.ravel(crux.eval([design]))[0])
crux.solve(40, log=False)
R_end = float(np.ravel(crux.eval([design]))[0])
print(f"{corroded.size}-cell density design: R {R_start:.3f} -> {R_end:.3f} uOhm  (solid copper {R_healthy * 1e6:.3f})")
assert R_healthy * 1e6 - 1e-6 < R_end < R_start
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "inverse_corrosion.npz",
        x=x_c.reshape(tuple(n))[:, 0, 0] / mm,
        corroded=corroded.reshape(tuple(n))[:, 0, 0],
        path=path,
        truth=LOSS_TRUE,
        width=float(h[0] / mm),
    )
