import os
from pathlib import Path

# --8<-- [start:code]
"""Electro-osmotic flow in a microchannel with patterned wall charge: ions, potential and fluid, solved together."""

import jax
import numpy as np
from scipy.interpolate import LinearNDInterpolator

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# nondimensional: lengths in the channel width H, potential in kT/e, concentrations in the bulk value, velocity in eps (kT/e)^2 / (mu H)
EPS, PE = 0.05, 0.25  # Debye length over width, Peclet number U H / D (about 0.25 for water)
ZETA, EFIELD = -2.0, 1.0  # the walls' zeta potential (about -51 mV) and the applied field E H / (kT/e)
END, PITCH, PATCHES = 0.6, 0.8, 4  # straight ends, then a stretch of 4 periods of 0.8 whose wall charge alternates
SHARP = 12.0  # how sharply the wall charge flips sign from one patch to the next
T_END, STEPS = 0.4, 64
T_ON, T_RAMP = 0.15, 0.05  # the field is switched on around t = T_ON over about T_RAMP, after the double layers have formed
H_WALL, H_MAX = 0.014, 0.06  # mesh size at the walls (3.6 cells per Debye length) and in the bulk
LENGTH = 2 * END + PATCHES * PITCH

gouy = lambda s, xp: (
    4 * xp.arctanh(np.tanh(ZETA / 4) * xp.exp(-s / EPS))
)  # Gouy-Chapman: the layer at distance s from one wall
bulk = lambda y, xp: gouy(y, xp) + gouy(1 - y, xp)  # both layers of a straight channel (they overlap by e^-10)


def electro_osmosis(length, patterned):
    """cp, cm, phi, u, p of an electrolyte between charged walls with a potential drop along them (the walls' charge
    flips from patch to patch on the bottom when `patterned`); returns the mesh and each field's nodes and values."""
    h_of = lambda x, y, z: min(H_MAX, H_WALL + 0.5 * min(y, 1 - y))
    d = jno.shape.rect(0, 0, length, 1.0).sized(h_of).domain(time=(0.0, T_END, STEPS + 1))
    x, y, t = d.variable("interior", split=True)
    ci, left, right, bottom, top = (d.variable(s, split=True) for s in ("initial", "left", "right", "bottom", "top"))
    cp, cm, phi = (d.unknown.scalar(name=n) for n in ("cp", "cm", "phi"))
    u, p = d.unknown.vector(2, order=2), d.unknown.scalar(name="p")  # Taylor-Hood: P2 velocity, P1 pressure
    q, r, psi, v, s = cp.test(), cm.test(), phi.test(), u.test(), p.test()

    grad, dot, ddot = (lambda w: jno.np.jacobian(w, [x, y])), jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
    div = lambda w: jno.np.trace(grad(w))
    # the wall charge that gives the zeta potential, and its sign pattern along the bottom wall (+1 on the ends, -1 on the odd patches)
    charge = lambda sign: 2 * EPS * jno.np.sinh(ZETA * sign / 2)
    inside = lambda xs: jno.np.minimum(jno.np.maximum(xs, END), END + PATCHES * PITCH) - END
    flip = lambda xs: jno.np.tanh(SHARP * jno.np.cos(np.pi * inside(xs) / PITCH))
    sigma_bottom = charge(flip(bottom[0]) if patterned else 1.0)
    on = lambda ts: 0.5 * (1 + jno.np.tanh((ts - T_ON) / T_RAMP))  # the applied potential drop, switched on
    drop = EFIELD * length

    flux = lambda c, sign: grad(c) + sign * c * grad(phi)  # diffusion and migration in the potential
    force = flux(cp, +1) + flux(cm, -1)  # = (cp - cm) grad(phi) + grad(cp + cm): the Coulomb force and the osmotic pressure
    nernst_planck = lambda c, sign, w: c.bind(x=x, y=y, t=t).t * w + PE * dot(u, grad(c)) * w + dot(flux(c, sign), grad(w))
    fem = jno.fem(
        [
            EPS**2 * dot(grad(phi), grad(psi)) - 0.5 * (cp - cm) * psi,  # eps^2 lap(phi) = -(cp - cm) / 2
            -sigma_bottom * psi.bind(x=bottom[0], y=bottom[1], t=bottom[2]),  # the walls' surface charge
            -charge(1.0) * psi.bind(x=top[0], y=top[1], t=top[2]),
            nernst_planck(cp, +1, q),  # cp_t + Pe u.grad(cp) = div(grad(cp) + cp grad(phi))
            nernst_planck(cm, -1, r),  # cm_t + Pe u.grad(cm) = div(grad(cm) - cm grad(phi))
            ddot(grad(u), grad(v)) - p * div(v) + dot(force, v) / (2 * EPS**2),  # Stokes
            -s * div(u),
            u(*bottom) - (0.0, 0.0),  # no slip
            u(*top) - (0.0, 0.0),
            phi(*left) - (0.5 * drop * on(left[2]) + bulk(left[1], jno.np)),  # reservoirs at both ends: equilibrium layers
            phi(*right) - (-0.5 * drop * on(right[2]) + bulk(right[1], jno.np)),  # and the potential drop
            cp(*left) - jno.np.exp(-bulk(left[1], jno.np)),
            cp(*right) - jno.np.exp(-bulk(right[1], jno.np)),
            cm(*left) - jno.np.exp(bulk(left[1], jno.np)),
            cm(*right) - jno.np.exp(bulk(right[1], jno.np)),
            cp(*ci) - 1.0,  # uniform electrolyte at rest at the start
            cm(*ci) - 1.0,
            phi(*ci) - 0.0,
            u(*ci) - (0.0, 0.0),
            p(*ci) - 0.0,
        ]
    )
    traj = np.asarray(fem.solve(nonlinear=jno.solve.newton(direct=True), linear=jno.solve.lu(backend="pardiso")).eval())
    nodes = lambda f: (np.asarray(fem.field_points[fem.block_index(f)])[:, :2], traj[:, fem.blocks[fem.block_index(f)]])
    (xy, c_p), (_, c_m), (_, pot), (xu, vel) = nodes(cp), nodes(cm), nodes(phi), nodes(u)
    return d, fem, xy, (c_p, c_m, pot), xu, vel.reshape(len(traj), -1, 2)


