# %% [markdown]
# # Where does the Hawaiian shower lift air as it intensifies?
#
# The [KiD-A workshop](https://adehill.github.io/KiD-A/) provides a rising
# Hawaiian shower, a circulating marine cloud and a warm-rain column. Their
# prescribed winds let us compare cloud microphysics under repeatable
# forcing. Here we isolate the lift itself. The Hawaiian shower strengthens
# in its existing core, the marine cloud spins up over ten minutes and the
# column stops after one ascent pulse.
#
# ## Sample the prescribed winds
#
# Draw a vertical section through the 9 km shower. At the beginning, peak
# and final stage, multiply w by the initialized reference density to obtain
# vertical mass flux. Sample the two other cases over the same clock to
# see how different wind histories can deliver similar or different lifts.

# %%
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style as mplstyle
from particula import plotting  # noqa: F401
from particula.flow.kinematic.kid import (
    HawaiianCumulus,
    KidColumn,
    KidStratocumulus,
)


def simulate():
    """Return vertical sections and the workshop's independent wind histories."""
    cu = HawaiianCumulus()
    east = np.arange(0, 9001, 150.0)
    up = np.arange(0, 3001, 100.0)
    x, z = np.meshgrid(east, up)
    points = np.column_stack([x.ravel(), np.zeros(x.size), z.ravel()])
    stages = [0, 1500, 2400]
    flux = [
        cu.velocity(points, t)[:, 2].reshape(x.shape) * cu.profile.density(z)
        for t in stages
    ]
    sample_t = np.arange(0, 2401, 30.0)
    eddy = KidStratocumulus()
    return {
        "time_s": sample_t.tolist(),
        "east_m": east.tolist(),
        "height_m": up.tolist(),
        "stages_s": stages,
        "vertical_flux_kg_m2_s": [section.tolist() for section in flux],
        "column_m_s": KidColumn().history().velocity(sample_t).tolist(),
        "eddy_m_s": [
            eddy.velocity([[375.0, 0, 750.0]], t)[0, 2] for t in sample_t
        ],
        "reference": "Adehill/KiD-A dcaf19a592942e7858c6f47fdba3591590e2c532, cases 101, 601, 650",
    }


# %% [markdown]
# ## Locate the mass flux and time the ascent
#
# Use a common scale across the three shower sections. Compare the vertical
# wind at the center of the marine cloud's rising branch with the W2 column.
# The section color is mass flux, while the time series reports wind speed.


# %%
@mplstyle.context("particula.default")
def plot_results(report):
    """Plot comparable shower sections, and the column and marine wind clocks."""
    fig, axes = plt.subplots(2, 2, figsize=(9, 6), layout="constrained")
    for ax, t, f in zip(
        axes.flat,
        report["stages_s"],
        report["vertical_flux_kg_m2_s"],
        strict=False,
    ):
        img = ax.pcolormesh(
            np.asarray(report["east_m"]) / 1000,
            np.asarray(report["height_m"]) / 1000,
            f,
            vmin=0,
            vmax=8,
            cmap="viridis",
            shading="auto",
        )
        ax.set(
            title=f"Hawaiian shower at {t / 60:g} min",
            xlabel="East (km)",
            ylabel="Height (km)",
        )
    fig.colorbar(
        img,
        ax=[axes[0, 0], axes[0, 1], axes[1, 0]],
        label="Vertical mass flux (kg m⁻² s⁻¹)",
    )
    ax = axes[1, 1]
    t = np.asarray(report["time_s"]) / 60
    ax.plot(t, report["column_m_s"], label="Warm-rain column")
    ax.plot(t, report["eddy_m_s"], label="Marine eddy")
    ax.set(xlabel="Elapsed time (min)", ylabel="Vertical wind (m/s)")
    ax.legend()
    return fig


def run_example():
    """Compute, summarize and display the workshop cases."""
    report = simulate()
    print(
        "Shower peak mass flux by stage (kg/m²/s):",
        [round(float(np.max(f)), 2) for f in report["vertical_flux_kg_m2_s"]],
    )
    plot_results(report)
    plt.show()
    return report


if __name__ == "__main__":
    run_example()

# %% [markdown]
# The prescribed shower core carries 1, 8 and 2 kg/m²/s at the three
# times, with its crest at 1.7 km. The prescribed wind is uniform
# in the northward direction. The W2 column peaks after five
# minutes and ends as the marine case begins spinning up. Change the marine
# peak parameter from 0.25 to 1 m/s to compare the workshop's strong case.
# For the source equations, density conventions and staggered references, see
# the [KiD-A case derivation](../../../../theory/dynamics/kid-cloud-forcing.md).
