# --8<-- [start:code]
"""Topology optimisation of a bracket on a deformable mesh: the density AND the node positions are design variables.

A plate bolted down through two holes carries a deck load that rises along its top. The optimiser drives one
vector [rho, x, y]: an element density per triangle plus the position of every interior node, so the
boundary of the material is resolved by moving nodes onto it.
Method: K. Jung and D.-N. Kim, "Density-based topology optimization using a deformable mesh",
Computers & Structures (2025), doi:10.1016/j.compstruc.2025.107879; perimeter control after
R.B. Haber, C.S. Jog and M.P. Bendsoe, Struct. Optim. 11 (1996) 1-12.

The run ends with a reanalysis: the converged density is transferred to a clean, undistorted mesh and
solved again, to tell a better structure from distorted elements that under-integrate the strain energy.
"""

import os
from pathlib import Path

import jax
import jax.numpy as jnp
import numpy as np
import optax

import jno

jax.config.update("jax_enable_x64", True)  # the p = 50 geometric aggregates need the exponent range
run = jno.setup(__file__)

L, H, h = 60.0, 30.0, 0.5  # plate and target edge length
HOLES, R, WASHER, SKIN = ((12.0, 6.0), (48.0, 6.0)), 2.5, 1.5, 1.0  # bolt holes, washer ring, deck thickness
E0, EMIN, NU, PENAL, VOLFRAC = 1.0, 1e-9, 0.3, 3.0, 0.3
LAM, MU = E0 * NU / (1 - NU**2), E0 / (2 * (1 + NU))  # plane stress
THETA_MIN, PNORM = np.deg2rad(20.0), 50.0  # min interior angle; p-norm aggregation exponent
V0MAX, V0MIN = 0.75 * h**2, 0.05 * h**2  # element-volume bounds, scaled from edge length 1
MOVE_BOUND, TOL, ITERS = 2.0 * h, 1e-6 * L, 400  # node move bound; tolerance; iterations
PSTAR, BETA, GAMMA, BETA_MIN = 700.0, 2e-4, 0.997, 1e-4  # perimeter target and barrier schedule

# --8<-- [start:bracket]
plate = lambda size: jno.shape.rect(0, 0, L, H, size=size) - jno.shape.disk(*HOLES[0], R) - jno.shape.disk(*HOLES[1], R)
rim = lambda x, y: sum(jnp.hypot(x - cx, y - cy) < R + 1e-3 for cx, cy in HOLES) > 0  # on a bolt hole


def fixed(d):
    """The non-designable cells of domain d: the deck along the top and a washer ring around each bolt."""
    cx, cy = np.asarray(d.mesh.points)[np.asarray(d.mesh_connectivity["triangles"])][..., :2].mean(axis=1).T
    return (cy > H - SKIN) | (sum(np.hypot(cx - hx, cy - hy) < R + WASHER for hx, hy in HOLES) > 0)


def bracket(d, density, penal, physical=None):
    """The SIMP bracket on domain d: bolted through the holes, a deck load rising along the top.
    Returns the density parameter, the compliance C = a(u, u) and the FEM problem."""
    x, y, _ = d.variable("interior", split=True)
    xb, yb, _ = d.variable("bolts", where=rim, split=True)
    xt, yt, _ = d.variable("deck", where=lambda x, y: y > H - TOL, split=True)
    u = d.unknown.vector(2)
    v = u.test()
    rho = jno.np.parameter(d.unknown.scalar(space="P0", name="r").test(), name="rho").initialize(density)
    rho.dtype(jnp.float64)
    if physical:
        rho.constrain(physical)  # the physics sees the physical density
    eps = lambda w: jno.np.symgrad(w, [x, y])
    a = lambda p, q: LAM * jno.np.trace(p) * jno.np.trace(q) + 2 * MU * jno.np.inner(p, q, n_contract=2)
    E = EMIN + rho**penal * (E0 - EMIN)  # SIMP
    q = (1 + 2 * xt / L) / (2 * L)  # downward pressure rising linearly from 1 to 3 along the deck, unit resultant
    fem = jno.fem([E * a(eps(u), eps(v)), u(xb, yb) - (0.0, 0.0), q * v.bind(x=xt, y=yt)[1]], quad_degree=2)
    return rho, (E * a(eps(u), eps(u))).integrate(fem).name("C"), fem


