import os
from pathlib import Path

# --8<-- [start:code]
"""Rayleigh-Benard convection in a pot heated from below: the Boussinesq model, fully coupled.

    u_t + (u.grad)u = -grad p + Pr lap u + Pr Ra T e_y     (momentum + buoyancy)
    div u = 0
    T_t + u.grad T = lap T                                  (heat)

Velocity (P2), pressure (P1) and temperature (P1) in one jno.fem. No slip on the walls, a hot floor and a cold
lid with the conductive profile on the walls, and a rest state plus a small perturbation to seed the rolls.
"""

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

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
Pr, Ra = 1.0, 1.0e4  # Ra >> Ra_c ~ 1708: the layer must convect
Lx, Ly = 2.0, 1.0
dt, nsteps = 0.002, 150

d = jno.shape.rect(0, 0, Lx, Ly, size=0.03).domain(time=(0.0, nsteps * dt, nsteps + 1))
x, y, t = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
x0, y0, _ = d.variable("initial", split=True)

u = d.unknown.vector(2, order=2)  # P2 velocity  ┐ Taylor-Hood
p = d.unknown.scalar(name="p")  # P1 pressure  ┘
T = d.unknown.scalar(name="T")  # P1 temperature
v, q, s = u.test(), p.test(), T.test()

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

# the two-way coupling: buoyancy carries T into the momentum, advection carries u into the heat
momentum = dot(ddt(u), v) + dot(dot(grad(u), u), v) + Pr * ddot(grad(u), grad(v)) - p * div(v) - Pr * Ra * T * v[1]
heat = ddt(T) * s + dot(u, grad(T)) * s + dot(grad(T), grad(s))

fem = jno.fem(
    [
        momentum,
        -q * div(u),  # continuity
        heat,
        u(xb, yb) - 0.0,  # no slip
        T(xb, yb) - (1 - yb / Ly),  # hot floor, cold lid
        p.pin(),
        u(x0, y0) - 0.0,  # start at rest, with the conductive profile plus a perturbation
        T(x0, y0) - (1 - y0 / Ly + 0.05 * jno.np.sin(2 * np.pi * x0 / Lx) * jno.np.sin(np.pi * y0 / Ly)),
    ]
)
assert fem.is_transient and not fem.is_linear  # buoyancy and advection couple the fields both ways
traj = np.asarray(fem.solve(linear=jno.solve.lu()).eval())  # backward Euler + Newton per step, a direct saddle solve

pts_v, pts_T = np.asarray(fem.field_points[0]), np.asarray(fem.field_points[2])
vel = traj[:, fem.offsets[0] : fem.offsets[1]].reshape(len(traj), -1, 2)
Tf = traj[:, fem.offsets[2] :]
Tv = LinearNDInterpolator(pts_T[:, :2], Tf[-1])(pts_v[:, :2])  # T at the velocity nodes
flux = np.nanmean(vel[-1, :, 1] * Tv)  # <u_y T>: positive when hot fluid rises and cold sinks
print(
    f"Ra={Ra:g} Pr={Pr:g}: dofs={fem.dofs}, {nsteps} steps  max|u| {np.abs(vel[0]).max():.3f} (rest) -> {np.abs(vel[-1]).max():.2f}  <u_y T> = {flux:+.3f}"
)
assert np.abs(vel[-1]).max() > 1.0 and flux > 0.0  # convection onsets and carries heat upward
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "rayleigh_benard_2d.npz",
        points_T=pts_T[:, :2],
        points_v=pts_v[:, :2],
        triangles=np.asarray(d.mesh.cells_dict["triangle"]),
        T=Tf.astype(np.float32),
        velocity=vel.astype(np.float32),
        t=np.arange(len(Tf)) * dt,
        box=np.array([Lx, Ly, Ra, Pr]),
    )
