import os
from pathlib import Path

# --8<-- [start:code]
"""A piezoelectric bimorph cantilever: displacement and electric potential solved together, against the beam formula."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# PZT-5A-like ceramic in mm, N, V and mC (so MPa for stress, mC/mm^2 for charge density)
Y, NU = 6.1e4, 0.3  # Young's modulus (MPa) and Poisson ratio of the ceramic
D31, D33 = -1.71e-7, 3.74e-7  # piezoelectric strain constants (mm/V): strain per field along the poling axis
KAPPA = 1.53e-8  # permittivity at constant stress (mC/(V mm))
L, T, VOLTS = 20.0, 1.0, 500.0  # the beam's length and total thickness (mm), the voltage across it
lam, mu = Y * NU / (1 - NU**2), Y / (2 * (1 + NU))  # plane-stress Lame parameters
E31, E33 = (lam + 2 * mu) * D31 + lam * D33, lam * D31 + (lam + 2 * mu) * D33  # stress per unit field, plane stress
KAPPA_S = KAPPA - (E31 * D31 + E33 * D33)  # permittivity at constant strain

# two bonded layers, poled in opposite directions (pol = +1: along +y, -1: along -y)
up = jno.shape.rect(0, T / 2, L, T, size=0.06).name("up").attach(pol=1.0)
down = jno.shape.rect(0, 0, L, T / 2, size=0.06).name("down").attach(pol=-1.0)
d = (down + up).domain()
x, y, _ = d.variable("interior", split=True)
root, top, bottom = (d.variable(side, split=True) for side in ("left", "top", "bottom"))
u, phi = d.unknown.vector(2, order=2), d.unknown.scalar(name="phi", order=2)
v, psi = u.test(), phi.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)
stress = lambda w: 2 * mu * eps(w) + lam * tr(eps(w)) * jno.np.identity(2)  # the ceramic's elastic stress
couple = lambda w: E31 * eps(w)[..., 0, 0] + E33 * eps(w)[..., 1, 1]  # e : eps(w), the coupling tensor on a strain
phi_y, psi_y = phi.bind(x=x, y=y).y, psi.bind(x=x, y=y).y


def bimorph(volts):
    """u and phi with the top electrode at `volts` and the bottom one grounded (the two layers share one field)."""
    fem = jno.fem(
        [
            ddot(stress(u), eps(v)) + d.pol * phi_y * couple(v),  # div(C eps - e E) = 0, E = -grad phi
            KAPPA_S * dot(grad(phi), grad(psi)) - d.pol * psi_y * couple(u),  # div(e eps + kappa E) = 0
            u(*root) - (0.0, 0.0),  # clamped root
            phi(*top) - volts,
            phi(*bottom) - 0.0,
        ]
    )
    sol = fem.solve(linear=jno.solve.lu())
    return fem, np.asarray(sol.u).reshape(-1, 2), np.asarray(sol.phi)


fem, disp, pot = bimorph(VOLTS)
tip = np.asarray(fem.field_points[fem.block_index(u)])[:, 0] > L - 1e-9
deflection = disp[tip, 1].mean()
classical = 3 * D31 * VOLTS * L**2 / (2 * T**2)  # series bimorph, E = V/t in both layers
k2 = Y * D31**2 / KAPPA  # electromechanical coupling k31^2: the field the beam's own bending feeds back
corrected = classical * (1 - k2) / (1 - 0.75 * k2)
half = bimorph(-VOLTS / 2)[1]  # linear problem: half the voltage, reversed, gives -1/2 of the displacement
print(f"bimorph: {fem.dofs} DOFs; tip deflection {deflection:.5f} mm, 3 d31 V L^2 / (2 t^2) = {classical:.5f} mm")
print(f"  ratio {deflection / classical:.4f}; with the coupling correction ({k2:.3f}) {deflection / corrected:.4f}")
assert abs(deflection / classical - 1) < 0.05  # the beam formula, to the slenderness and the coupling it neglects
assert abs(deflection / corrected - 1) < 0.01 and np.abs(half + disp / 2).max() < 1e-9 * np.abs(disp).max()
# --8<-- [end:code]

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

    verts, nodes = np.asarray(d.built_mesh.points)[:, :2], np.asarray(fem.field_points[fem.block_index(u)])[:, :2]
    near = cKDTree(nodes).query(verts)[1]
    cells = np.asarray(d.mesh.cells_dict["triangle"])
    np.savez_compressed(
        Path(out) / "piezo_bimorph.npz",
        vertices=verts,
        cells=cells,
        upper=verts[cells][..., 1].mean(1) > T / 2,
        displacement=disp[near].astype(np.float32),
        potential=pot[near],
        geometry=[L, T, VOLTS, D31],
        deflection=[deflection, classical, corrected],
    )
