# %% [markdown]
# # How does a tracer patch follow a stratocumulus eddy?
#
# Release a passive tracer in the rising branch of the 1.5 km marine
# stratocumulus circulation of Arabas et al. (2015). Compare a zero-slip
# air marker at its center with the entire patch on two grids. The marker's
# streamline predicts when it reaches 750 m. The initial patch spans
# several streamlines, so its physical width can change even in perfectly
# steady air. Following many air markers gives a reference for that width.
# [Eddy equations and normalization](../../../theory/dynamics/stratocumulus-eddy.md)
#
# Use SI units throughout, with east, north and upward coordinates. One
# metre of northward thickness gives the vertical section a physical volume.
# The example uses a closed dry-air budget and zero unresolved mixing.
# Temperature and water vapor come from the prescribed atmospheric profile.

# %%
import matplotlib.pyplot as plt
import numpy as np
from particula.coupling import FlowFactory, FlowGrid
from particula.coupling.flow_replay import GridReplay
from particula.coupling.grid_inventory import InventoryLayout
from particula.coupling.grid_run import GridRun
from particula.dynamics.parcel import ParcelInitialState
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq, minimize_scalar

CENTER = np.array([250.0, 0.5, 500.0])
RADIUS = 150.0
PEAK_RATIO = 1e-9  # kg/kg dry air
TARGET = 750.0
TIMES = np.arange(0.0, 601.0, 60.0)
REVISION = "37967bce978ae4543066afb35dc1684aae10711c"


# %% [markdown]
# ## Time the ascent independently
#
# At a fixed streamfunction, the phase factor
# $b=\cos(2\pi x/L)\sin(\pi z/H)$ stays constant. Substituting this
# into the published vertical velocity leaves a function of height alone.
# Integrate its reciprocal from the release to 750 m, and compare with
# the crossing from Particula's parcel solver. Bracket the crossing with
# 1 s output and refine its time by solving for the trajectory endpoint.
# The published case scales its streamfunction with a nominal 0.6 m/s.
# Diagnose the maximum vertical speed separately using the density profile.


# %%
def marker_crossing(flow):
    """Return the marker's path and two independent crossing times in s."""
    eddy = flow.eddy
    z0 = CENTER[2]
    phase = np.cos(2 * np.pi * CENTER[0] / eddy.width) * np.sin(
        np.pi * z0 / eddy.depth
    )

    def reciprocal_speed(z):
        shape = np.sqrt(np.sin(np.pi * z / eddy.depth) ** 2 - phase**2)
        return eddy.profile.density(z) / (2 * eddy.nominal_speed * shape)

    reference, _ = quad(reciprocal_speed, z0, TARGET)
    aerosol = ParcelInitialState(
        np.array([70e-9]), np.array([1e7]), 0.5, 101500.0, 289.0, 0.0075
    )

    def follow(times):
        return flow.parcel_trace(
            "air-marker",
            CENTER,
            times,
            aerosol,
            provenance=f"ICMW8 paper case {REVISION}",
        )[0]

    track = follow(np.arange(TIMES[-1] + 1))
    reached = np.flatnonzero(track.xyz[:, 2] >= TARGET)[0]
    crossing = brentq(
        lambda t: follow([0, t]).xyz[-1, 2] - TARGET,
        track.time[reached - 1],
        track.time[reached],
    )
    return track.xyz[::10, ::2], crossing, reference


# %% [markdown]
# ## Follow a finite release
#
# Within 150 m of the marker, a squared cosine prescribes the initial
# tracer mixing ratio with a peak of 1 µg/kg dry air. Weight that ratio
# by local dry-air mass to obtain
# tracer mass. Use the same profile for a dense set of zero-slip markers
# and for the cells. Record dry-air face transfers at 60 s intervals and
# replay them through the grid transport runner, which takes conservative
# substeps. Calculate the patch's root-mean-square distance from its own
# center, weighting each observation by tracer mass. Retain mixing-ratio
# sections only at the three times displayed.


# %%
def patch(x, z):
    """Tracer mixing ratio (kg/kg dry air) with compact circular support."""
    distance = np.hypot(x - CENTER[0], z - CENTER[2]) / RADIUS
    return PEAK_RATIO * np.where(
        distance < 1, np.cos(0.5 * np.pi * distance) ** 2, 0
    )


