"""AC60 independent evidence: recover a known population from synthetic catalogs.

Found O3b injections are split by index parity. Even-indexed injections become "true" detected
binaries after importance resampling to a known population (alpha, m_max) = (3.5, 70). Odd-indexed
injections estimate the selection integral, so the catalog and the selection estimate share nothing.

Each synthetic event gets a mock posterior in u = (ln detector-frame chirp mass, ln q, ln z): Gaussian
measurement noise of widths 0.04, 0.3 and 0.3, and a PE prior uniform in u, so the posterior samples are
exactly Gaussian in u, truncated to q <= 1 by the mass ordering. The Jacobian of u with respect to (m1, m2, z) is 1 / (m1 m2 z), hence
pi_PE(m1, m2, z) = 1 / (m1 m2 z). Chirp mass is measured far better than the mass ratio or the distance,
which gives the anticorrelated m1-m2 and mass-redshift posteriors seen in real events, but real GWTC-3
posteriors are not Gaussian; this test checks the estimator, not the realism of the noise.

Coverage: over many catalogs, the posterior probability below the true value should be uniform.
Run:  python injection_recovery.py
"""
import json
import platform

import numpy as np
from scipy.special import ndtr, ndtri

from frozen_inputs import OUTPUTS, load_found_injections, load_manifest
from hierarchical_likelihood import SortedWeights, event_terms, injection_weights, normalized_posterior, selection_terms, truth_percentile
from hierarchical_mass_inference import ALPHA_GRID, M_MAX_GRID, MINIMUM_EVENT_EFFECTIVE_SAMPLES
from population_model import population_density, redshift_density, secondary_density

TRUE_ALPHA = 3.5
TRUE_M_MAX = 70.0
LOG_WIDTHS = np.array([0.04, 0.3, 0.3])
SAMPLES_PER_EVENT = 4000
CATALOGS = 100
SEED = 6060


def to_mock_coordinates(m1, m2, z):
    chirp_detector = (m1 * m2) ** 0.6 / (m1 + m2) ** 0.2 * (1 + z)
    return np.stack([np.log(chirp_detector), np.log(m2 / m1), np.log(z)], axis=-1)


def from_mock_coordinates(u):
    chirp_source = np.exp(u[:, 0]) / (1 + np.exp(u[:, 2]))
    ratio = np.exp(u[:, 1])
    m1 = chirp_source * (1 + ratio) ** 0.2 / ratio ** 0.6
    return m1, ratio * m1, np.exp(u[:, 2])


def mock_posterior_samples(observed_u, rng):
    """Gaussian in u, with ln q truncated to q <= 1 because the PE prior orders the masses (m1 >= m2)."""
    u = observed_u + LOG_WIDTHS * rng.standard_normal((SAMPLES_PER_EVENT, 3))
    upper = ndtr((0.0 - observed_u[1]) / LOG_WIDTHS[1])
    u[:, 1] = observed_u[1] + LOG_WIDTHS[1] * ndtri(np.clip(rng.uniform(size=SAMPLES_PER_EVENT) * upper, 1e-300, 1.0))
    return u


def mock_event_weights(observed_u, rng):
    m1, m2, z = from_mock_coordinates(mock_posterior_samples(observed_u, rng))
    fixed = secondary_density(m1, m2) * redshift_density(z) * (m1 * m2 * z)  # divided by pi_PE = 1 / (m1 m2 z)
    order = np.argsort(m1)
    return SortedWeights(m1[order], fixed[order])


def catalog_terms(truth_pool, truth_probability, observed, rng):
    """Log of the summed event likelihoods and the smallest per-event effective sample size, on the grid."""
    chosen = rng.choice(len(truth_pool), size=observed, p=truth_probability)
    log_event_sum = np.zeros((len(ALPHA_GRID), len(M_MAX_GRID)))
    minimum_effective = np.full_like(log_event_sum, np.inf)
    for index in chosen:
        true_m1, true_m2, true_z = truth_pool[index, :3]
        observed_u = to_mock_coordinates(true_m1, true_m2, true_z) + LOG_WIDTHS * rng.standard_normal(3)
        likelihood, effective = event_terms(mock_event_weights(observed_u, rng), SAMPLES_PER_EVENT, ALPHA_GRID, M_MAX_GRID)
        with np.errstate(divide="ignore"):
            log_event_sum += np.log(likelihood)
        minimum_effective = np.minimum(minimum_effective, effective)
    return log_event_sum, minimum_effective


def catalog_posterior(log_event_sum, minimum_effective, selection, observed, include_selection):
    """Posterior on the grid and the share of it sitting in cells that fail the Monte Carlo checks.

    The checks (every event with at least MINIMUM_EVENT_EFFECTIVE_SAMPLES effective samples and, with the
    selection term, Farr's N_eff > 4 N_obs) are reported, not used to cut the grid: a hard cut that depends on
    the data moves the posterior and breaks coverage.
    """
    fraction, _, selection_effective = selection
    with np.errstate(divide="ignore"):
        log_posterior = log_event_sum - (observed * np.log(fraction) if include_selection else 0)
    reliable = minimum_effective >= MINIMUM_EVENT_EFFECTIVE_SAMPLES
    if include_selection:
        reliable &= selection_effective > 4 * observed
    posterior = normalized_posterior(log_posterior, np.isfinite(log_posterior))
    return posterior, float(posterior[~reliable].sum())


