"""Drag, lift and pressure drop for the DFG 2D-1 cylinder (Scientific ML Studio, section 13.11).

Reads the network a Studio script trained and compares it with the benchmark:

    python cylinder_forces.py flow_past_a_cylinder.py model.pt

The problem is solved in nondimensional form: lengths over the diameter
D = 0.1, velocities over the mean inflow U = 0.2, pressure over rho*U**2 = 0.04,
so Re = U*D/nu = 20 and the cylinder is a circle of radius 0.5 at (2, 2) in a
22 x 4.1 channel.  The network's outputs are u1 = u, u2 = v, u3 = p.

Force on the cylinder, per unit depth, with n the unit normal pointing from the
cylinder into the fluid and the benchmark's stress sigma = (1/Re) grad(u) - p I:

    F = integral over the rim of sigma . n ds
    C_D = 2 F_x,  C_L = 2 F_y           (nondimensional F, since C = 2F/(rho U^2 D))
    dp  = 0.04 * (p(1.5, 2) - p(2.5, 2))   (front and back of the cylinder, in the benchmark's units)

Reference values: FEATFLOW, DFG benchmark 2D-1.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import math
import sys
from pathlib import Path

import torch

REFERENCE = {"C_D": 5.57953523384, "C_L": 0.010618948146, "dp": 0.11752016697}
RE = 20.0
CENTRE = (2.0, 2.0)
RADIUS = 0.5
PRESSURE_SCALE = 0.04          # rho * U_mean**2 in the benchmark's units
H = 4.1                        # channel height (nondimensional)


def load(script: Path, checkpoint: Path):
    """Import the generated script as a module and load the trained weights into its network."""
    spec = importlib.util.spec_from_file_location("studio_script", script)
    module = importlib.util.module_from_spec(spec)
    sys.argv = [str(script)]                       # the script parses its own arguments only in main()
    spec.loader.exec_module(module)
    state = torch.load(checkpoint, map_location="cpu", weights_only=False)
    module.net.load_state_dict(state["model"] if "model" in state else state)
    module.net.to("cpu").eval()
    return module.net


def outputs_and_gradients(net, pts: torch.Tensor):
    pts = pts.clone().requires_grad_(True)
    out = net(pts)
    grads = [torch.autograd.grad(out[:, k].sum(), pts, retain_graph=True)[0] for k in range(3)]
    return out.detach(), [g.detach() for g in grads]


def forces(net, n: int = 4000) -> tuple[float, float]:
    theta = (torch.arange(n, dtype=torch.float32) + 0.5) * (2 * math.pi / n)
    nx, ny = torch.cos(theta), torch.sin(theta)
    pts = torch.stack([CENTRE[0] + RADIUS * nx, CENTRE[1] + RADIUS * ny], dim=1)
    out, (gu, gv, _gp) = outputs_and_gradients(net, pts)
    p = out[:, 2]
    # sigma . n with sigma = (1/Re) grad(u) - p I  (rows: x and y momentum)
    tx = (gu[:, 0] * nx + gu[:, 1] * ny) / RE - p * nx
    ty = (gv[:, 0] * nx + gv[:, 1] * ny) / RE - p * ny
    ds = 2 * math.pi * RADIUS / n
    return float(tx.sum() * ds), float(ty.sum() * ds)


def pressure_drop(net) -> float:
    with torch.no_grad():
        p = net(torch.tensor([[1.5, 2.0], [2.5, 2.0]]))[:, 2]
    return float(p[0] - p[1]) * PRESSURE_SCALE


def flow_rate(net, x: float, n: int = 2000) -> float:
    """Volume flux through the vertical line at x; 4.1 at every x for the exact solution."""
    y = (torch.arange(n, dtype=torch.float32) + 0.5) * (H / n)
    with torch.no_grad():
        u = net(torch.stack([torch.full_like(y, x), y], dim=1))[:, 0]
    # A line through the cylinder crosses solid: the network is unconstrained
    # there, so only the fluid part of the line counts.
    fluid = (x - CENTRE[0]) ** 2 + (y - CENTRE[1]) ** 2 > RADIUS ** 2
    return float(u[fluid].sum() * H / n)


def no_slip(net, n: int = 2000) -> float:
    """Largest speed the network gives on the cylinder and the walls (0 for the exact solution)."""
    theta = torch.linspace(0, 2 * math.pi, n)
    rim = torch.stack([CENTRE[0] + RADIUS * torch.cos(theta), CENTRE[1] + RADIUS * torch.sin(theta)], dim=1)
    x = torch.linspace(0, 22, n)
    walls = torch.cat([torch.stack([x, torch.zeros_like(x)], 1), torch.stack([x, torch.full_like(x, H)], 1)])
    with torch.no_grad():
        out = net(torch.cat([rim, walls]))
    return float(torch.sqrt(out[:, 0] ** 2 + out[:, 1] ** 2).max())


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("script", type=Path, help="the script the Studio generated")
    ap.add_argument("checkpoint", type=Path, nargs="?", default=Path("model.pt"))
    ap.add_argument("--json", type=Path, help="also write the numbers to this file")
    args = ap.parse_args()

    net = load(args.script, args.checkpoint)
    fx, fy = forces(net)
    got = {"C_D": 2 * fx, "C_L": 2 * fy, "dp": pressure_drop(net)}

    print(f"{'quantity':<10}{'PINN':>14}{'reference':>14}{'error':>10}")
    for key, ref in REFERENCE.items():
        err = abs(got[key] - ref) / abs(ref)
        print(f"{key:<10}{got[key]:>14.5f}{ref:>14.5f}{100 * err:>9.1f}%")
    print()
    print("Checks that need no reference:")
    for x in (0.0, 2.0, 10.0, 22.0):
        print(f"  flow rate at x = {x:>4g}: {flow_rate(net, x):.4f}   (exact 4.1)")
    print(f"  largest speed on the cylinder and walls: {no_slip(net):.2e}   (exact 0)")

    if args.json:
        args.json.write_text(json.dumps({"pinn": got, "reference": REFERENCE,
                                         "flow_rate": {str(x): flow_rate(net, x) for x in (0.0, 2.0, 10.0, 22.0)},
                                         "max_wall_speed": no_slip(net)}, indent=2))


if __name__ == "__main__":
    main()
