import os
import time
from pathlib import Path

# --8<-- [start:code]
"""Pulsatile blood flow through an artery with a saccular aneurysm: stabilised equal-order P1/P1 Navier-Stokes
marched with BDF2, a Womersley inflow, zero-traction outflow, no-slip walls.

    u_t + (u.grad)u - nu lap u + grad p = 0,   div u = 0,   mu = 3.5 mPa s, rho = 1060 kg/m^3

Checked against the exact Womersley solution in the straight inlet section, mass conservation and the
periodicity of the last cardiac cycle; the wall shear stress on the aneurysm dome is read off the velocity.
"""

from functools import reduce

import jax
import numpy as np
from scipy.special import factorial, jv

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)

# artery (mm), blood (kg/m^3, Pa s), heart (Hz, mm/s), mesh sizes (mm) and time steps
R, L_IN, L_OUT = 2.0, 12.0, 10.0  # parent artery: radius, straight length before and after the sac
R_NECK, R_SAC, X_SAC = 1.5, 2.6, 4.4  # neck radius; sac radius and the distance of its centre from the axis
RHO, MU = 1060.0, 3.5e-3
NU = MU / RHO * 1e6  # kinematic viscosity in mm^2/s
F_HEART, UMEAN = 1.25, 250.0  # 75 beats per minute; velocity averaged over the section and the cycle
OMEGA, PERIOD = 2 * np.pi * F_HEART, 1 / F_HEART
ALPHA = R * np.sqrt(OMEGA / NU)  # Womersley number
HARMONICS = {1: -0.55 - 0.95j, 2: -0.30 - 0.15j, 3: -0.15 + 0.10j}  # Q(t)/Q_mean = 1 + Re sum A_k e^{i k w t}, Q(0) = 0
H_ARTERY, H_SAC = 0.45, 0.30
CYCLES, PER_CYCLE = 3, 100
C_I = 36.0
dt = PERIOD / PER_CYCLE

# Womersley: harmonic k of the profile is f_k(r/R) = (1 - J0(z r/R)/J0(z)) / (1 - 2 J1(z)/(z J0(z))), z = i^(3/2) alpha sqrt(k).
# The inflow expression needs J0 of a complex argument, so it is written as a power series in s = (r/R)^2.
zeta = lambda k: np.exp(3j * np.pi / 4) * ALPHA * np.sqrt(k)
exact_f = lambda k, s: (
    (1 - jv(0, zeta(k) * np.sqrt(s)) / jv(0, zeta(k))) / (1 - 2 * jv(1, zeta(k)) / (zeta(k) * jv(0, zeta(k))))
)
exact = lambda s, t: (
    UMEAN * (2 * (1 - s) + sum((A * exact_f(k, s) * np.exp(1j * k * OMEGA * t)).real for k, A in HARMONICS.items()))
)


def series(k):
    """Coefficients of s^m of A_k f_k(s): J0(z sqrt(s)) = sum_m (i alpha^2 k s / 4)^m / (m!)^2."""
    j0 = np.array([(1j * ALPHA**2 * k / 4) ** m / factorial(m) ** 2 for m in range(24)])
    norm = 1 - 2 * jv(1, zeta(k)) / (zeta(k) * jv(0, zeta(k)))
    c = -j0 / j0.sum() / norm
    c[0] += 1 / norm
    return HARMONICS[k] * c


# the artery: a straight cylinder along z, a short neck and a sphere bulging in +x at z = L_IN, after the straight inlet length
artery = (
    jno.shape.cylinder(0, 0, 0, 0, 0, L_IN + L_OUT, R, size=H_ARTERY)
    | jno.shape.cylinder(0, 0, L_IN, X_SAC, 0, 0, R_NECK, size=H_SAC)
    | jno.shape.sphere(X_SAC, 0, L_IN, R_SAC, size=H_SAC)
)