_, _, xy_r, (_, _, pot_r), xu_r, vel_r = electro_osmosis(2.0, False)  # a straight channel: the reference
d, fem, xy, (c_plus, c_minus, pot), xu, vel = electro_osmosis(LENGTH, True)  # the patterned channel

# the straight channel against the two classical results: Gouy-Chapman across the layer, Helmholtz-Smoluchowski along it
at = lambda nodes, f, px, py: LinearNDInterpolator(nodes, f)(px, py)
ys = np.linspace(0.0, 0.5, 101)
err_gc = abs(at(xy_r, pot_r[-1], 1.0, ys) - bulk(ys, np)).max() / abs(ZETA)  # mid-length, from the wall to the centre
e_bulk = at(xy_r, pot_r[-1], 0.5, 0.5) - at(xy_r, pot_r[-1], 1.5, 0.5)  # the bulk field
u_c, u_hs = at(xu_r, vel_r[-1, :, 0], 1.0, 0.5), -ZETA * e_bulk  # u = -eps zeta E / mu is -zeta E in these units
print(
    f"straight channel: layer within {err_gc:.1%} of zeta of Gouy-Chapman, wall potential {at(xy_r, pot_r[-1], 1.0, 0.0):.3f}"
)
print(f"  centre velocity {u_c:.4f} against Helmholtz-Smoluchowski {u_hs:.4f} (field {e_bulk:.4f}): ratio {u_c / u_hs:.3f}")
assert err_gc < 0.02 and abs(u_c / u_hs - 1) < 0.03  # the layer within 2 % of zeta, the plug flow within 3 %

# the patterned channel: the flow rate through every cross-section must be the same, and the odd patches turn the flow back
yy = np.linspace(0.0, 1.0, 201)
rate = np.array([np.trapezoid(at(xu, vel[-1, :, 0], px, yy), yy) for px in np.linspace(0.3, LENGTH - 0.3, 25)])
print(f"patterned channel, {fem.dofs} DOFs: flow rate {rate.mean():.4f}, spread {np.ptp(rate) / rate.mean():.1%} along it")
print(
    f"  reverse flow down to u = {vel[-1, :, 0].min():.3f}, peak speed {np.hypot(*vel[-1].T).max():.3f}, peak charge {0.5 * (c_plus - c_minus).max():.2f}"
)
assert np.ptp(rate) < 0.03 * rate.mean() and vel[-1, :, 0].min() < -0.1  # mass conserved; flow turns back
# --8<-- [end:code]

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

    verts = np.asarray(d.built_mesh.points)[:, :2]
    np.savez_compressed(
        Path(out) / "electro_osmotic_flow.npz",
        vertices=verts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        charge=(0.5 * (c_plus - c_minus))[:, cKDTree(xy).query(verts)[1]].astype(np.float32),
        velocity=vel[:, cKDTree(xu).query(verts)[1]].astype(np.float32),
        t=np.linspace(0.0, T_END, STEPS + 1),
        geometry=[LENGTH, END, PITCH, PATCHES, EPS, ZETA, T_ON, T_RAMP],
    )
