import os
from pathlib import Path

# --8<-- [start:code]
"""Two droplets, meshed as bodies in a void, touch and become one: ALE with a free surface, re-triangulated every step."""

import jax
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
RHO, ETA, SIGMA = 1.0, 1.0, 10.0  # density, viscosity, surface tension: Ohnesorge number 0.7, so the merged drop settles
R, GAP, H = 0.20, 0.02, 0.022  # two drops of radius R, rims GAP apart, element size H
DT, N_STEPS = 5e-4, 300  # 5.3 capillary times; the step the mesh survives is set by h^(3/2), not by the usual estimate
C_I, TAU_SCALE = 36.0, 1e-4  # SUPG/PSPG constants; the scale only keeps this example's recorded output
T_CAP = np.sqrt(RHO * R**3 / SIGMA)  # capillary time

cx = R + GAP / 2.0
d = (jno.shape.disk(-cx, 0, R, size=H) | jno.shape.disk(cx, 0, R, size=H)).domain(time=(0.0, N_STEPS * DT, N_STEPS + 1))
x, y, t = d.variable("interior", split=True)
xs, ys, ts, nx, ny = d.variable("boundary", normals=True, split=True)  # the free surface, with normals
ci = d.variable("initial", split=True)
u, p = d.unknown.vector(2, order=1, name="u"), d.unknown(order=1, name="p")  # P1/P1, stabilised
v, q = u.test(), p.test()
ub, vb, pb, qb = (w.bind(x=x, y=y, t=t) for w in (u, v, p, q))

dot, ddot = lambda a, b: jno.np.inner(a, b, n_contract=1), lambda a, b: jno.np.inner(a, b, n_contract=2)
D = lambda w: jno.np.symgrad(w, [x, y])
div = lambda w: w.x[0] + w.y[1]
c0, c1 = ub[0] - x.d(t), ub[1] - y.d(t)  # u - w, with w the mesh velocity: x.d(t) read inside the weak form
conv = lambda i: c0 * ub.x[i] + c1 * ub.y[i]  # ((u - w).grad) u_i
G = d.cell_metric
tau = jno.lag(TAU_SCALE * ((2.0 / DT) ** 2 + dot(ub, dot(G, ub)) + C_I * (ETA / RHO) ** 2 * ddot(G, G)) ** -0.5)
r0, r1 = ub.t[0] + conv(0) + pb.x / RHO, ub.t[1] + conv(1) + pb.y / RHO  # the strong residual; lap u vanishes on P1
supg = tau * ((c0 * vb.x[0] + c1 * vb.y[0]) * r0 + (c0 * vb.x[1] + c1 * vb.y[1]) * r1)

momentum = RHO * (dot(ub.t, vb) + conv(0) * vb[0] + conv(1) * vb[1]) + 2 * ETA * ddot(D(ub), D(vb)) - pb * div(vb) + supg
continuity = -qb * div(ub) - tau * (qb.x * r0 + qb.y * r1)  # PSPG: no pressure pin needed
vs = v.bind(x=xs, y=ys)
normal_derivative = lambda f, i: nx * f.x[i] + ny * f.y[i]
surface_div = vs.x[0] + vs.y[1] - nx * normal_derivative(vs, 0) - ny * normal_derivative(vs, 1)
capillary = SIGMA * surface_div  # T n = -sigma H n, integrated by parts onto the test function
us = u.bind(x=xs, y=ys).freeze(np.zeros((len(np.asarray(d.mesh.points)), 2)))  # the solved velocity, delivered each step

fem = jno.fem(
    [
        momentum,
        continuity,
        capillary,  # the traction also fixes the pressure level: no Dirichlet condition anywhere
        u(*ci) - (0.0, 0.0),  # both drops start at rest
        xs.d(ts) - us[0],  # the surface is Lagrangian: dX/dt = u
        ys.d(ts) - us[1],
    ]
)
traj = fem.solve(
    nonlinear=jno.solve.newton(direct=True),
    adapt=jno.solve.remesh(alpha=1.2, every=1),  # re-triangulate the moved nodes every step: the topology can change
)


def mesh(k):
    return np.asarray(traj.meshes[k][0]), np.asarray(traj.meshes[k][1])[:, :3]