def coverage(percentiles, level):
    percentiles = np.asarray(percentiles)
    lower = (1 - level) / 2
    return float(np.mean((percentiles > lower) & (percentiles < 1 - lower)))


def kolmogorov_smirnov_uniform(percentiles):
    """Largest distance between the empirical CDF of the truth percentiles and the uniform CDF."""
    values = np.sort(np.asarray(percentiles))
    count = len(values)
    above = np.max(np.arange(1, count + 1) / count - values)
    below = np.max(values - np.arange(count) / count)
    statistic = float(max(above, below))
    # Asymptotic Kolmogorov distribution (Marsaglia et al. 2003 series), good for n >= 35.
    effective = (np.sqrt(count) + 0.12 + 0.11 / np.sqrt(count)) * statistic
    terms = [2 * (-1) ** (k - 1) * np.exp(-2 * k * k * effective * effective) for k in range(1, 101)]
    return statistic, float(min(1.0, max(0.0, sum(terms))))


def main():
    manifest = load_manifest()
    injections = load_found_injections()
    total_generated = manifest["injections"]["effectiveTotalGenerated"]
    truth_pool, selection_pool = injections[0::2], injections[1::2]
    weights = population_density(truth_pool[:, 0], truth_pool[:, 1], truth_pool[:, 2], TRUE_ALPHA, TRUE_M_MAX) / truth_pool[:, 3]
    truth_probability = weights / weights.sum()
    truth_effective = float(weights.sum() ** 2 / np.sum(weights ** 2))
    selection = selection_terms(injection_weights(selection_pool), total_generated * len(selection_pool) / len(injections), ALPHA_GRID, M_MAX_GRID)

    rng = np.random.default_rng(SEED)
    report = {"software": {"python": platform.python_version(), "numpy": np.__version__},
              "truth": {"alpha": TRUE_ALPHA, "mMax": TRUE_M_MAX},
              "mockNoise": {"widths": {"lnDetectorChirpMass": 0.04, "lnMassRatio": 0.3, "lnRedshift": 0.3}, "samplesPerEvent": SAMPLES_PER_EVENT},
              "truthPoolEffectiveSize": truth_effective, "catalogs": CATALOGS, "seed": SEED, "runs": []}
    for observed in (23, 92):
        collected = {True: ([], [], []), False: ([], [], [])}
        flagged = {True: [], False: []}
        outside_support = 0
        for _ in range(CATALOGS):
            # The same synthetic catalog is analysed with and without the selection term.
            log_event_sum, minimum_effective = catalog_terms(truth_pool, truth_probability, observed, rng)
            if not np.isfinite(log_event_sum).any():
                # A noise draw put every posterior sample of some event outside the model (e.g. m2 < 5).
                outside_support += 1
                continue
            for include_selection in (True, False):
                posterior, flagged_mass = catalog_posterior(log_event_sum, minimum_effective, selection, observed, include_selection)
                flagged[include_selection].append(flagged_mass)
                alpha_marginal = posterior.sum(axis=1)
                alpha_percentiles, m_max_percentiles, widths = collected[include_selection]
                alpha_percentiles.append(truth_percentile(ALPHA_GRID, alpha_marginal, TRUE_ALPHA))
                m_max_percentiles.append(truth_percentile(M_MAX_GRID, posterior.sum(axis=0), TRUE_M_MAX))
                cumulative = np.cumsum(alpha_marginal)
                widths.append(float(np.interp(0.95, cumulative, ALPHA_GRID) - np.interp(0.05, cumulative, ALPHA_GRID)))
        for include_selection in (True, False):
            alpha_percentiles, m_max_percentiles, widths = collected[include_selection]
            alpha_ks = kolmogorov_smirnov_uniform(alpha_percentiles)
            m_max_ks = kolmogorov_smirnov_uniform(m_max_percentiles)
            run = {"observedEvents": observed, "selectionCorrected": include_selection,
                   "catalogsSkippedForAnEventOutsideModelSupport": outside_support,
                   "meanPosteriorMassInFlaggedCells": float(np.mean(flagged[include_selection])),
                   "catalogsWithMoreThanHalfFlagged": int(np.sum(np.array(flagged[include_selection]) > 0.5)),
                   "alpha": {"coverage68": coverage(alpha_percentiles, 0.68), "coverage90": coverage(alpha_percentiles, 0.9),
                             "ksStatistic": alpha_ks[0], "ksPValue": alpha_ks[1], "meanWidth90": float(np.mean(widths)),
                             "medianTruthPercentile": float(np.median(alpha_percentiles))},
                   "mMax": {"coverage68": coverage(m_max_percentiles, 0.68), "coverage90": coverage(m_max_percentiles, 0.9),
                            "ksStatistic": m_max_ks[0], "ksPValue": m_max_ks[1], "medianTruthPercentile": float(np.median(m_max_percentiles))}}
            report["runs"].append(run)
            print(json.dumps(run))
    # Binomial standard error of a coverage fraction over CATALOGS catalogs.
    report["coverageStandardError90"] = float(np.sqrt(0.9 * 0.1 / CATALOGS))
    report["coverageStandardError68"] = float(np.sqrt(0.68 * 0.32 / CATALOGS))
    OUTPUTS.mkdir(exist_ok=True)
    (OUTPUTS / "injection-recovery-results.json").write_text(json.dumps(report, indent=2) + "\n")


if __name__ == "__main__":
    main()
