import os
from pathlib import Path

from scipy.spatial import cKDTree

# --8<-- [start:code]
"""Inflating a thick rubber balloon through the pressure maximum, checked against the exact Neo-Hookean sphere."""

import jax
import numpy as np
from scipy.integrate import quad

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
A, B, h = 1.0, 1.3, 0.05  # inner and outer radius of the unloaded wall, mesh size
# shear and bulk modulus: the pressure unit is mu; kappa/mu = 100 keeps the rubber incompressible to about 1 %
mu, kappa = 1.0, 100.0

# the meridian quarter (r >= 0, z >= 0) of the wall; revolved about the axis it is a hemisphere
wall = (
    jno.Path(A, 0)
    .line_to(B, 0, name="equator")
    .arc_to(0, B, through=(B / 2**0.5, B / 2**0.5), name="outer")
    .line_to(0, A, name="axis")
    .arc_to(A, 0, through=(A / 2**0.5, A / 2**0.5), name="inner")
    .face(size=h)
)
d = wall.domain()
r, z, _ = d.variable("interior", split=True)
inner, axis, equator = (d.variable(name, split=True) for name in ("inner", "axis", "equator"))

u = d.unknown.vector(2, order=2)  # (u_r, u_z)
v = u.test()
ub, vb = u.bind(x=r, y=z), v.bind(x=r, y=z)
S = jno.np.stack


def grad3(w):  # the gradient of a body of revolution in (r, z, theta): the hoop entry is w_r / r
    zero = 0.0 * w[0].x
    return S([S([w[0].x, w[0].y, zero], -1), S([w[1].x, w[1].y, zero], -1), S([zero, zero, w[0] / r], -1)], -2)


F, dF = jno.np.identity(3) + grad3(ub), grad3(vb)
J = (F[..., 0, 0] * F[..., 1, 1] - F[..., 0, 1] * F[..., 1, 0]) * F[..., 2, 2]  # det F of the block form
psi = mu / 2 * (J ** (-2 / 3) * jno.np.sum(F * F, axis=(-2, -1)) - 3)  # Neo-Hookean, isochoric part
vary = lambda W: jno.np.sum(jno.np.diff(W, F) * dF, axis=(-2, -1))  # first variation of W along v
p_vol = kappa * (jno.np.cellwise(J) - 1)  # the pressure of the nearly incompressible rubber: a mean over each cell
mech = (vary(psi) + p_vol * jno.np.cellwise(vary(J))) * 2 * np.pi * r  # the ring measure 2 pi r

# the inner wall is moved radially by g (a runtime parameter): the pressure is then a reaction, not a load
g = jno.np.parameter((1,), name="g")
rho = jno.np.sqrt(inner[0] ** 2 + inner[1] ** 2)
fem = jno.fem([mech, u(*axis)[0] - 0.0, u(*equator)[1] - 0.0, u(*inner) - (g * inner[0] / rho, g * inner[1] / rho)])
steps = np.linspace(0.0, 0.7, 281)  # the inner radius A + g runs from 1 to 1.7 A, past the pressure maximum
family = jno.solve.continuation(keep="all", g=steps)  # each solve starts from the previous one
sol = np.asarray(
    fem.solve(continuation=family, nonlinear=jno.solve.newton(line_search=True, direct=True), linear=jno.solve.lu())
)

# the pressure is the reaction at the inner wall: p dV = (weak-form rows of the inner nodes) . du with dV = 2 pi a^2 da
P = np.asarray(fem.points)
rows = fem.region_dofs("inner", component=0) // 2  # the inner nodes (the solution is stored node by node: u_r, u_z)
e_r = P[rows] / np.hypot(*P[rows].T)[:, None]
a = A + steps  # the inner radius
pressure = np.array([(np.asarray(fem.eval(mech, s)).reshape(-1, 2)[rows] * e_r).sum() for s in sol]) / (
    2 * np.pi * a**2 * mu
)


# reference (scipy): the exact incompressible Neo-Hookean sphere. With R^3 = r^3 - a^3 + A^3 and lambda = r / R,
# p / mu = 2 int_a^b (lambda^2 - lambda^-4) dr / r, with b^3 = a^3 + B^3 - A^3
def exact(a):
    b = (a**3 + B**3 - A**3) ** (1 / 3)
    lam = lambda s: s / (s**3 - a**3 + A**3) ** (1 / 3)
    return 2 * quad(lambda s: (lam(s) ** 2 - lam(s) ** -4) / s, a, b)[0]


a_fine = np.linspace(A, a[-1], 2001)
p_fine = np.array([exact(s) for s in a_fine])
k = pressure.argmax()
# the maximum of the computed curve, from a parabola through its top
c = np.polyfit(a[k - 2 : k + 3], pressure[k - 2 : k + 3], 2)
peak_fe, peak_exact = -c[1] / (2 * c[0]), a_fine[p_fine.argmax()]
error = np.abs(pressure - np.array([exact(s) for s in a])).max() / p_fine.max()

# the wall's volume, from the radius of the outer surface and of the inner one
U = sol.reshape(len(sol), -1, 2)
outer = np.where(np.abs(np.hypot(*P.T) - B) < 0.01)[0]
b_fe = np.hypot(*(P[outer] + U[:, outer]).transpose(2, 0, 1)).mean(1)
dV = (b_fe**3 - a**3) / (B**3 - A**3) - 1
print(
    f"{len(P)} nodes, {len(d.mesh.cells_dict['triangle'])} triangles; {len(steps)} steps of the inner radius up to {a[-1]:.1f} A"
)
print(f"peak p/mu: computed {pressure.max():.4f} at a/A = {peak_fe:.3f}; exact {p_fine.max():.4f} at {peak_exact:.3f}")
print(
    f"largest pressure error over the curve {100 * error:.2f} % of the peak; wall volume change at most {100 * np.abs(dV).max():.2f} %"
)
# exact sphere; the tolerances are set from the run on the page
assert error < 0.02 and abs(peak_fe - peak_exact) < 0.02 and np.abs(dV).max() < 0.015
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    X, tree = np.asarray(d.built_mesh.points)[:, :2], cKDTree(P)
    np.savez_compressed(
        Path(out) / "inflating_balloon.npz",
        points=X,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        displacement=U[:, tree.query(X)[1]],
        inner_stretch=a / A,
        pressure=pressure,
        exact_stretch=a_fine / A,
        exact_pressure=p_fine,
    )