def bodies(k):  # connected components of the triangulation
    pts, cells = mesh(k)
    ij = np.concatenate([cells[:, [0, 1]], cells[:, [1, 2]], cells[:, [2, 0]]])
    _, lab = connected_components(coo_matrix((np.ones(len(ij)), ij.T), shape=(len(pts),) * 2), directed=False)
    return np.unique(lab[np.unique(cells)]).size


def surface(k):  # the boundary edges, those that belong to one triangle only
    cells = mesh(k)[1]
    e = np.sort(np.concatenate([cells[:, [0, 1]], cells[:, [1, 2]], cells[:, [2, 0]]]), axis=1)
    u_, n = np.unique(e, axis=0, return_counts=True)
    return u_[n == 1]


def loops(k):  # closed boundary loops: one per body unless the alpha filter punched a hole
    e, n = surface(k), len(mesh(k)[0])
    _, lab = connected_components(coo_matrix((np.ones(len(e)), e.T), shape=(n, n)), directed=False)
    return np.unique(lab[np.unique(e)]).size


def shape_of(k):  # area, width, height and neck width (the height at the plane x = 0)
    pts, cells = mesh(k)
    a, b = pts[cells[:, 1]] - pts[cells[:, 0]], pts[cells[:, 2]] - pts[cells[:, 0]]
    mid = np.abs(pts[:, 0]) < 0.02
    return (
        np.abs(0.5 * np.sum(a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0])),
        np.ptp(pts[:, 0]),
        np.ptp(pts[:, 1]),
        np.ptp(pts[mid, 1]),
    )


def perimeter(k):
    pts, e = mesh(k)[0], surface(k)
    return np.linalg.norm(pts[e[:, 0]] - pts[e[:, 1]], axis=1).sum()


last = len(traj.states) - 1
print(f"{len(mesh(0)[0])} nodes, {fem.dofs} dofs, {N_STEPS} steps = {N_STEPS * DT / T_CAP:.2f} capillary times")
for k in (0, last // 4, last // 2, 3 * last // 4, last):
    area, width, height, neck = shape_of(k)
    print(
        f"  t = {float(traj.times[k]) / T_CAP:4.2f} t_cap: {bodies(k)} body(ies), area {area:.5f}, width {width:.4f}, height {height:.4f}, neck {neck:.4f}"
    )
area0, area1, merged = shape_of(0)[0], shape_of(last)[0], shape_of(last // 4)[0]
per = np.array([perimeter(k) for k in range(last + 1)])
print(
    f"{sum(h['remeshed'] for h in fem.adapt_history)} reconnections; area {area0:.5f} -> {area1:.5f} ({100 * (area1 / area0 - 1):+.2f} %)"
)
print(f"perimeter {per[0]:.4f} -> {per[-1]:.4f}; worst one-step change {100 * np.max(per[1:] / per[:-1] - 1):+.2f} %")
assert bodies(0) == 2 and bodies(last) == 1  # two meshes became one
assert shape_of(last)[3] > 0.5 * shape_of(last)[2]  # the neck opened
assert abs(shape_of(last)[1] / shape_of(last)[2] - 1) < 0.05  # and the merged drop is round
# merging adds the liquid that fills the initial gap; what the scheme owes is conservation once it has settled
assert abs(area1 / area0 - 1) < 0.05 and abs(area1 / merged - 1) < 0.01
assert all(loops(k) == bodies(k) and np.isfinite(np.asarray(traj.states[k])).all() for k in range(last + 1))  # no holes
assert (
    per[-1] < per[0] and np.max(per[1:] / per[:-1] - 1) < 0.2
)  # surface tension shrinks the surface; no wedge is bitten out
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    ks = np.arange(0, last + 1, 3)  # each frame has its own layout: node management changes the node count
    speed = lambda k: np.linalg.norm(
        np.asarray(traj.states[k])[int(traj.layouts[k]["offsets"][0]) : int(traj.layouts[k]["offsets"][1])].reshape(-1, 2),
        axis=1,
    )
    np.savez_compressed(
        Path(out) / "droplet_coalescence_ale_2d.npz",
        points=np.concatenate([mesh(k)[0] for k in ks]),
        cells=np.concatenate([mesh(k)[1] for k in ks]),
        speed=np.concatenate([speed(k) for k in ks]),
        n_points=np.array([len(mesh(k)[0]) for k in ks]),
        n_cells=np.array([len(mesh(k)[1]) for k in ks]),
        t=np.asarray(traj.times)[ks] / T_CAP,
        bodies=np.array([bodies(k) for k in ks]),
    )
