import os
from pathlib import Path

# --8<-- [start:code]
"""Heat, then stress, in a real CAD part: a NIST test part (STEP) meshed with gmsh, heated at a shaft bearing, bolted down."""

import gmsh
import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# structural steel (representative values), SI units: m, s, W, K, Pa; T is the temperature rise over the 20 C ambient
E, NU, ALPHA = 200e9, 0.3, 12e-6  # Young's modulus, Poisson ratio, thermal expansion
KTH, RHOC = 45.0, 7850 * 470.0  # conductivity, heat capacity per volume
H, Q = 25.0, 1.2e4  # convection to the air (W/m^2K); heat flux into the bearing journal (W/m^2)
BAND = (0.34, 0.44)  # the bearing journal on the shaft, from z to z (m)
T_END, N, SIZE = 10800.0, 180, 0.012  # three hours in steps of one minute; mesh size (m)
lam, mu = E * NU / ((1 + NU) * (1 - 2 * NU)), E / (2 * (1 + NU))
STEP = Path(__file__).with_name("nist_ctc_05_asme1_rd.stp")  # NIST MBE PMI test case CTC-05, geometry only
mesh_file = Path(run) / "shaft_flange.msh"  # written by cad_mesh, read by jno.domain


def cad_mesh(h, path):
    """The STEP file as a tetrahedral gmsh mesh (in metres) with the faces we load named: the journal and the bolt seats."""
    gmsh.initialize()
    gmsh.option.setString("Geometry.OCCTargetUnit", "M")  # the file is in inches
    occ = gmsh.model.occ
    occ.importShapes(str(STEP))
    occ.synchronize()
    occ.fragment([(3, 1)], [(2, occ.addDisk(0, 0, z, 0.2, 0.2)) for z in BAND])  # planes through the shaft: the journal
    occ.synchronize()
    outside = [s for _, s in gmsh.model.getEntities(2) if not gmsh.model.getAdjacencies(2, s)[0].size]
    occ.remove([(2, s) for s in outside])  # the parts of those planes in the air
    occ.synchronize()
    faces = [s for _, s in gmsh.model.getEntities(2)]
    box = lambda s: np.array(gmsh.model.getBoundingBox(2, s))
    kind = lambda s: gmsh.model.getType(2, s)
    seat = [s for s in faces if kind(s) == "Plane" and np.ptp(box(s)[[2, 5]]) < 1e-6 and abs(box(s)[2] - 0.0127) < 1e-5]
    journal = [s for s in faces if kind(s) == "Cylinder" and box(s)[2] > BAND[0] - 1e-5 and box(s)[5] < BAND[1] + 1e-5]
    gmsh.model.addPhysicalGroup(3, [v for _, v in gmsh.model.getEntities(3)], name="part")
    gmsh.model.addPhysicalGroup(2, seat, name="seat")  # the floors of the ten counterbores, under the bolt heads
    gmsh.model.addPhysicalGroup(2, [s for s in journal if box(s)[3] < 0.034], name="journal")  # the shaft, not the hub
    fine = gmsh.model.mesh.field.add("Box")  # half the element size around the shaft, where the stress is read
    for key, val in dict(
        VIn=h / 2, VOut=h, XMin=-0.04, XMax=0.04, YMin=-0.04, YMax=0.04, ZMin=0.28, ZMax=0.49, Thickness=0.03
    ).items():
        gmsh.model.mesh.field.setNumber(fine, key, val)
    gmsh.model.mesh.field.setAsBackgroundMesh(fine)
    gmsh.option.setNumber("Mesh.MeshSizeMax", h)
    gmsh.option.setNumber("Mesh.MeshSizeMin", h / 12)
    gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 10 * SIZE / h)  # elements per circle, in step with h
    gmsh.model.mesh.generate(3)
    gmsh.write(str(path))
    gmsh.finalize()


