import os
from pathlib import Path

# --8<-- [start:code]
"""A channel driven at a prescribed flow rate: the inlet pressure is a constant unknown.

    -Δu + ∇p = 0,  ∇·u = 0   on [0, L] x [0, H]
    u = 0 on the walls, u_y = 0 on the inlet, a do-nothing outlet,
    inlet traction -P n with P unknown, and  ∫_inlet u_x dy = Q.

Closed form (Poiseuille, unit viscosity): P = 12 Q L / H³.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the assembler builds in float64
run = jno.setup(__file__)
L, H, Q = 2.0, 1.0, 0.3

d = jno.shape.rect(0, 0, L, H).structured(n=32).domain()
x, y, _ = d.variable("interior", split=True)
xi, yi, _ = d.variable("left", split=True)  # the inlet
xw, yw, _ = d.variable("walls", where=lambda x, y: (y < 1e-9) | (y > H - 1e-9), split=True)

u = d.unknown.vector(2, order=2)  # Taylor-Hood velocity
p = d.unknown.scalar(name="p")  # and pressure
P = d.unknown.scalar(constant=True, name="P_in")  # the inlet pressure: one value
v, q, W = u.test(), p.test(), P.test()

grad = lambda w: jno.np.jacobian(w, [x, y])
div = lambda w: jno.np.trace(grad(w))
ddot = lambda a, b: jno.np.inner(a, b, n_contract=2)

fem = jno.fem(
    [
        ddot(grad(u), grad(v)) - p * div(v),  # momentum
        -q * div(u),  # continuity
        P * (-v.bind(x=xi, y=yi)[0]),  # inlet traction -P n, with n = (-1, 0)
        (u.bind(x=xi, y=yi)[0] - Q / H) * W,  # the flow rate through the inlet: an integral row
        u(xw, yw) - 0.0,  # no slip
        u(xi, yi)[1] - 0.0,  # inflow normal to the inlet
    ]
)
sol = fem.solve(linear=jno.solve.lu())  # a bordered saddle system: solve it directly

P_in = float(np.asarray(sol)[fem.blocks[fem.block_index(P)]][0])
exact = 12 * Q * L / H**3
print(f"inlet pressure P = {P_in:.12f}   Poiseuille 12 Q L / H^3 = {exact:.12f}")
assert abs(P_in - exact) < 1e-10
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    sol = np.asarray(sol)
    np.savez_compressed(
        Path(out) / "channel_flow_rate.npz",
        points=np.asarray(fem.field_points[0])[:, :2],
        velocity=sol[fem.offsets[0] : fem.offsets[1]].reshape(-1, 2),
        vertices=np.asarray(d.built_mesh.points)[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        box=np.array([L, H, Q, P_in]),
    )