def march(k, x0=None):
    """Cardiac cycle k (0-based) with BDF2, from the state x0 at its start (rest for the first cycle)."""
    d = artery.domain(time=(k * PERIOD, (k + 1) * PERIOD, PER_CYCLE + 1))
    x, y, z, t = d.variable("interior", split=True)
    xi, yi, zi, ti = d.variable("bottom", split=True)  # the inlet
    walls = [d.variable(side, split=True) for side in ("side", "surface")]  # artery wall; neck and sac wall
    ci = d.variable("initial", split=True)

    u = d.unknown.vector(3)  # equal order: P1 velocity,
    p = d.unknown.scalar(name="p")  # P1 pressure
    v, q = u.test(), p.test()

    grad = lambda w: jno.np.jacobian(w, [x, y, z])
    div = lambda w: jno.np.trace(grad(w))
    dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
    adv = lambda w, b: dot(grad(w), b)  # (b . grad) w
    ddt = lambda w: w.bind(x=x, y=y, z=z, t=t).t

    # SUPG and PSPG with the quasi-static residual of the DFG tutorial; tau carries the step, so it needs the fixed time grid
    G = d.cell_metric
    tau = jno.lag(((2 / dt) ** 2 + dot(u, dot(G, u)) + C_I * NU**2 * ddot(G, G)) ** -0.5)
    r_m = adv(u, u) - NU * jno.np.laplacian(u, [x, y, z]) + grad(p)
    momentum = dot(ddt(u), v) + dot(adv(u, u), v) + NU * ddot(grad(u), grad(v)) - p * div(v) + tau * dot(adv(v, u), r_m)
    continuity = -q * div(u) - tau * dot(grad(q), r_m)

    # the Womersley inflow along z: the steady Poiseuille part and three harmonics, a polynomial in s = (r/R)^2 times cos / sin
    s = (xi**2 + yi**2) / R**2
    horner = lambda c: reduce(lambda acc, ck: acc * s + ck, c[::-1])
    beat = sum(
        horner(series(h).real) * jno.np.cos(h * OMEGA * ti) - horner(series(h).imag) * jno.np.sin(h * OMEGA * ti)
        for h in HARMONICS
    )
    fem = jno.fem(
        [
            momentum,
            continuity,
            u(xi, yi, zi, ti)[0] - 0.0,
            u(xi, yi, zi, ti)[1] - 0.0,
            u(xi, yi, zi, ti)[2] - UMEAN * (2 * (1 - s) + beat),
            *[u(*w) - 0.0 for w in walls],  # no slip; the outlet gets no term (zero traction)
            u(*ci) - 0.0,  # the first cycle starts from rest, where Q(0) = 0
        ]
    )
    newton, lu = jno.solve.newton(direct=True, rtol=1e-7, atol=1e-7), jno.solve.lu(backend="pardiso")
    return fem, np.asarray(fem.solve(x0=x0, nonlinear=newton, linear=lu, time=jno.solve.bdf2()).eval())


tic, states = time.time(), []
for k in range(CYCLES):
    fem, traj = march(k, None if k == 0 else states[-1][-1])
    states.append(traj)
    el = time.time() - tic
    print(
        f"cycle {k + 1}/{CYCLES} done ({fem.dofs} dofs, {el / 60:.1f} min elapsed, ~{el / (k + 1) * (CYCLES - k - 1) / 60:.0f} min left)"
    )

# post-processing on the same mesh, steady: a form with these unknowns fixes the layout of the saved states
d = artery.domain()
x, y, z, _ = d.variable("interior", split=True)
u, p = d.unknown.vector(3), d.unknown.scalar(name="p")
v, q = u.test(), p.test()
grad = lambda w: jno.np.jacobian(w, [x, y, z])
div = lambda w: jno.np.trace(grad(w))
dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
post = jno.fem([NU * ddot(grad(u), grad(v)) - p * div(v) - q * div(u)])
pts, N, one = np.asarray(post.points), len(post.points), jno.np.vector(1.0, 1.0, 1.0)
assert np.allclose(pts, d.built_mesh.points)  # the nodes of the marched domains
nodal = lambda w: np.asarray(w)[: 3 * N].reshape(N, 3)  # the velocity block: (u_x, u_y, u_z) per node
rest = np.zeros(post.dofs)


def boundary(tag):
    """u and the test function on a tagged boundary, with its coordinates and outward normal."""
    xb, yb, zb, _, nx, ny, nz = d.variable(tag, normals=True, split=True)
    return u.bind(x=xb, y=yb, z=zb), v.bind(x=xb, y=yb, z=zb), [xb, yb, zb], jno.np.vector(nx, ny, nz)


def wall_shear(tag):
    """Wall shear stress in Pa on a wall: the traction mu (grad u) n of the no-slip wall without its normal part."""
    ub, vb, X, n = boundary(tag)
    tw = MU * dot(jno.np.jacobian(ub, X), n)  # (mm/s) / mm = 1/s
    return tw - dot(tw, n) * n, vb