def moments(points, weights):
    """Return the tracer-mass centroid and rms radial width in metres."""
    centroid = np.average(points, axis=0, weights=weights)
    variance = np.average(
        np.sum((points - centroid) ** 2, axis=1), weights=weights
    )
    return centroid, float(np.sqrt(variance))


def marker_patch(eddy):
    """Advect weighted release points for a reference without grid diffusion."""
    offsets = np.linspace(-RADIUS, RADIUS, 31)
    x, z = np.meshgrid(CENTER[0] + offsets, CENTER[2] + offsets)
    weights = patch(x, z) * eddy.profile.density(z)
    active = weights > 0
    xyz = np.column_stack(
        (x[active], np.full(active.sum(), CENTER[1]), z[active])
    )

    def wind(time, flat):
        return eddy.velocity(flat.reshape(-1, 3), time).ravel()

    track = solve_ivp(
        wind,
        (0, TIMES[-1]),
        xyz.ravel(),
        t_eval=TIMES,
        method="DOP853",
        rtol=1e-9,
        atol=1e-8,
    )
    if not track.success:
        raise RuntimeError(track.message)
    return [
        moments(row.reshape(-1, 3)[:, ::2], weights[active])[1]
        for row in track.y.T
    ]


def grid_patch(flow, n, device):
    """Replay face transfers on an n by n grid and return patch diagnostics."""
    eddy = flow.eddy
    grid = FlowGrid(
        (n, 1, n),
        ((0, eddy.width), (0, 1), (0, eddy.depth)),
        ("periodic", "periodic", "closed", "closed", "closed", "closed"),
    )
    forcing = GridReplay.record(
        grid, flow, TIMES, provenance=f"ICMW8 {REVISION}", device=device
    )
    points = grid.centers[:, ::2]
    dry_air = forcing.frames[0].dry_air_mass
    mass = dry_air * patch(*points.T)
    initial_mass = mass.sum()
    run = GridRun(
        forcing,
        InventoryLayout(("passive tracer",)),
        mass[:, None],
        device=device,
    )
    sections, widths, centroids, residuals = [], [], [], []
    for i, time in enumerate(TIMES):
        if i:
            run.advance()
            mass = run.snapshot()["state"][:, 0]
        center, width = moments(points, mass)
        centroids.append(center.tolist())
        widths.append(width)
        residuals.append(float((mass.sum() - initial_mass) / initial_mass))
        if time in (0, 300, 600):
            sections.append((mass / dry_air).reshape(n, n).T.tolist())
    return dict(
        n=n,
        width_m=widths,
        center_m=centroids,
        relative_residual=residuals,
        sections=sections,
    )


def simulate(device="cpu", resolutions=(32, 64)):
    """Compare the published field on two meshes over ten minutes."""
    flow = FlowFactory().get_strategy("stratocumulus_eddy")
    eddy = flow.eddy
    track, measured, reference = marker_crossing(flow)

    def negative_updraft(z):
        return -eddy.velocity([[eddy.width / 4, CENTER[1], z]], 0)[0, 2]

    peak = minimize_scalar(
        negative_updraft, bounds=(0, eddy.depth), method="bounded"
    )
    x = np.linspace(0, eddy.width, 65)
    xx, zz = np.meshgrid(x, np.linspace(0, eddy.depth, 65))
    cases = [grid_patch(flow, n, device) for n in resolutions]
    del cases[0]["sections"]
    return dict(
        source_revision=REVISION,
        times_s=TIMES.tolist(),
        marker_m=track.tolist(),
        crossing_s=measured,
        quadrature_s=reference,
        peak_w_m_s=float(-peak.fun),
        peak_z_m=float(peak.x),
        width_m=eddy.width,
        depth_m=eddy.depth,
        psi=eddy.streamfunction(xx, zz).tolist(),
        marker_width_m=marker_patch(eddy),
        grids=cases,
    )