def heat_terms(d, T, source, robin, flux, init=None):
    """rho c T_t - div(k grad T) = source;  k dT/dn + h T = robin on every face, and a flux q into the journal."""
    x, y, z, t = d.variable("interior", split=True)
    xb, yb, zb, tb, nx, ny, nz = d.variable("boundary", normals=True, split=True)
    j = d.variable("journal", split=True)
    S, Tb, Tw = T.test(), T.bind(x=x, y=y, z=z, t=t), T.bind(x=xb, y=yb, z=zb, t=tb)
    grad, dot = lambda w: jno.np.jacobian(w, [x, y, z]), jno.np.inner
    volume = KTH * dot(grad(Tb), grad(S)) - source(x, y, z, t) * S + (RHOC * Tb.t * S if init else 0)
    terms = [
        volume,
        (H * Tw - robin(xb, yb, zb, tb, (nx, ny, nz))) * S.bind(x=xb, y=yb, z=zb, t=tb),
        -flux * S.bind(x=j[0], y=j[1], z=j[2]),
    ]
    if init:  # a march: the initial state
        terms.append(T(*(ci := d.variable("initial", split=True))) - init(*ci))
    return terms


# verification on this geometry: a manufactured temperature, with the source and the convection data it implies,
# solved by the same terms on three meshes of the part. The formulas are written once for jno.np (the weak form) and numpy (the error)
def manufactured_solution(m):
    a = lambda x, y, z: 40.0 * (1.0 + m.sin(8 * x + 1) * m.cos(6 * y) + 2 * z)
    b = lambda x, y, z: (30.0 / T_END) * (1.0 + 3 * x - 2 * y + 2 * z)  # harmonic, so the source does not depend on time
    exact = lambda x, y, z, t: a(x, y, z) + t * b(x, y, z)  # a ramp in time: the backward Euler march has no time error
    dn_a = lambda x, y, z, n: (
        320.0 * m.cos(8 * x + 1) * m.cos(6 * y) * n[0] - 240.0 * m.sin(8 * x + 1) * m.sin(6 * y) * n[1] + 80.0 * n[2]
    )
    dn_b = lambda n: (30.0 / T_END) * (3 * n[0] - 2 * n[1] + 2 * n[2])  # normal derivatives, by hand
    source = lambda x, y, z, t: RHOC * b(x, y, z) + 4000.0 * KTH * m.sin(8 * x + 1) * m.cos(6 * y)  # rho c T_t - k lap T
    robin = lambda x, y, z, t, n: KTH * (dn_a(x, y, z, n) + t * dn_b(n)) + H * exact(x, y, z, t)  # k dT/dn + h T
    return exact, source, robin


def manufactured(h):
    cad_mesh(h, mesh_file)
    dm = jno.domain(str(mesh_file), time=(0.0, T_END, 5))
    Tm, (exact, source, robin) = dm.unknown.scalar(name="T"), manufactured_solution(jno.np)
    fm = jno.fem(heat_terms(dm, Tm, source, robin, 0.0, init=lambda x, y, z, t: exact(x, y, z, 0.0)))
    last = np.asarray(fm.solve(linear=jno.solve.lu(backend="pardiso")).eval())[-1]
    X, w = np.asarray(fm.field_points[0]), np.asarray(fm.eval(1.0 * Tm.test(), last))  # w: the lumped mass of every node
    return float(np.sqrt(w @ (last - manufactured_solution(np)[0](X[:, 0], X[:, 1], X[:, 2], T_END)) ** 2)), len(X)


levels = [manufactured(h) for h in (2 * SIZE, np.sqrt(2) * SIZE, SIZE)]
orders = [np.log(e0 / e1) / np.log((n1 / n0) ** (1 / 3)) for (e0, n0), (e1, n1) in zip(levels, levels[1:])]
print(
    "manufactured solution, L2 error:",
    ", ".join(f"{e:.3g} K ({n} nodes)" for e, n in levels),
    f"orders {np.round(orders, 2)}",
)
assert levels[-1][0] < 0.5 * levels[0][0] and min(orders) > 1.8  # P1: second order in the mesh size

# the heat problem of the real run: cold start, no volume source, the journal heated, convection on every face
cad_mesh(SIZE, mesh_file)
d = jno.domain(str(mesh_file), time=(0.0, T_END, N + 1))
x, y, z, t = d.variable("interior", split=True)
xb, yb, zb, tb = d.variable("boundary", split=True)[:4]
j, seat = d.variable("journal", split=True), d.variable("seat", split=True)
T, u = d.unknown.scalar(name="T"), d.unknown.vector(3, name="u")
v, S = u.test(), T.test()

