# --8<-- [start:code]
"""Chladni figures: the free vibration modes of a square plate on the Argyris element.

A thin plate (Kirchhoff) vibrates as  D Delta^2 w = rho h w_tt , so its modes solve  K w = lambda M w  with
lambda = omega^2 rho h / D, the bending energy  (1 - nu) |hess w|^2 + nu (Delta w)^2  and the mass  w^2.
All four edges are free: bending moment and effective shear vanish, which is the natural condition of that
energy, so the boundary needs no term at all. The nodal lines of a mode are where sand collects on a plate
shaken at that frequency. A fourth-order form needs a C1 element: Argyris, a quintic on each triangle with
the value, gradient and Hessian at the vertices and the normal slope at the edge midpoints.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # a fourth-order operator needs double precision
run = jno.setup(__file__)
NU, SIZE, MODES = 0.3, 0.1, 18


def plate_modes(size, k, supported=False):
    """The k lowest modes of the unit plate (free edges, or simply supported) on Argyris triangles: Omega and DOF vectors."""
    d = jno.shape.rect(0, 0, 1, 1, size=size).domain()
    x, y, _ = d.variable("interior", split=True)
    b = d.variable("boundary", split=True)
    u = d.unknown(space="Argyris")
    v = u.test()
    ui, vi = u.bind(x=x, y=y), v.bind(x=x, y=y)
    hess = lambda w: jno.np.hessian(w, [x, y])
    lap = lambda w: jno.np.laplacian(w, [x, y])
    ddot = lambda a, b: jno.np.inner(a, b, n_contract=2)
    energy = (1 - NU) * ddot(hess(ui), hess(vi)) + NU * lap(ui) * lap(vi)
    plate = jno.fem([energy, u(*b) - 0.0] if supported else [energy])  # free edges need no boundary term
    lam, X = plate.eigs(mass=[ui * vi], k=k)
    return d, plate.dofs, np.sqrt(np.abs(np.asarray(lam))), np.asarray(X)


runs = {size: plate_modes(size, MODES) for size in (0.25, 0.15, SIZE, 0.05)}
for size, (_, dofs, omega, _) in runs.items():
    print(f"size {size}: {dofs} DOFs, Omega 1-6 = " + " ".join(f"{o:.4f}" for o in omega[3:9]))
d, dofs, omega, X = runs[SIZE]
assert omega[:3].max() < 1e-2, "the three rigid-body modes (two tilts and a lift) have no frequency"
# exact reference: the simply supported square (w = 0 on the edges, moments free) has Omega = pi^2 (m^2 + n^2)
_, _, ss, _ = plate_modes(SIZE, 4, supported=True)
exact = np.pi**2 * np.array([2, 5, 5, 8])
print(
    "simply supported, Omega 1-4 = " + " ".join(f"{o:.5f}" for o in ss) + "   exact " + " ".join(f"{o:.5f}" for o in exact)
)
assert np.abs(ss / exact - 1).max() < 1e-6, ss
# the free plate's fourth and fifth vibration modes (a symmetric pair) are degenerate
assert abs(omega[7] / omega[6] - 1) < 1e-5, omega[6:8]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/chladni_plate_argyris.py), only when asked ----
import os  # noqa: E402
from pathlib import Path  # noqa: E402

if out := os.environ.get("JNO_FIGURE_DATA"):
    from jno.utils.solver.fem_topology import BASIX_TRIANGLE_EDGES, build_edge_topology  # noqa: E402

    cells = np.asarray(d.mesh.cells_dict["triangle"])
    top = build_edge_topology(cells, BASIX_TRIANGLE_EDGES)
    np.savez_compressed(
        Path(out) / "chladni_plate_argyris.npz",
        points=np.asarray(d.mesh.points)[:, :2],
        triangles=cells,
        edge_vertices=np.asarray(top.edge_vertices),
        cell_edges=np.asarray(top.cell_edges),
        omega=omega,
        modes=X[:, 3:].T,
    )
