import os
from pathlib import Path

# --8<-- [start:code]
"""A strip footing on saturated soil: Biot consolidation in plane strain, against Terzaghi's column."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# soil, in kPa, m and days
E, NU, KAPPA = 3000.0, 0.3, 2.5e-4  # drained Young's modulus, Poisson ratio, mobility k/gamma_w (m^2/(kPa day))
Q = 150.0  # the footing pressure, switched on at t = 0 and held
WIDTH, DEPTH, FOOT = 16.0, 8.0, 2.0  # half the modelled ground, the layer, half the footing (the left edge is the axis)
lam, mu = E * NU / ((1 + NU) * (1 - 2 * NU)), E / (2 * (1 + NU))
cv = KAPPA * (lam + 2 * mu)  # Terzaghi's coefficient of consolidation
T_END, N_STEPS = 1.2 * DEPTH**2 / cv, 240  # until the column under uniform load is 99 % consolidated


def consolidate(shape, width, a):
    """u (P2) and p (P1) of saturated soil under the pressure Q on the part x < a of its top, drained there."""
    d = shape.domain(time=(0.0, T_END, N_STEPS + 1))
    x, y, t = d.variable("interior", split=True)
    ci, base, top = (d.variable(s, split=True) for s in ("initial", "bottom", "top"))
    sides = d.variable("sides", where=lambda x, y: (x < 1e-9) | (x > width - 1e-9), split=True)
    load = d.variable("load", where=lambda x, y: (y > DEPTH - 1e-9) & (x < a + 1e-9), split=True)
    u, p = d.unknown.vector(2, order=2), d.unknown.scalar(name="p")  # Taylor-Hood: P2 displacement, P1 pressure
    v, q = u.test(), p.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)
    sigma = lambda w: 2 * mu * eps(w) + lam * tr(eps(w)) * jno.np.identity(2)  # the soil skeleton's stress
    div_ut = tr(jno.np.jacobian(u.bind(x=x, y=y, t=t).t, [x, y]))  # the rate of volume change
    fem = jno.fem(
        [
            ddot(sigma(u), eps(v)) - p * tr(eps(v)),  # div(sigma - p I) = 0
            Q * v.bind(x=load[0], y=load[1])[1],  # the pressure Q on the footing, pushing down
            div_ut * q + KAPPA * dot(grad(p), grad(q)),  # d/dt div u = div(kappa grad p): Darcy, incompressible grains
            u(*sides)[0] - 0.0,  # the axis and the far edge: rollers
            u(*base) - (0.0, 0.0),  # rigid, impermeable base
            p(*top) - 0.0,  # drained at the ground surface, everywhere else sealed
            u(*ci) - (0.0, 0.0),
            p(*ci) - 0.0,
        ]
    )
    traj = np.asarray(fem.solve(linear=jno.solve.lu()).eval())
    return d, fem, traj, fem.block_index(u), fem.block_index(p)


h = lambda x, y, z: min(0.4, 0.04 + 0.08 * np.hypot(x - FOOT, y - DEPTH))  # fine at the footing's edge
d, fem, traj, iu, ip = consolidate(jno.shape.rect(0, 0, WIDTH, DEPTH).sized(h), WIDTH, FOOT)
_, femc, trajc, icu, icp = consolidate(jno.shape.rect(0, 0, 0.5, DEPTH, size=0.1), 0.5, 0.5)  # the reference column

ts = np.linspace(0.0, T_END, N_STEPS + 1)
field = lambda f, tr_, i: (np.asarray(f.field_points[i])[:, :2], tr_[:, f.blocks[i]])
(_, cu), (cpts, cp) = field(femc, trajc, icu), field(femc, trajc, icp)
(xu, uf), (xp, pf) = field(fem, traj, iu), field(fem, traj, ip)
uf = uf.reshape(len(ts), -1, 2)
cu = cu.reshape(len(ts), -1, 2)

# Terzaghi (1923): a column under uniform load, drained on top; U is the settled fraction, p_base the pressure at the sealed foot
Tv = cv * ts / DEPTH**2
M = (2 * np.arange(200)[:, None] + 1) * np.pi / 2
U_exact = 1 - (2 / M**2 * np.exp(-(M**2) * Tv)).sum(0)
p_exact = Q * (2 / M * (-1.0) ** np.arange(200)[:, None] * np.exp(-(M**2) * Tv)).sum(0)
settle_col = -cu[:, np.asarray(femc.field_points[icu])[:, 1] > DEPTH - 1e-9, 1].mean(1) / (Q * DEPTH / (lam + 2 * mu))
p_base = cp[:, cpts[:, 1] < 1e-9].mean(1)
k = [int(np.searchsorted(Tv, T)) for T in (0.05, 0.1, 0.2, 0.4, 0.8)]
centre = -uf[:, (xu[:, 0] < 1e-9) & (xu[:, 1] > DEPTH - 1e-9), 1][:, 0]  # the footing's settlement on the axis
err_U, err_p = abs(settle_col[k] - U_exact[k]).max(), abs(p_base[k] - p_exact[k]).max() / Q
print(
    f"{fem.dofs} DOFs under the footing, {femc.dofs} in the column; cv = {cv:.3f} m^2/day, {T_END:.0f} days in {N_STEPS} steps"
)
print(
    f"column against Terzaghi: settled fraction within {err_U:.4f}, base pressure within {err_p:.4f} Q; first step p/Q = {p_base[1] / Q:.4f}"
)
print(
    f"footing: first-step peak p = {pf[1].max() / Q:.3f} Q, settlement {centre[1]:.4f} m at once, {centre[-1]:.4f} m at {T_END:.0f} days"
)
assert err_U < 0.01 and err_p < 0.01 and p_base[1] > 0.99 * Q  # Terzaghi (1923), and the undrained jump p = Q
# --8<-- [end:code]

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

    verts = np.asarray(d.built_mesh.points)[:, :2]
    frames = np.unique(np.round(np.geomspace(1, N_STEPS, 150)).astype(int))
    frames = np.concatenate([[0], frames])
    np.savez_compressed(
        Path(out) / "footing_consolidation.npz",
        vertices=verts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        displacement=uf[frames][:, cKDTree(xu).query(verts)[1]].astype(np.float32),
        pressure=pf[frames][:, cKDTree(xp).query(verts)[1]].astype(np.float32),
        t=ts[frames],
        settlement=centre,
        times=ts,
        geometry=[WIDTH, DEPTH, FOOT, Q, cv],
    )