# thermo-elasticity: sigma = C : (eps(u) - alpha T I), quasi-static
eps = lambda w: jno.np.symgrad(w, [x, y, z])
ddot, tr, I3, ez = (
    lambda a, b: jno.np.inner(a, b, n_contract=2),
    jno.np.trace,
    jno.np.identity(3),
    jno.np.vector(0.0, 0.0, 1.0),
)
sigma = (lam * tr(eps(u)) - (3 * lam + 2 * mu) * ALPHA * T.bind(x=x, y=y, z=z, t=t)) * I3 + 2 * mu * eps(u)
dev = sigma - tr(sigma) / 3 * I3
mises = jno.np.sqrt(1.5 * ddot(dev, dev) + 1e-30)
szz = jno.np.inner(jno.np.inner(sigma, ez, n_contract=1), ez)
nothing = lambda *c: 0.0
fem = jno.fem(
    heat_terms(d, T, nothing, nothing, Q, init=nothing)
    + [
        ddot(sigma, eps(v)),  # equilibrium
        u(*seat) - (0.0, 0.0, 0.0),  # bolted: no displacement on the bolt seats
    ]
)
traj = np.asarray(fem.solve(linear=jno.solve.lu(backend="pardiso")).eval())
iT, iu = fem.block_index(T), fem.block_index(u)
theta, disp = traj[:, fem.blocks[iT]], traj[:, fem.blocks[iu]].reshape(len(traj), -1, 3)
pts = np.asarray(fem.field_points[iT])
print(f"{fem.dofs} dofs, {len(pts)} nodes, {len(d.mesh.cells_dict['tetra'])} tetrahedra, {N} steps")

# stress at the nodes: the rows of the weak form  int f S  over the lumped weights  int S  (a mass-lumped L2 projection)
rows_of = lambda f, k: np.asarray(fem.eval(f * S, traj[k]))[fem.blocks[iT]]  # the rows of the T test functions
nodal = lambda f, k: rows_of(f, k) / rows_of(1.0, 0)

# (1) energy balance of every step: heat in = stored + convected out (rows of a weak term sum to its integral)
row = lambda e, k: float(np.asarray(fem.eval(e, traj[k])).sum())
Sb, Sj = S.bind(x=xb, y=yb, z=zb), S.bind(x=j[0], y=j[1], z=j[2])
stored = lambda k: row(RHOC * T.bind(x=x, y=y, z=z, t=t) * S, k)
lost = lambda k: row(H * T.bind(x=xb, y=yb, z=zb, t=tb) * Sb, k)
power, dt = row(Q * Sj, 0), T_END / N
balance = max(abs(power - (stored(k) - stored(k - 1)) / dt - lost(k)) for k in range(1, N + 1)) / power
print(f"heater {power:.0f} W; energy balance {balance:.1e}; convected {lost(N) / power:.1%} of the heater power at the end")
assert balance < 1e-9  # backward Euler conserves the heat exactly: only the solver's round-off is left

# (2) the steady state: the end of the march against a direct solve of the steady problem on the same mesh
ds = jno.domain(str(mesh_file))
steady = np.asarray(jno.fem(heat_terms(ds, ds.unknown.scalar(name="T"), nothing, nothing, Q)).solve(linear=jno.solve.lu()))
gap = np.abs(theta[-1] - steady).max() / steady.max()
print(f"peak rise {theta[-1].max():.1f} K after {T_END / 3600:g} h, steady {steady.max():.1f} K (gap {gap:.1%})")
assert gap < 0.01

# (3) no stress without a gradient: the part heated uniformly and free to expand, u = alpha T0 x, leaves no residual, no stress
T0 = 50.0
state, free = np.zeros(fem.dofs), np.zeros(fem.dofs)
state[fem.blocks[iT]] = free[fem.blocks[iT]] = T0
free[fem.blocks[iu]] = (ALPHA * T0 * np.asarray(fem.field_points[iu])).ravel()
equilibrium = ddot(sigma, eps(v))
rows = lambda e, s: np.abs(np.asarray(fem.eval(e, s))).max()
residual = rows(equilibrium, free) / rows(equilibrium, state)  # against the thermal load it balances
rough = float(np.asarray(fem.eval(mises * S, free)).sum()) / (E * ALPHA * T0 * row(1.0 * S, 0))  # mean von Mises
print(f"free part, uniform rise: residual {residual:.1e} of the thermal load, mean von Mises {rough:.1e} of E alpha T0")
assert residual < 1e-10 and rough < 1e-10

