# %% [markdown]
# # Which particles reach the surface beneath a cloud eddy?
#
# Release an air marker and two sizes of unit-density spheres together
# at 150 m in the descending branch of the VOCALS kinematic eddy. Keep
# their material, initial position and wind identical. Repeat with a
# specified horizontal and vertical eddy diffusivity. Compare the fate
# of an initially narrow release, counting a surface hit at first contact.
# [Stratocumulus circulation](../../../theory/dynamics/stratocumulus-eddy.md)
#
# ## Define the settling and spread controls
#
# Calculate a constant terminal slip for each sphere from drag at a
# reference air density of 1.2 kg/m³ and viscosity of 1.8e-5 Pa s.
# The 10 and 50 µm radii permit a continuum slip factor of unity for
# this comparison. The zero-slip marker follows the resolved cell wind.
# First test the stochastic increments in a uniform wind, where the
# predicted horizontal variance after time t is 2Kt.

# %%
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.flows import DirectionalMixing, UniformFlow
from particula.coupling.grid_inventory import InventoryLayout
from particula.coupling.grid_run import GridRun, Release
from particula.coupling.particle_dispersion import ParticleDispersion
from particula.dynamics.parcel_motion import Particle
from particula.particles.properties.settling_velocity import (
    get_particle_settling_velocity_with_drag,
)

LABELS = ["Air marker", "10 µm radius", "50 µm radius"]
RADII = np.array([1e-6, 10e-6, 50e-6])
LAYOUT = InventoryLayout(("passive gas",))
TIMES = np.arange(0, 601, 30)


def run_particles(grid, flow, times, k, position, cell, slips, n, device):
    """Return height, spread and surface fates of equal-weight records."""
    replay = GridReplay.record(
        grid,
        flow,
        times,
        DirectionalMixing((k, 0, k)),
        device=device,
        provenance="settling and specified physical-space diffusion",
    )
    releases = []
    for group, slip in enumerate(slips):
        radius = RADII[group]
        mass = 4 * np.pi / 3 * radius**3 * 1000
        for i in range(n):
            grain = Particle(
                f"{group}-{i}", str(cell), position, radius, 1000, 1, (mass,), 0
            )
            releases.append(Release(grain, slip))
    run = GridRun(
        replay,
        LAYOUT,
        np.zeros((len(grid.volume), 1)),
        releases=releases,
        dispersion=ParticleDispersion(281, 1) if k else None,
        device=device,
    )
    height, spread, deposited = [], [], []
    for i in range(len(times)):
        if i:
            run.advance()
        snap = run.snapshot()
        heights = snap["world"][:, 2].reshape(-1, n)
        x = snap["world"][:, 0].reshape(-1, n)
        status = snap["status"].reshape(-1, n)
        assert np.all((status == 1) | (status == 2))
        height.append(heights.mean(axis=1).tolist())
        spread.append(x.var(axis=1, ddof=1).tolist())
        deposited.append((status == 2).mean(axis=1).tolist())
    budget = run.budget()
    payload = budget["airborne"] + budget["deposited"]
    np.testing.assert_allclose(payload[0], len(releases))
    np.testing.assert_allclose(
        payload[2], sum(r.particle.masses[0] for r in releases), rtol=1e-11
    )
    return dict(
        mean_height_m=height,
        horizontal_variance_m2=spread,
        deposited_fraction=deposited,
    )


# %% [markdown]
# ## Compare the same releases with and without diffusion
#
# The uniform-wind control begins hundreds of metres from a wall. In
# the eddy, east and west connect periodically, the lid reflects, and the
# lower boundary collects particles. Retain deposited records at zero height
# when calculating population means. The fixed seed makes sampling error
# repeatable. The finite contact timestep sets the temporal resolution of
# diffusion-driven surface hits.


# %%
def simulate(device="cpu", n=256):
    """Measure a uniform-wind variance and two eddy deposition histories."""
    k = 3.0
    box = FlowGrid((8, 1, 8), ((0, 1500), (0, 1), (0, 1500)))
    center = box.centers[36]
    control = run_particles(
        box,
        UniformFlow((0.5, 0, 0), 289, 101500, 0.0075),
        [0, 30],
        k,
        center,
        36,
        [0],
        2048,
        device,
    )
    variance = control["horizontal_variance_m2"][-1][0]
    grid = FlowGrid(
        (32, 1, 32),
        box.bounds,
        ("periodic",) * 2 + ("closed",) * 2 + ("deposit", "closed"),
    )
    origin = (1125.0, 0.5, 150.0)
    cell = int(np.ravel_multi_index((24, 0, 3), grid.shape))
    flow = FlowFactory().get_strategy("stratocumulus_eddy")
    slips = get_particle_settling_velocity_with_drag(
        RADII[1:], 1000.0, 1.2, 1.8e-5, 1.0
    )
    slips = [0.0, *map(float, slips)]
    runs = [
        run_particles(grid, flow, TIMES, coef, origin, cell, slips, n, device)
        for coef in (0.0, k)
    ]
    return dict(
        times_s=TIMES.tolist(),
        velocity_m_s=slips,
        labels=LABELS,
        runs=runs,
        diffusivity_m2_s=k,
        control_variance_m2=variance,
        expected_variance_m2=2 * k * 30,
        records_per_group=n,
        wind_source="libcloudph++ 37967bce",
        seed=281,
    )


# %% [markdown]
# ## Read height and cumulative surface arrivals together
#
# In each column the panels use the same particles. A falling mean height
# can reflect descent in the air as well as settling. Compare the
# zero-slip markers in that column to isolate what the wind and stochastic
# trajectories contribute.


# %%
def plot_results(report):
    """Plot population-mean height and fraction collected at the surface."""
    fig, axes = plt.subplots(
        2, 2, sharex=True, sharey="row", figsize=(9, 6), layout="constrained"
    )
    time = np.array(report["times_s"]) / 60
    for col, case in enumerate(report["runs"]):
        for g, label in enumerate(report["labels"]):
            axes[0, col].plot(
                time, np.array(case["mean_height_m"])[:, g], label=label
            )
            axes[1, col].plot(time, np.array(case["deposited_fraction"])[:, g])
        axes[0, col].set_title(
            ["Resolved wind", "Wind + 3 m²/s diffusion"][col]
        )
        axes[1, col].set_xlabel("Time (min)")
    axes[0, 0].set_ylabel("Mean height (m)")
    axes[1, 0].set_ylabel("Fraction deposited")
    axes[0, 1].legend()
    return fig


def run_example(device="cpu"):
    """Run the controls and plot the measured histories."""
    result = simulate(device)
    print(
        f"Uniform-wind variance {result['control_variance_m2']:.1f} m², expected {result['expected_variance_m2']:.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]
# The surface fraction distinguishes permanent removal from reversible
# descent in the eddy. Increase the number of records to tighten the
# sampling uncertainty, and reduce the walk timestep to check sensitivity
# of first contacts. The separate gas-tracer example follows a conserved
# mixing ratio and provides the Eulerian comparison.