(ub, _, _, n_in), (uo, _, _, n_out) = boundary("bottom"), boundary("top")
flux_in, flux_out = -dot(ub, n_in), dot(uo, n_out)  # volume flow rate in mm^3/s, in and out
shear = {tag: wall_shear(tag) for tag in ("surface", "side")}  # the dome with the neck rim; the artery wall with the neck
area = {tag: nodal(post.eval(dot(one, vb), rest))[:, 0] for tag, (_, vb) in shear.items()}  # lumped facet areas
dome_area, wall_area = area["surface"].sum(), area["surface"] + area["side"]
mass = nodal(post.eval(dot(one, v), rest))[:, 0]  # lumped volume of each node
vorticity = jno.np.curl_3d(u[0], u[1], u[2], x, y, z)


def wss(sol):
    """Nodal wall shear vector (Pa): the lumped L2 projection of the wall traction."""
    load = sum(nodal(post.eval(dot(tw, vb), sol)) for tw, vb in shear.values())
    return load / np.maximum(wall_area, 1e-30)[:, None]


states = np.concatenate([c[:-1] for c in states] + [states[-1][-1:]])  # every step of the CYCLES cycles
ts = np.linspace(0.0, CYCLES * PERIOD, len(states))
last = slice(-PER_CYCLE - 1, None)  # the last cycle, both ends included
Q_in = np.array([post.eval(flux_in, sol) for sol in states])
Q_out = np.array([post.eval(flux_out, sol) for sol in states])
Q_beat = UMEAN * np.pi * R**2 * (1 + sum((A * np.exp(1j * k * OMEGA * ts)).real for k, A in HARMONICS.items()))

# (1) the straight inlet section against the exact Womersley solution, at eight phases of the last cycle
inlet = (pts[:, 2] > 1.0) & (pts[:, 2] < 7.0) & (np.hypot(pts[:, 0], pts[:, 1]) <= R + 1e-9)
s_n = (pts[inlet, 0] ** 2 + pts[inlet, 1] ** 2) / R**2
phases = (CYCLES - 1) * PER_CYCLE + np.arange(8) * PER_CYCLE // 8
peak = exact(0.0, ts[(CYCLES - 1) * PER_CYCLE :]).max()  # peak centre-line velocity of the cycle
err_axial = max(np.abs(nodal(states[i])[inlet, 2] - exact(s_n, ts[i])).max() for i in phases) / peak
err_cross = max(np.abs(nodal(states[i])[inlet, :2]).max() for i in phases) / peak
print(f"Womersley section: alpha = {ALPHA:.2f}, peak centre-line velocity {peak:.0f} mm/s, Re_peak = {peak * R / NU:.0f}")
print(f"  axial velocity: max error {100 * err_axial:.1f}% of the peak at eight phases; cross-flow {100 * err_cross:.2f}%")

# (2) mass: what flows in flows out, and the inflow is the prescribed waveform
leak = np.abs(Q_in - Q_out).max() / np.abs(Q_in).max()
dev = np.abs(Q_in - Q_beat).max() / Q_beat.max()
print(
    f"mass: max |Q_in - Q_out| = {leak:.1e} of the peak flow rate {Q_in.max() / 1e3:.2f} mL/s; inflow vs prescribed {100 * dev:.2f}%"
)

# (3) the last cycle against the one before: the whole artery, and the sac alone, which is slow and remembers longest
sac = (pts[:, 0] > R) & (np.linalg.norm(pts - [X_SAC, 0.0, L_IN], axis=1) < R_SAC)  # the nodes inside the sphere
norm = lambda i, m: np.linalg.norm(nodal(states[i])[m])
diff = lambda i, m: np.linalg.norm(nodal(states[i])[m] - nodal(states[i - PER_CYCLE])[m])
gaps = {}
for c in range(2, CYCLES + 1):  # cycle c against cycle c - 1: the largest difference over the largest velocity norm
    for name, m in (("artery", slice(None)), ("sac", sac)):
        idx = range((c - 1) * PER_CYCLE, c * PER_CYCLE + 1)
        gaps[c, name] = max(diff(i, m) for i in idx) / max(norm(i, m) for i in idx)
    print(
        f"periodicity, cycle {c} vs {c - 1}: relative velocity difference {100 * gaps[c, 'artery']:.3f}% in the artery, {100 * gaps[c, 'sac']:.3f}% in the sac"
    )