# (4) a long hot cylinder against its closed form: the same part, but with the temperature prescribed in the shaft,
# T = dT r^2 / R^2 above a smooth ramp near the root. Far from both ends a free solid cylinder has the axial stress
# sigma_zz = E alpha / (1 - nu) (2/R^2 int_0^R T r dr - T)  (Timoshenko and Goodier): dT / 2 - T, times E alpha / (1 - nu)
R_SHAFT, DT = 0.03175, 50.0
xs, ys, zs, _ = ds.variable("interior", split=True)
us, Ps = ds.unknown.vector(3, name="u"), ds.unknown.scalar(name="P")  # P: the axial stress, projected onto the nodes
vs, Qs = us.test(), Ps.test()
eps_s = lambda w: jno.np.symgrad(w, [xs, ys, zs])
hot = DT * jno.np.minimum((xs**2 + ys**2) / R_SHAFT**2, 1.0) * (1.0 + jno.np.tanh((zs - 0.31) / 0.01)) / 2
sigma_s = (lam * tr(eps_s(us)) - (3 * lam + 2 * mu) * ALPHA * hot) * I3 + 2 * mu * eps_s(us)
cyl = jno.fem(
    [
        ddot(sigma_s, eps_s(vs)),
        us(*ds.variable("seat", split=True)) - (0.0, 0.0, 0.0),
        (Ps - jno.np.inner(jno.np.inner(sigma_s, ez, n_contract=1), ez)) * Qs,
    ]
)
sol = np.asarray(cyl.solve(linear=jno.solve.lu(backend="pardiso")))
found, at = sol[cyl.blocks[cyl.block_index(Ps)]], np.asarray(cyl.field_points[cyl.block_index(Ps)])
mid = np.abs(at[:, 2] - 0.406) < 0.012  # mid shaft, between the ramp and the tip
slab = mid & (np.hypot(at[:, 0], at[:, 1]) < R_SHAFT + 1e-6)
closed = E * ALPHA * DT / (1 - NU) * (0.5 - (at[slab, 0] ** 2 + at[slab, 1] ** 2) / R_SHAFT**2)
mismatch = np.sqrt(np.mean((found[slab] - closed) ** 2)) / np.abs(closed).max()
lo, hi = found[slab].min() / 1e6, found[slab].max() / 1e6
print(
    f"hot cylinder, sigma_zz {lo:.1f} to {hi:.1f} MPa, closed form +-{closed.max() / 1e6:.1f} MPa, rms gap {mismatch:.1%} of its peak"
)
# the projection overshoots at the surface, and the part is a short cylinder on a hub, not an infinite one
assert mismatch < 0.12

# the stress of the run, at the saved states: dense while the shaft heats
frames = np.unique(np.round(N * np.linspace(0, 1, 91) ** 2).astype(int))
vm = np.stack([nodal(mises, k) for k in frames])
peak = vm.max(axis=1)
at_peak, at_end = frames[peak.argmax()] * dt / 60, pts[vm[-1].argmax(), 2] * 1e3
print(
    f"von Mises: peak {peak.max() / 1e6:.1f} MPa at t = {at_peak:.0f} min, {peak[-1] / 1e6:.1f} MPa at the end, at z = {at_end:.0f} mm"
)
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    from scipy.spatial import cKDTree

    X = np.asarray(d.built_mesh.points)
    at = cKDTree(pts).query(X)[1]
    np.savez_compressed(
        Path(out) / "shaft_flange_thermal_stress.npz",
        points=X,
        tets=np.asarray(d.mesh.cells_dict["tetra"]),
        t=frames * dt,
        theta=theta[frames][:, at].astype(np.float32),
        mises=vm[:, at].astype(np.float32),
        band=BAND,
    )
