import os
from pathlib import Path

# --8<-- [start:code]
"""**3-D Stokes flow** through a rectangular duct past a sphere -- creeping flow in three dimensions
on inf-sup-stable Taylor-Hood tetrahedra (P2 velocity, P1 pressure).

    -nu lap u + grad p = 0,   div u = 0

Three things worth noticing, all of them 3-D-specific:

* the **geometry is CSG** -- a box minus a sphere -- so the obstacle needs no bespoke mesh;
* the **outflow is natural**. Nothing is written for the downstream face: an untagged boundary is
  do-nothing in jNO, which is exactly the traction-free condition Stokes flow wants there. It also
  fixes the pressure LEVEL, which is why this problem needs no `p.pin()` at all -- an enclosed flow
  (every wall Dirichlet) does, and should use `p.pin(mean=True)`;
* the **drag on the sphere is read as a reaction**, not by integrating stress over its surface.
  `fem.eval(term, u)` assembles the momentum residual with no essential elimination applied, and the
  sum over the sphere's constrained DOFs is the force the fluid exerts on it -- the accurate way to
  get a force out of a finite element solution.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)

NU = 1.0  # creeping flow: the Stokes limit, no convective term at all
L, H = 1.2, 0.4  # duct length and (square) cross-section
CX, CY, CZ, R = 0.35, 0.2, 0.2, 0.1  # sphere centre and radius
U0 = 1.0  # peak inflow speed
H_MESH = 0.03

duct = jno.shape.box(0, 0, 0, L, H, H) - jno.shape.sphere(CX, CY, CZ, R)
d = duct.size(H_MESH).domain()

# The downstream face ("right") is deliberately left out of the conditions -> natural (do-nothing).
x, y, z = d.variable("interior", split=True)[:3]
inlet = d.variable("left", split=True)[:3]
walls = [d.variable(side, split=True)[:3] for side in ("bottom", "top", "front", "back")]
ball = d.variable("surface", split=True)[:3]

u = d.unknown.vector(3, order=2)  # P2 velocity
p = d.unknown.scalar(name="p")  # P1 pressure
v, q = u.test(), p.test()

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

momentum = NU * ddot(grad(u), grad(v)) - p * div(v)
inflow = U0 * 16.0 * inlet[1] * (H - inlet[1]) * inlet[2] * (H - inlet[2]) / H**4  # parabolic in both cross-stream axes

fem = jno.fem(
    [
        momentum,
        -q * div(u),
        u(*inlet)[0] - inflow,  # driven face
        u(*inlet)[1] - 0.0,
        u(*inlet)[2] - 0.0,
        *[u(*w) - 0.0 for w in walls],  # no-slip duct walls
        u(*ball) - 0.0,  # no-slip sphere
    ]
)
off = fem.offsets
print(f"3-D Stokes duct past a sphere: dofs={fem.dofs} (velocity {off[1]}, pressure {fem.dofs - off[1]})")

# A saddle system: use a direct factorization rather than the matrix-free default (fem.solve() says
# so itself if you forget). Past this size the block/Schur route in jno.precond is what scales.
sol = np.asarray(fem.solve(linear=jno.solve.lu(backend="host")))
vel = sol[off[0] : off[1]].reshape(-1, 3)
pre = sol[off[1] :]
pts = np.asarray(fem.field_points[0])

# ---- drag on the sphere, as the reaction conjugate to its no-slip constraint ----
# `fem.eval` returns the INTERNAL force at every DOF. At a constrained DOF that is the reaction --
# the force holding the sphere in place -- so the force the fluid exerts on it is its negative.
R_free = np.asarray(fem.eval(momentum, sol))  # residual with NO essential elimination applied
drag = -float(R_free[fem.region_dofs("surface", field=u, component=0)].sum())

ppts = np.asarray(fem.field_points[1])
up = (ppts[:, 0] > CX - R - 0.06) & (ppts[:, 0] < CX - R)
dn = (ppts[:, 0] > CX + R) & (ppts[:, 0] < CX + R + 0.06)
speed = np.linalg.norm(vel, axis=1)
stokes_law = 6.0 * np.pi * NU * R * U0  # the UNBOUNDED sphere, for scale only

print(f"  peak speed {speed.max():.4f}   pressure drop across the duct {pre.max() - pre.min():.2f}")
print(f"  drag on the sphere Fx = {drag:+.4f}   ({drag / stokes_law:.2f}x the unbounded Stokes-law value)")
print(f"  mean pressure upstream {pre[up].mean():+.1f} vs downstream {pre[dn].mean():+.1f}")

assert drag > 0.0 and pre[up].mean() > pre[dn].mean()  # the sphere resists, and the pressure falls across it
# The duct is only twice the sphere diameter across: a STRONGLY confined sphere, whose drag is several times
# the unbounded Stokes-law value. A sanity band, not a benchmark: the wall correction at 50% blockage is large.
assert 2.0 < drag / stokes_law < 6.0, f"drag {drag:.3f} is not a plausible confined-sphere value"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/stokes_3d_duct_sphere.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "stokes_3d_duct_sphere.npz",
        points=pts.astype(np.float32),
        velocity=vel.astype(np.float32),
        box=np.array([L, H, CX, CY, CZ, R]),
    )
