# %% [markdown]
# # Reconstruct the size-selective capture ceiling
#
# Ice-rich cloud samples on 4 June carried 12.26 femtograms of soot per
# detected core. If the cloud draws on the measured below-cloud population,
# what is the largest share of cores that can reach that mean? This check
# starts with the digitized Figure 3 spectrum and selects the largest cores
# first. Change the target to explore a different measured mean.

# %%
import csv
from io import TextIOWrapper
from pathlib import Path
from zipfile import ZipFile

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import brentq


def read_below_cloud():
    """Load the published below-cloud spectrum from the complete download."""
    relative = Path("website/public/study-data/arctic-soot-selection/study.zip")
    here = Path(globals().get("__file__", ".")).resolve().parent
    for start in (Path.cwd(), here):
        for parent in (start, *start.parents):
            for path in (parent / relative, parent / "study.zip"):
                if path.is_file():
                    with (
                        ZipFile(path) as archive,
                        archive.open("figure3/source-spectra.csv") as stream,
                    ):
                        table = csv.DictReader(
                            TextIOWrapper(stream, encoding="utf-8")
                        )
                        return sorted(
                            (
                                float(row["centre_nm"]),
                                float(row["mass_fraction"]),
                            )
                            for row in table
                            if row["source"] == "below"
                        )
    raise FileNotFoundError("Place study.zip beside this script.")


# %% [markdown]
# The source figure gives the fraction of soot mass in each size bin. Dividing
# by the mass of one core recovers the relative number of cores. We use a
# spherical core at each bin centre, a density of 1,800 kg/m³ and the
# instrument's 0.37–178 fg response range.

# %%
diameter_nm, mass_share = np.array(read_below_cloud()).T
core_fg = np.clip(
    np.pi / 6 * 1800 * (diameter_nm * 1e-9) ** 3 * 1e18, 0.37, 178
)
counts = mass_share / core_fg
counts /= counts.sum()
larger_count = np.cumsum(counts[::-1])[::-1] - counts
target_fg = 12.2618070767


def selected_counts(fraction):
    """Assign each incoming core once, starting with the largest bin."""
    return np.clip(fraction - larger_count, 0.0, counts)


def captured_mean(fraction):
    captured = selected_counts(fraction)
    return np.dot(captured, core_fg) / captured.sum()


# %% [markdown]
# At the limiting fraction, the captured mean equals the observed target.
# Adding any smaller cores lowers the mean. The remaining population lets us
# check both inventories against the original totals.

# %%
fraction = brentq(lambda f: captured_mean(f) - target_fg, 1e-8, 1.0)
captured = selected_counts(fraction)
remaining = counts - captured
total_mass = counts @ core_fg
captured_mass_share = (captured @ core_fg) / total_mass
assert np.isclose(captured.sum() + remaining.sum(), 1.0)
assert np.isclose(captured @ core_fg + remaining @ core_fg, total_mass)
print(f"Incoming mean: {total_mass:.2f} fg/core")
print(f"Maximum core fraction at {target_fg:.2f} fg/core: {fraction:.1%}")
print(
    f"Fraction of incoming soot mass in those cores: {captured_mass_share:.1%}"
)

# %% [markdown]
# Compare the two shares on the same scale. Selecting the largest cores can
# retain most of the soot mass while leaving most cores behind.

# %%
shares = np.array([fraction, captured_mass_share]) * 100
fig, ax = plt.subplots(figsize=(5.5, 2.2), layout="constrained")
ax.barh(["Core number", "Soot mass"], shares, color=["#246b73", "#945633"])
for row, share in enumerate(shares):
    ax.text(share + 1.2, row, f"{share:.1f}%", va="center")
ax.set(xlim=(0, 100), xlabel="Share of incoming below-cloud population (%)")
ax.invert_yaxis()
ax.spines[["top", "right"]].set_visible(False)
plt.show()

# %% [markdown]
# *Captured shares for the nominal below-cloud source, with larger cores
# selected first.* The result is an upper bound conditional on the source.
# The aircraft measured the soot in cloud particles. Measuring the fraction
# that entered those particles would let us test the bound on a tracked layer.