# the wall shear stress: the straight artery against the exact Womersley wall shear, then the dome over the last cycle
cycle = np.arange(len(states) - PER_CYCLE - 1, len(states))
tau = np.array([np.linalg.norm(wss(states[i]), axis=1) for i in cycle])  # |wall shear| per node, Pa
straight = (area["side"] > 0) & (pts[:, 2] > 2.0) & (pts[:, 2] < 8.0) & (np.abs(np.hypot(pts[:, 0], pts[:, 1]) - R) < 1e-6)
tau_wall = lambda t: MU * (exact(1.0, t) - exact((1 - 1e-4) ** 2, t)) / (R * 1e-4)  # mu du/dr at r = R, Pa
ratio = np.array(
    [np.median(tau[j][straight]) / abs(tau_wall(ts[i])) for j, i in enumerate(cycle) if abs(tau_wall(ts[i])) > 2.0]
)
print(
    f"wall shear of the straight artery / exact: median {np.median(ratio):.2f} (range {ratio.min():.2f} to {ratio.max():.2f})"
)
dome = area["surface"] > 0
mean_dome = np.array([post.eval(jno.np.norm(shear["surface"][0]), states[i]) for i in cycle]) / dome_area  # area mean, Pa
tawss = tau.mean(0)  # time-averaged |wall shear| per node
osi = 0.5 * (1 - np.linalg.norm(np.array([wss(states[i]) for i in cycle]).mean(0), axis=1) / np.maximum(tawss, 1e-30))
print(
    f"dome ({dome_area:.1f} mm^2): area-mean wall shear {mean_dome.min():.2f} to {mean_dome.max():.2f} Pa over the cycle, peak at t/T = {np.argmax(mean_dome) / PER_CYCLE:.2f}"
)
print(
    f"  time-averaged: mean {np.average(tawss[dome], weights=area['surface'][dome]):.2f} Pa, nodes from {tawss[dome].min():.2f} to {tawss[dome].max():.2f} Pa; mean oscillatory index {np.average(osi[dome], weights=area['surface'][dome]):.3f}"
)

# the vortex in the sac: nodal vorticity (lumped projection of curl u) and speed over the nodes inside the sphere
omega = np.array([nodal(post.eval(dot(vorticity, v), states[i])) / mass[:, None] for i in cycle])
speed = np.linalg.norm([nodal(states[i]) for i in cycle], axis=2)
rms_vort, mean_speed = np.sqrt((omega[:, sac] ** 2).sum(2).mean(1)), speed[:, sac].mean(1)
spin = omega[:, sac, 1].mean(1)  # y-component: the rotation in the mid-plane through the artery axis and the sac
print(
    f"sac: mean speed {mean_speed.min():.1f} to {mean_speed.max():.1f} mm/s ({100 * mean_speed.max() / UMEAN:.0f}% of the mean velocity), peak at t/T = {np.argmax(mean_speed) / PER_CYCLE:.2f}"
)
print(
    f"  rms vorticity {rms_vort.min():.1f} to {rms_vort.max():.1f} 1/s, peak at t/T = {np.argmax(rms_vort) / PER_CYCLE:.2f}; mean omega_y {spin.min():+.1f} to {spin.max():+.1f} 1/s"
)
assert err_axial < 0.08 and err_cross < 0.02  # a first-order P1 profile on this mesh: a few per cent of the peak
assert leak < 1e-8 and dev < 0.04  # global conservation, and the inflow the prescribed waveform to the P1 interpolation
assert gaps[CYCLES, "artery"] < 1e-3 and gaps[CYCLES, "sac"] < 1e-3  # the last cycle repeats the one before
assert 0.8 < np.median(ratio) < 1.1  # the P1 wall shear of a straight artery is within about 10-20% of the exact one
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    frames = cycle[::2]  # every second step of the last cycle
    np.savez_compressed(
        Path(out) / "pulsatile_aneurysm_3d.npz",
        points=pts,
        tets=np.asarray(d.mesh.cells_dict["tetra"]),
        faces=np.asarray(d.mesh.cells_dict["triangle"]),
        velocity=np.array([nodal(states[i]) for i in frames], np.float32),
        wss=tau[::2].astype(np.float32),
        omega=omega[::2].astype(np.float32),
        t=ts[frames] - ts[cycle[0]],
        tawss=tawss,
        osi=osi,
        dome=dome,
        flow=Q_in[frames],
        geometry=np.array([R, L_IN, L_OUT, R_NECK, R_SAC, X_SAC, UMEAN, PERIOD]),
    )
