import os
from pathlib import Path

# --8<-- [start:code]
"""A bimetallic strip curls when heated: transient heating and plane-stress thermo-elasticity, against Timoshenko's formula."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L = 10.0  # length of the strip
T1, E1, A1 = 0.5, 2.0, 0.01  # layer 1 (top): thickness, Young's modulus, thermal expansion: stiff, expands little
T2, E2, A2 = 0.5, 1.0, 0.03  # layer 2 (bottom): soft, expands three times as much
NU, RHOC, K = 0.3, 1.0, 1.0  # Poisson ratio, heat capacity and conductivity (both layers)
DT_END, T_END, N_STEPS = 1.0, 1.0, 60  # heated uniformly by DT_END over T_END

top = jno.shape.rect(0, T2, L, T1 + T2, size=0.1).name("layer1").attach(E=E1, alpha=A1)
bottom = jno.shape.rect(0, 0, L, T2, size=0.1).name("layer2").attach(E=E2, alpha=A2)
d = (bottom + top).domain(time=(0.0, T_END, N_STEPS + 1))  # two bodies, one conforming interface
x, y, t = d.variable("interior", split=True)
root, ci = d.variable("left", split=True), d.variable("initial", split=True)
u = d.unknown.vector(2, order=2)  # P2: constant-strain triangles are too stiff in bending
T = d.unknown.scalar(name="T")  # the temperature rise over the reference state
v, S = u.test(), T.test()

grad, eps, tr = (lambda w: jno.np.jacobian(w, [x, y])), (lambda w: jno.np.symgrad(w, [x, y])), jno.np.trace
dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
mu, lam = d.E / (2 * (1 + NU)), d.E * NU / (1 - NU**2)  # plane-stress Lame parameters, layer by layer
sigma = lambda w, Tw: 2 * mu * eps(w) + (lam * tr(eps(w)) - d.E * d.alpha * Tw / (1 - NU)) * jno.np.identity(2)

fem = jno.fem(
    [
        RHOC * T.bind(x=x, y=y, t=t).t * S + K * dot(grad(T), grad(S)) - RHOC * DT_END / T_END * S,  # uniform heating
        ddot(sigma(u, T), eps(v)),  # sigma(u, T) : eps(v) = 0, quasi-static
        u(*root) - (0.0, 0.0),  # clamped root
        T(*ci) - 0.0,
    ]
)
traj = np.asarray(fem.solve(linear=jno.solve.lu()).eval())

ib, it = fem.block_index(u), fem.block_index(T)
disp = traj[:, fem.blocks[ib]].reshape(len(traj), -1, 2)
tip = np.asarray(fem.field_points[ib])[:, 0] > L - 1e-6
deflection = disp[-1, tip, 1].mean()
m, n, h = T1 / T2, E1 / E2, T1 + T2  # Timoshenko (1925): the curvature of a heated bimetal strip
kappa = 6 * (A2 - A1) * DT_END * (1 + m) ** 2 / (h * (3 * (1 + m) ** 2 + (1 + m * n) * (m**2 + 1 / (m * n))))
exact = kappa * L**2 / 2  # a circular arc of curvature kappa, for small angles
spread = np.ptp(traj[-1, fem.blocks[it]])
print(f"bimetal strip: {fem.dofs} DOFs; temperature rise {traj[-1, fem.blocks[it]].mean():.4f}, spread {spread:.1e}")
print(
    f"  tip deflection {deflection:.4f}   Timoshenko {exact:.4f}   ratio {deflection / exact:.4f}   (kappa L = {kappa * L:.3f})"
)
assert spread < 1e-9 and abs(deflection / exact - 1) < 0.03  # Timoshenko, J. Opt. Soc. Am. 11 (1925) 233
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "bimetallic_strip.npz",
        points=np.asarray(fem.field_points[ib]),
        vertices=np.asarray(d.built_mesh.points)[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        displacement=disp.astype(np.float32),
        temperature=traj[:, fem.blocks[it]].mean(axis=1),
        t=np.linspace(0.0, T_END, len(traj)),
        material=[E1, E2, A1, A2, NU],
        geometry=[L, T1, T2],
        kappa=kappa,
    )