# --8<-- [end:bracket]


d = plate(h).domain()
pts0 = np.asarray(d.mesh.points)[:, :2]
cells = np.asarray(d.mesh_connectivity["triangles"])

# design variables 2 and 3: the interior node coordinates, each free within MOVE_BOUND of where it started;
# the outline and the hole rims stay put
inside = lambda x, y: (x > TOL) & (x < L - TOL) & (y > TOL) & (y < H - TOL) & ~rim(x, y)
xm, ym, _ = d.variable("mv", where=inside, split=True)
mesh_x, mesh_y = xm.trainable(name="mesh_x"), ym.trainable(name="mesh_y")  # before jno.fem(...)
ids = np.flatnonzero(np.asarray(inside(*pts0.T)))
for p, axis in ((mesh_x, 0), (mesh_y, 1)):
    x0 = pts0[ids, axis]
    p.optimizer(
        jno.optimizers.mma(move=0.02, lower=x0 - MOVE_BOUND, upper=x0 + MOVE_BOUND, move_gamma=0.9985, move_min=0.001)
    )

# design variable 1: one density per element; the deck and a washer ring around each bolt are solid
penal = jno.np.parameter((1,), name="penal").initialize(lambda k, sh, dtype=None: jnp.full(sh, PENAL))
penal.dtype(jnp.float64)
penal.optimizer(optax.sgd(1.0))  # a runtime parameter, so the continuation can raise it without a recompile
solid = jnp.asarray(fixed(d))
patch = d.patch_filter()  # eq. (17)-(19): no one-node connections, no lone dense elements
physical = lambda r: jnp.where(solid, 1.0, patch(r))
rho, compliance, fem = bracket(d, jax.nn.initializers.constant(VOLFRAC), penal, physical)
rho.optimizer(jno.optimizers.mma(move=0.15, lower=1e-3, upper=1.0, move_gamma=0.9985, move_min=0.0075))

# constraints: volume, and the mesh staying valid while its nodes move (eq. 24, 26, 28)
cellv, angles, rho_e = d.cell_volume(), d.cell_angles(), rho.reshape(-1)
volume = (rho_e * cellv).sum / (VOLFRAC * cellv.sum)
g_ang = ((2 * jnp.pi - angles) / (2 * jnp.pi - THETA_MIN)).reshape(-1).pnorm(PNORM, normalize=True)
g_vmx = (cellv / ((2.0 - rho_e) * V0MAX)).pnorm(PNORM, normalize=True)
g_vmn = ((2 * V0MAX - cellv) / (2 * V0MAX - V0MIN)).pnorm(PNORM, normalize=True)

# perimeter control, an interior penalty -beta log(P* - P) whose weight decays (eq. 38-41)
perim = rho.perimeter(zeta=0.1)
beta = jno.np.parameter((1,), name="beta").initialize(lambda k, sh, dtype=None: jnp.full(sh, BETA))
beta.dtype(jnp.float64)
beta.optimizer(optax.sgd(1.0))
frames = jno.callbacks.snapshot([rho, mesh_x, mesh_y], every=2)  # the design, for the animation
callbacks = [
    jno.optimizers.simp_continuation(penal, rho, physical=patch, every=25, watch=0),
    jno.optimizers.geometric_decay(beta, GAMMA, start=BETA, minimum=BETA_MIN),
    frames,
]

