import os
from pathlib import Path

# --8<-- [start:code]
"""Coarse spaces for two-level Schwarz: rigid-body modes, where they stop being enough, and GenEO."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # Schwarz keys its entries in int64; the solves run in float64
run = jno.setup(__file__)
R, NU, E_STIFF, RHO_G = jno.shape.rect, 0.3, 1e4, 0.1
PARTS, CONTRASTS = (4, 16, 64), (1, 1e4)


def layered_block(contrast, h=0.05):
    """Plane-strain elasticity on a 4 x 1 block of four layers, clamped on the left, under its own weight; soft layers E = E_STIFF / contrast."""
    soft = E_STIFF / contrast
    d = (
        (
            R(0, 0.00, 4, 0.25).name("layer0").attach(E=E_STIFF)
            + R(0, 0.25, 4, 0.50).name("layer1").attach(E=soft)
            + R(0, 0.50, 4, 0.75).name("layer2").attach(E=E_STIFF)
            + R(0, 0.75, 4, 1.00).name("layer3").attach(E=soft)
        )
        .sized(h)
        .domain()
    )
    x, y, _ = d.variable("interior", split=True)
    left = d.variable("left", split=True)
    u = d.unknown.vector(2)
    v = u.test()
    eps, tr, ddot = (lambda w: jno.np.symgrad(w, [x, y])), jno.np.trace, (lambda a, b: jno.np.inner(a, b, n_contract=2))
    lam, mu = d.E * NU / ((1 + NU) * (1 - 2 * NU)), d.E / (2 * (1 + NU))
    fem = jno.fem([2 * mu * ddot(eps(u), eps(v)) + lam * tr(eps(u)) * tr(eps(v)) + RHO_G * v[1], u(*left) - (0.0, 0.0)])
    return fem, (x, y)


def cg_iterations(fem, precond, ref):  # every solve is checked against the sparse-direct answer
    sol = np.asarray(fem.solve(linear=jno.solve.cg(tol=1e-8, maxiter=5000), precond=precond))
    assert np.abs(sol - ref).max() < 1e-5 * np.abs(ref).max()
    return fem.stats["linear_iterations"]["total"]


its = {}
for contrast in CONTRASTS:
    fem, (x, y) = layered_block(contrast)
    ref = np.asarray(fem.solve(linear=jno.solve.lu()))
    rigid = [(1, 0), (0, 1), (-y, x)]  # the 2-D rigid-body modes: two translations, one rotation
    for p in PARTS:
        S = jno.precond.schwarz(parts=p, coarse=False)  # one level: local solves on p METIS subdomains
        Q = jno.precond.coarse(rigid, parts=S)  # the same vectors, cut to S's subdomains
        G = jno.precond.coarse(jno.space.geneo(), parts=S)  # computed from S's subdomains by local eigenproblems
        its[contrast, "one-level", p] = cg_iterations(fem, S, ref)
        its[contrast, "rigid", p] = cg_iterations(fem, Q >> S >> Q, ref)  # balancing Neumann-Neumann
        its[contrast, "geneo", p] = cg_iterations(fem, G >> S >> G, ref)
    print(f"contrast {contrast:g}  ({fem.dofs} dofs): CG iterations to 1e-8")
    for name in ("one-level", "rigid", "geneo"):
        print(f"  {name:10s}" + "".join(f"  parts={p:<3d} {its[contrast, name, p]:4d}" for p in PARTS))

for c in CONTRASTS:  # rigid modes keep the count from growing with the subdomains
    assert its[c, "rigid", 64] < 0.6 * its[c, "one-level", 64]
assert (
    its[1, "rigid", 64] < 1.5 * its[1, "rigid", 4] and its[1e4, "rigid", 64] > 2 * its[1, "rigid", 64]
)  # but the contrast stays
for p in PARTS:  # GenEO closes the gap: the contrast costs almost nothing
    assert its[1e4, "geneo", p] < 0.6 * its[1e4, "rigid", p] and its[1e4, "geneo", p] < 1.3 * its[1, "geneo", p]
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    # The figures follow the CG iterates e_k = u_k - u_ref of the three preconditioners at the last contrast and
    # the most subdomains: `truncate=True` returns iterate k of a solve stopped after k steps.
    import jax.numpy as jnp

    ref = np.asarray(fem.solve(linear=jno.solve.lu())).ravel()
    S = jno.precond.schwarz(parts=PARTS[-1], coarse=False)
    Q, G = jno.precond.coarse(rigid, parts=S), jno.precond.coarse(jno.space.geneo(), parts=S)
    A = fem.operator[0]
    names, specs = ("one-level", "rigid", "geneo"), (S, Q >> S >> Q, G >> S >> G)
    k_max = max(its[CONTRASTS[-1], n, PARTS[-1]] for n in names)
    ks = np.concatenate([[0], np.unique(np.round(np.geomspace(1, k_max, 48)).astype(int))])

    def iterate(spec, k):  # CG from zero, stopped after k steps (or where it converges)
        if k == 0:
            return np.zeros_like(ref)
        return np.asarray(fem.solve(linear=jno.solve.cg(tol=1e-8, maxiter=int(k), truncate=True), precond=spec)).ravel()

    errs = {n: [iterate(sp, k) - ref for k in ks] for n, sp in zip(names, specs)}
    A_norm = lambda e: float(np.sqrt(e @ np.asarray(A @ jnp.asarray(e))))
    mag = lambda e: np.hypot(e[0::2], e[1::2])  # DOFs interleave (u_x, u_y) per node
    np.savez_compressed(
        Path(out) / "coarse_spaces_layered_elasticity.npz",
        points=np.asarray(fem.points),
        cells=np.asarray(fem.mesh.cells_dict["triangle"]),
        part=np.asarray(S._pattern.part)[0::2],
        n_parts=PARTS[-1],
        ks=ks,
        names=np.array(names),
        iterations=np.array([its[CONTRASTS[-1], n, PARTS[-1]] for n in names]),
        u_ref=ref.reshape(-1, 2),
        err_mag=np.array([[mag(e) for e in errs[n]] for n in names], dtype=np.float32),
        err_energy=np.array([[A_norm(e) for e in errs[n]] for n in names]),
    )
