# %% [markdown]
# # Where do particles go in a storm-relative squall line?
#
# The [KiD-A GATE squall line](https://github.com/Adehill/KiD-A/blob/dcaf19a592942e7858c6f47fdba3591590e2c532/namelists/SQUALL_2D.nml)
# combines a convective core, upper stratiform ascent and lower stratiform
# descent. Release three groups of coarse particles in the same section and
# supply fine aerosol in the incoming air. Follow the coarse groups and
# close a material budget for both populations.
#
# ## Define the storm section and releases
#
# Use a 240 km by 12 km section, 10 m thick. Resolve the core and
# stratiform branches with 3 km by 250 m cells. For a 20-minute excerpt of
# the steady storm, prescribe 10⁶ fine particles per kg of incoming dry air.
# Each fine particle carries 10⁻¹⁸ kg of material. The resolved coarse
# particles follow the local wind with an illustrative 1 m/s downward slip.

# %%
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style as mplstyle
from particula import plotting  # noqa: F401
from particula.coupling.flow_replay import GridReplay
from particula.coupling.grid import FlowGrid
from particula.coupling.grid_inventory import InventoryLayout
from particula.coupling.grid_run import GridRun, Release
from particula.coupling.kid import KidFlow
from particula.dynamics.parcel_motion import Particle
from particula.flow.kinematic.kid_squall import KidSquallLine


def experiment(device="cpu"):
    """Initialize the open storm section and its three particle releases."""
    field = KidSquallLine()
    grid = FlowGrid(
        (80, 1, 48),
        ((0, field.width), (0, 10), (0, field.depth)),
        ("open", "open", "closed", "closed", "deposit", "closed"),
    )
    times = np.arange(0, 1201, 60.0)
    replay = GridReplay.record(
        grid, KidFlow(field), times, provenance="KiD-A 605, dcaf19a5"
    )
    xyz = np.array([[40000.0, 5, 1500], [120000.0, 5, 75], [239500.0, 5, 4750]])
    mass = 1e-9
    groups = []
    for label, pos in zip(
        ["Core", "Near surface", "Downstream"], xyz, strict=True
    ):
        cell = np.ravel_multi_index(
            np.floor(pos / grid.spacing).astype(int), grid.shape
        )
        particle = Particle(
            label, str(cell), tuple(pos), 50e-6, 1900, 1000, (mass,), 0
        )
        groups.append(Release(particle, 1.0))
    layout = InventoryLayout((), ("fine",), ("dust",))
    run = GridRun(
        replay,
        layout,
        np.zeros((len(grid.volume), 2)),
        releases=groups,
        device=device,
        inlet_mixing_ratio=np.array([1e6, 1e-12]),
    )
    return run, field


def simulate(device="cpu"):
    """Advect imported aerosol and three resolved coarse-particle releases."""
    run, field = experiment(device)
    paths = [run.snapshot()["world"]]
    rows = []
    initial = sum(r.particle.count * r.particle.masses[0] for r in run.releases)
    for _ in run.forcing.frames:
        run.advance()
        paths.append(run.snapshot()["world"])
        b = run.budget()
        rows.append(
            [
                b["imports"][1],
                b["state"][1] + b["airborne"][2],
                b["deposited"][2],
                b["exports"][1] + b["escaped"][2],
            ]
        )
    rows = np.asarray(rows)
    east = np.arange(0, field.width + 1, 3000.0)
    up = np.arange(0, field.depth + 1, 250.0)
    x, z = np.meshgrid(east, up)
    pts = np.column_stack([x.ravel(), np.zeros(x.size), z.ravel()])
    residual = initial + rows[:, 0] - rows[:, 1:].sum(axis=1)
    return {
        "reference": "Adehill/KiD-A dcaf19a592942e7858c6f47fdba3591590e2c532, SQUALL_2D.nml",
        "east_m": east.tolist(),
        "height_m": up.tolist(),
        "wind_m_s": field.velocity(pts, 0)[:, 2].reshape(z.shape).tolist(),
        "time_s": [frame.end for frame in run.forcing.frames],
        "paths_m": np.array(paths).tolist(),
        "budget_kg": rows.tolist(),
        "initial_kg": initial,
        "max_residual_kg": float(np.max(abs(residual))),
        "resolved_count_by_fate": [
            b[k][0] for k in ["airborne", "deposited", "escaped"]
        ],
    }


# %% [markdown]
# ## Compare particle paths with imported and exported material
#
# At each output time, add fine and coarse material in each fate. The
# difference between the released plus imported mass and the three final
# reservoirs measures numerical closure. The colored section shows the
# air's vertical wind before particle slip is applied.


# %%
@mplstyle.context("particula.default")
def plot_results(report):
    """Overlay paths on the storm and show the coupled aerosol budgets."""
    fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
    section = axes[0].pcolormesh(
        np.asarray(report["east_m"]) / 1000,
        np.asarray(report["height_m"]) / 1000,
        report["wind_m_s"],
        cmap="RdBu_r",
        vmin=-3,
        vmax=3,
        shading="auto",
    )
    fig.colorbar(
        section, ax=axes[0], label="Vertical wind (m/s)", extend="both"
    )
    paths = np.asarray(report["paths_m"])
    for j, label in enumerate(["Core", "Near surface", "Downstream"]):
        axes[0].plot(
            paths[:, j, 0] / 1000, paths[:, j, 2] / 1000, ".-", label=label
        )
    axes[0].set(xlabel="East (km)", ylabel="Height (km)")
    axes[0].legend()
    for y, label in zip(
        np.asarray(report["budget_kg"]).T,
        ["Imported", "Airborne", "Deposited", "Exported"],
        strict=True,
    ):
        axes[1].plot(np.asarray(report["time_s"]) / 60, y * 1e6, label=label)
    axes[1].set(xlabel="Elapsed time (min)", ylabel="Material (mg)")
    axes[1].set_yscale("symlog", linthresh=0.1)
    axes[1].legend()
    return fig


def run_example():
    """Print resolved fates and combined mass closure and display the case."""
    report = simulate()
    print(
        "Airborne, deposited and exported coarse count:",
        report["resolved_count_by_fate"],
    )
    print("Maximum budget residual (kg):", report["max_residual_kg"])
    plot_results(report)
    plt.show()
    return report


if __name__ == "__main__":
    run_example()

# %% [markdown]
# Release location changes the fate. The core group remains aloft,
# the group near the surface deposits, and the downstream group exits
# through the east face. Inflow continuously adds fine aerosol. Move the
# downstream release toward the core to test whether it can remain airborne
# over this interval. The prescribed circulation and aerosol transport
# exclude ice microphysics and precipitation scavenging.