terms = [compliance, (beta[0] * perim.log_barrier(PSTAR)).name("R")]
terms += [jno.le(volume, 1.0), jno.le(g_ang, 1.0), jno.le(g_vmx, 1.0), jno.le(g_vmn, 1.0)]
crux = jno.core(terms)
crux.solve(ITERS, callbacks=callbacks)

rho_f = np.ravel(crux.eval([rho]))  # the physical density
pts_f = pts0.copy()
pts_f[ids, 0], pts_f[ids, 1] = (np.ravel(crux.eval([p])) for p in (mesh_x, mesh_y))
C, P = (float(np.ravel(crux.eval([q]))[0]) for q in (compliance, perim))
vol = np.ravel(crux.eval([cellv]))

# reanalysis: the same density on a clean mesh twice as fine, calibrated against a uniform density
# (no design, no distortion), whose gap between the two meshes is pure discretisation
clean = lambda size, dens: bracket(plate(size).domain(), dens, PENAL)[1]
d_ref = plate(h / 2).domain()
rho_ref = d.transfer_cell_field(rho_f, d_ref, points=pts_f, outside=1e-3)  # points= -> deformed source
rho_ref = np.where(fixed(d_ref), 1.0, rho_ref)  # the deck and washers are solid on any mesh
uniform = jax.nn.initializers.constant(VOLFRAC)
C_ref, C_u_coarse, C_u_fine = (
    float(np.ravel(jno.core([c]).eval([c]))[0])
    for c in (
        bracket(d_ref, lambda k, sh, dtype=None: jnp.asarray(rho_ref).reshape(sh), PENAL)[1],
        clean(h, uniform),
        clean(h / 2, uniform),
    )
)
discretisation = C_u_fine / C_u_coarse
excess = (C_ref / C) / discretisation - 1.0  # what the node movement bought that was not real

print(
    f"\nBracket: {len(cells)} elements, {fem.dofs} dofs, {ITERS} iterations"
    f"\n  compliance (own deformed mesh)          = {C:9.4f}"
    f"\n  compliance (clean mesh, {len(d_ref.mesh_connectivity['triangles'])} elements) = {C_ref:9.4f}   raw gap {100 * (C_ref - C) / C:+.1f} %"
    f"\n  control, uniform density, no distortion = {C_u_coarse:9.4f} -> {C_u_fine:9.4f}   ({100 * (discretisation - 1):+.1f} % is pure discretisation)"
    f"\n  => stiffness over-report attributable to the moved nodes: {100 * excess:+.1f} %"
    f"\n  perimeter P = {P:.3f} against target P* = {PSTAR:.1f}"
    f"\n  volume fraction = {np.sum(rho_f * vol) / np.sum(vol):.4f}   M_nd = {4 * np.mean(rho_f * (1 - rho_f)):.4f}   inverted elements = {int((vol <= 0).sum())}"
)
assert P < PSTAR  # the barrier kept the perimeter under its bound
assert np.sum(rho_f * vol) / np.sum(vol) < VOLFRAC * 1.05  # volume constraint respected
assert int((vol <= 0).sum()) == 0  # the geometric constraints kept every element valid
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    raw = jnp.asarray([f[0] for f in frames.frames])
    design = np.array([np.ravel(physical(r)) for r in raw])
    moved = np.repeat(pts0[None], len(frames.frames), 0)
    moved[:, ids, 0], moved[:, ids, 1] = (np.array([f[k] for f in frames.frames]) for k in (1, 2))
    np.savez_compressed(
        Path(out) / "topology_optimisation_bracket.npz",
        cells=cells,
        points=moved.astype(np.float32),
        density=design.astype(np.float32),
        every=frames.every,
        box=np.array([L, H, C, P]),
        holes=np.array([[*c, R] for c in HOLES]),
    )
    np.savez_compressed(
        Path(out) / "topology_optimisation_design.npz", pts=pts_f, cells=cells, rho_e=rho_f
    )  # for the reanalysis script
