# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check published values, an exact mixture and the limit of closure."""

from math import fsum, isclose
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).parents[1] / "reference"))
from rir import phase_fractions, spiked_fractions


def _close(got, expected, tol=1e-12):
    assert len(got) == len(expected)
    assert all(isclose(g, e, rel_tol=0, abs_tol=tol) for g, e in zip(got, expected, strict=True))


# Davis (1992), NIST SP 846, Table 2, reports all fractions on the spiked basis.
spike = 0.2144
measured = spiked_fractions([4661, 2298], [4.35, 2.98], [1, 1], 631, 1, spike)
_close(measured, [0.3641, 0.2620], 5e-5)
assert isclose(1 - spike - fsum(measured), 0.1595, rel_tol=0, abs_tol=5e-5)

# The measured result is close to the published estimate, with a difference
# from the weighed values (0.3443 and 0.2800) reported in the same table.
assert abs(measured[0] - 0.3443) < 0.020
assert abs(measured[1] - 0.2800) < 0.020

# Doubling the ratios for both analytes and the spike leaves their mass scale intact.
common_reference = spiked_fractions([80, 18], [4, 1.5], [0.5, 0.8], 100, 0.5, 0.25, 2)
spike_reference = spiked_fractions([80, 18], [2, 0.75], [0.5, 0.8], 100, 0.5, 0.25)
_close(common_reference, [0.1, 0.0375])
_close(common_reference, spike_reference)

# Report over-closure to the caller without truncation or normalization.
over_closed = spiked_fractions([130], [1], [1], 25, 1, 0.25)
_close(over_closed, [1.3])
assert 1 - 0.25 - fsum(over_closed) < 0

# Generate areas independently with a common gain of 1000.
weights = [0.2, 0.3, 0.5]
rirs = [4, 2, 0.5]
rel = [0.5, 1, 0.4]
areas = [1000 * w * k * r for w, k, r in zip(weights, rirs, rel, strict=True)]
_close(phase_fractions(areas, rirs, rel), weights)
_close(phase_fractions([7 * a for a in areas], rirs, rel), weights)

# An omitted phase forces closure to 100% of the included material.
_close(phase_fractions(areas[:2], rirs[:2], rel[:2]), [0.4, 0.6])
assert fsum(weights[:2]) == 0.5

for inputs in [([0], [1], [1]), ([1], [0], [1]), ([1], [1], [100])]:
    try:
        phase_fractions(*inputs)
    except ValueError:
        pass
    else:
        raise AssertionError(f"invalid inputs accepted: {inputs!r}")

print("PASS Davis Table 2 to 0.00005 mass fraction; check spike conversion, closure, gain invariance and invalid inputs")