# %% [markdown]
# ## Read the trajectory, spread and mass budget together
#
# Each map shows tracer mass per unit dry-air mass on the finer grid at
# the indicated time. Gray contours show streamlines. The white trail ends
# at the marker's current position. The bottom row tracks the patch width
# against the freely advected reference and checks the closed-domain mass
# budget. Initial widths can differ slightly because the two meshes and
# the freely advected markers sample the release at different locations.


# %%
def plot_results(report):
    """Render the common-time sections, physical spread and budget residual."""
    fig = plt.figure(figsize=(10, 6.7), layout="constrained")
    grid = fig.add_gridspec(2, 6, height_ratios=(1.25, 1))
    maps = [fig.add_subplot(grid[0, 2 * i : 2 * i + 2]) for i in range(3)]
    spread = fig.add_subplot(grid[1, :3])
    budget = fig.add_subplot(grid[1, 3:])
    track = np.asarray(report["marker_m"])
    width, depth = report["width_m"], report["depth_m"]
    for i, ax in enumerate(maps):
        field = 1e9 * np.asarray(report["grids"][-1]["sections"][i])
        img = ax.imshow(
            field,
            origin="lower",
            extent=(0, width, 0, depth),
            cmap="viridis",
            vmin=0,
            vmax=1,
            interpolation="nearest",
        )
        psi = np.asarray(report["psi"])
        ax.contour(
            np.linspace(0, width, psi.shape[1]),
            np.linspace(0, depth, psi.shape[0]),
            psi,
            levels=9,
            colors="0.75",
            linewidths=0.45,
        )
        segment = track[: i * 30 + 1]
        ax.plot(*segment.T, color="white", linewidth=1.5)
        ax.plot(
            *segment[-1],
            "o",
            color="white",
            markeredgecolor="black",
            markersize=5,
        )
        ax.set(
            xlabel="East (m)",
            title=f"{i * 5} min",
            xticks=[0, 750, 1500],
            yticks=[0, 750, 1500],
            xlim=(0, width),
            ylim=(0, depth),
        )
    maps[0].set_ylabel("Height (m)")
    fig.colorbar(img, ax=maps, label="µg tracer / kg dry air", shrink=0.75)
    minutes = np.array(report["times_s"]) / 60
    for case in report["grids"]:
        label = f"{case['n']} × {case['n']} grid"
        spread.plot(minutes, case["width_m"], label=label)
        budget.plot(
            minutes, np.array(case["relative_residual"]) * 1e15, label=label
        )
    spread.plot(
        minutes,
        report["marker_width_m"],
        "--",
        color="black",
        label="Marker cloud",
    )
    spread.set(xlabel="Elapsed time (min)", ylabel="RMS patch width (m)")
    budget.set(
        xlabel="Elapsed time (min)", ylabel="Relative mass residual (×10⁻¹⁵)"
    )
    spread.legend(fontsize="small")
    budget.axhline(0, linewidth=0.7, color="0.4")
    return fig


# %% [markdown]
# Run the script with Python for CPU or add `--cuda` for the published GPU
# run. The trajectory and its reference quadrature run on the host. The
# selected device evaluates the grid wind and advances the tracer field.


# %%
def run_example(device):
    """Calculate, summarize and plot the eddy comparison."""
    result = simulate(device)
    print(
        f"Marker crossing {result['crossing_s']:.4f} s; "
        f"streamline quadrature {result['quadrature_s']:.4f} s"
    )
    print(
        f"Peak vertical speed {result['peak_w_m_s']:.4f} m/s "
        f"at {result['peak_z_m']:.1f} m"
    )
    plot_results(result)
    plt.show()
    return result


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--cuda", action="store_true")
    run_example("cuda:0" if parser.parse_args().cuda else "cpu")

# %% [markdown]
# Over ten minutes, the freely advected reference widens by about 7 m.
# The 32-cell and 64-cell grids widen by about 61 and 35 m respectively.
# Refinement reduces the extra spread while both grid mass budgets close.
# The freely advected patch deforms as the wind varies across its diameter.
# Any additional broadening from the grid affects predicted exposure to
# localized vapor or aerosol, even when the domain mass balance closes.
# To explore settling, change the tracer to resolved particles and compare
# their displacement with this zero-slip marker.
