#!/usr/bin/env python3
"""Draw the three figures from the files in results/ (no statistics are recomputed here,
apart from reference curves of named theoretical distributions).

Writes figures/fig1_f2_ratios_vs_3to1.{png,pdf}, fig2_consistency_is_not_proof.{png,pdf},
       fig3_too_good_to_be_true.{png,pdf}
"""
import csv, json, math, pathlib

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

ROOT = pathlib.Path(__file__).resolve().parents[1]
RES, FIG = ROOT / "results", ROOT / "figures"
FIG.mkdir(exist_ok=True)

OBS, THEORY, MODEL, FISHER = "#0072B2", "#4d4d4d", "#D55E00", "#009E73"   # Okabe-Ito, colour-vision safe
BAND = "#e6e6e6"
BASE, MID, SMALL = 8, 7, 6
plt.rcParams.update({
    "font.family": "DejaVu Sans", "font.size": BASE, "axes.titlesize": BASE, "axes.labelsize": BASE,
    "xtick.labelsize": SMALL, "ytick.labelsize": SMALL, "legend.fontsize": MID,
    "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.6,
    "xtick.major.width": 0.6, "ytick.major.width": 0.6, "xtick.major.size": 3, "ytick.major.size": 3,
    "axes.titlelocation": "left", "axes.titleweight": "normal", "legend.frameon": False,
    "pdf.fonttype": 42, "savefig.dpi": 300, "figure.dpi": 100,
})


def read(name):
    with open(RES / name, encoding="utf-8") as f:
        return list(csv.DictReader(f))


def letter(ax, s, dx=-0.02):
    ax.text(dx, 1.06, s, transform=ax.transAxes, fontsize=BASE + 2, fontweight="bold", ha="right", va="bottom")


def save(fig, stem):
    fig.savefig(FIG / f"{stem}.png", dpi=300)
    fig.savefig(FIG / f"{stem}.pdf")
    return fig


f2 = read("f2_chi_square_tests.csv")
f3 = read("f3_progeny_tests.csv")
b84 = read("binomial84_tests.csv")
alt_summary = json.loads((RES / "f2_summary.json").read_text())
con = json.loads((RES / "controversy_summary.json").read_text())
mc = json.loads((RES / "monte_carlo_summary.json").read_text())
hist = read("monte_carlo_total_chi_square_histogram.csv")

# ------------------------------------------------------------------ Figure 1: seven F2 experiments against 3:1
def figure1():
    rows = f2
    y = np.arange(len(rows))[::-1].astype(float)
    y[-1] -= 0.5                                              # set the pooled row apart
    names = [f"{r['trait']}\n{int(r['n']):,} {r['unit']}" for r in rows]
    names[-1] = f"All seven pooled\n{int(rows[-1]['n']):,} seeds and plants"
    fig, (a, b) = plt.subplots(1, 2, figsize=(7.2, 3.9), sharey=True, gridspec_kw={"wspace": 0.07, "width_ratios": [1.15, 1]})
    fig.subplots_adjust(left=0.215, right=0.985, top=0.86, bottom=0.14)

    ratio = np.array([float(r["observed_ratio_to_1"]) for r in rows])
    lo = np.array([float(r["ratio95_low_to_1"]) for r in rows]); hi = np.array([float(r["ratio95_high_to_1"]) for r in rows])
    a.axvline(3, color=THEORY, lw=1.0, zorder=1)
    a.hlines(y, lo, hi, color=OBS, lw=1.4, zorder=2)
    a.plot(ratio[:-1], y[:-1], "o", color=OBS, ms=4.5, zorder=3)
    a.plot(ratio[-1:], y[-1:], "D", color=OBS, ms=5, zorder=3)
    a.text(3.0, y[0] + 0.62, "3:1 expected", color=THEORY, fontsize=MID, ha="center", va="bottom")
    a.text(ratio[-1], y[-1] - 0.34, f"{ratio[-1]:.2f}:1", color=OBS, fontsize=MID, ha="center", va="top")
    a.set_xlim(2.2, 3.8); a.set_xticks([2.4, 2.7, 3.0, 3.3, 3.6])
    a.set_xlabel("Observed dominant : recessive ratio (x : 1), with 95% interval")
    a.set_yticks(y); a.set_yticklabels(names)
    a.set_ylim(y[-1] - 0.85, y[0] + 1.05)
    a.set_title("Every 95% interval contains 3:1")
    a.tick_params(axis="y", length=0)
    letter(a, "a", dx=-0.42)

    z = np.array([float(r["signed_z"]) for r in rows])
    b.axvspan(-1.96, 1.96, color=BAND, zorder=0, lw=0)
    b.axvline(0, color=THEORY, lw=1.0, zorder=1)
    b.hlines(y, 0, z, color="#9a9a9a", lw=0.8, zorder=2)
    b.plot(z[:-1], y[:-1], "o", color=OBS, ms=4.5, zorder=3)
    b.plot(z[-1:], y[-1:], "D", color=OBS, ms=5, zorder=3)
    b.text(0, y[0] + 0.62, "95% chance range under 3:1", color=THEORY, fontsize=MID, ha="center", va="bottom")
    b.set_xlim(-2.6, 2.6); b.set_xticks([-2, -1, 0, 1, 2])
    b.set_xlabel("Observed minus expected dominant count\n(in standard errors under 3:1)")
    b.set_title("No count is even one standard error from 3:1")
    b.tick_params(axis="y", length=0)
    letter(b, "b", dx=-0.02)
    return save(fig, "fig1_f2_ratios_vs_3to1")


# ------------------------------------------------------------------ Figure 2: consistency is not proof
def figure2():
    D, N = int(f2[-1]["observed_dominant"]), int(f2[-1]["n"])
    lo, hi = alt_summary["f2"]["pooled_ratio95_to_1"]
    r = np.linspace(2.6, 3.4, 801)
    p0 = r / (1 + r)
    chi = (D - N * p0) ** 2 / (N * p0 * (1 - p0))
    pv = stats.chi2.sf(chi, 1)
    fig, ax = plt.subplots(figsize=(4.6, 3.1))
    fig.subplots_adjust(left=0.13, right=0.97, top=0.88, bottom=0.16)
    ax.axvspan(lo, hi, color=BAND, lw=0, zorder=0)
    ax.axhline(0.05, color=THEORY, lw=0.8, ls=(0, (4, 3)), zorder=1)
    ax.plot(r, pv, color=OBS, lw=1.6, zorder=3)
    p3 = float(f2[-1]["p_value"])
    ax.plot([3], [p3], "o", color=OBS, ms=4.5, zorder=4)
    ax.annotate(f"3:1   P = {p3:.2f}", xy=(3, p3), xytext=(3.085, 0.88), fontsize=MID, color=OBS, va="center",
                arrowprops=dict(arrowstyle="-", color=OBS, lw=0.6, shrinkA=1, shrinkB=3))
    ax.text((lo + hi) / 2, 0.30, f"not rejected:\n{lo:.2f}:1 to {hi:.2f}:1", fontsize=MID, color=THEORY, ha="center", va="center")
    ax.text(2.615, 0.075, "P = 0.05", fontsize=MID, color=THEORY, ha="left", va="bottom")
    ax.set_xlim(2.6, 3.4); ax.set_ylim(0, 1.02)
    ax.set_xticks([2.6, 2.8, 3.0, 3.2, 3.4])
    ax.set_xlabel("Hypothesised dominant : recessive ratio (x : 1)")
    ax.set_ylabel("P-value, pooled chi-square test")
    ax.set_title("Mendel's pooled counts also fit ratios near 3:1")
    return save(fig, "fig2_consistency_is_not_proof")


# ------------------------------------------------------------------ Figure 3: the too-good-to-be-true evidence
def figure3():
    pd = con["p_value_distribution"]
    chi = np.array([float(r["chi"]) for r in b84]); pv = np.sort(np.array([float(r["p_value"]) for r in b84]))
    fig, axs = plt.subplots(2, 2, figsize=(7.2, 6.0))
    fig.subplots_adjust(left=0.085, right=0.975, top=0.93, bottom=0.085, wspace=0.30, hspace=0.50)
    a, b, c, d = axs.ravel()

    # a. signed deviations of the 84 tests
    edges = np.arange(-3, 3.01, 0.5)
    exp = 84 * np.diff(stats.norm.cdf(edges))
    a.hist(chi, bins=edges, color=OBS, edgecolor="white", lw=0.6, zorder=2)
    a.stairs(exp, edges, color=THEORY, lw=1.1, zorder=3)
    a.text(1.62, 12.6, "expected by\nchance alone", color=THEORY, fontsize=MID, ha="left", va="center")
    a.text(-0.25, 21.6, "Mendel's 84 tests", color=OBS, fontsize=MID, ha="right", va="center")
    a.set_xlim(-3, 3); a.set_ylim(0, 24); a.set_xticks(range(-3, 4))
    a.set_xlabel("Deviation from expectation (standard errors)"); a.set_ylabel("Number of tests")
    a.set_title(f"No deviation exceeds {pd['largest_abs_chi']:.1f} standard errors")
    letter(a, "a", dx=-0.11)

    # b. distribution of the 84 P-values
    x = np.linspace(0, 1, 501); al = pd["model_A_alpha_hat"]
    b.plot([0, 1], [0, 1], color=THEORY, lw=1.1, zorder=2)
    b.plot(x, np.where(x <= al, x * x, (1 + al) * x - al), color=MODEL, lw=1.3, zorder=3)
    b.step(np.concatenate([[0], pv, [1]]), np.concatenate([[0], np.arange(1, 85) / 84, [1]]), where="post", color=OBS, lw=1.5, zorder=4)
    b.text(0.33, 0.50, "chance alone", color=THEORY, fontsize=MID, ha="right", va="center", rotation=0)
    b.text(0.60, 0.33, "Mendel's 84 tests", color=OBS, fontsize=MID, ha="left", va="center")
    b.text(0.60, 0.20, f"model: repeat a test when\nP < {al:.2f}, report the closer fit", color=MODEL, fontsize=MID, ha="left", va="center")
    b.set_xlim(0, 1); b.set_ylim(0, 1.0)
    b.set_xlabel("P-value of a single test"); b.set_ylabel("Cumulative share of tests")
    b.set_title(f"No P-value below {math.floor(pd['smallest_p_value'] * 100) / 100:.2f}; chance predicts 8 below 0.10")
    letter(b, "b", dx=-0.11)

    # c. total chi-square of the 84 tests
    lo = np.array([float(h["bin_low"]) for h in hist]); h0 = np.array([float(h["count_chance_alone"]) for h in hist]); h1 = np.array([float(h["count_selective_repeat_model"]) for h in hist])
    ed = np.append(lo, lo[-1] + 1)
    c.stairs(h0 / h0.sum(), ed, color=THEORY, fill=True, alpha=0.30, lw=0, zorder=1)
    c.stairs(h0 / h0.sum(), ed, color=THEORY, lw=0.9, zorder=2)
    c.stairs(h1 / h1.sum(), ed, color=MODEL, lw=1.3, zorder=3)
    obs = con["binomial_organisation_84_tests"]["total_chi_square"]
    ymax = max((h0 / h0.sum()).max(), (h1 / h1.sum()).max()) * 1.32
    c.axvline(obs, color=OBS, lw=1.5, zorder=4)
    c.text(obs - 1.5, ymax * 0.985, f"Mendel\n{obs:.1f}", color=OBS, fontsize=MID, ha="right", va="top")
    c.text(96, (h0 / h0.sum()).max() * 0.80, "chance alone", color=THEORY, fontsize=MID, ha="left", va="center")
    c.text(55.5, (h1 / h1.sum()).max() * 1.10, "repeat model", color=MODEL, fontsize=MID, ha="center", va="bottom")
    c.set_xlim(15, 135); c.set_ylim(0, ymax); c.set_yticks([])
    c.spines["left"].set_visible(False)
    c.set_xlabel("Sum of the 84 chi-square values"); c.set_ylabel("Relative frequency in 1M simulations")
    c.set_title("Chance alone predicts a total near 84, not 41")
    letter(c, "c", dx=-0.11)

    # d. progeny tests scored on 10 offspring per plant
    ten = [r for r in f3 if r["ten_progeny_per_plant"] == "True"]
    labels = {"3": "Seed-coat colour", "4": "Pod shape", "5": "Unripe pod colour", "6": "Flower position", "7": "Stem length",
              "5-repeat": "Unripe pod colour, repeat", "pooled 3-7 + repeat": "All six pooled"}
    yy = np.arange(len(ten))[::-1].astype(float); yy[-1] -= 0.5
    frac = np.array([float(r["segregating_fraction"]) for r in ten]); l = np.array([float(r["wilson95_low"]) for r in ten]); h = np.array([float(r["wilson95_high"]) for r in ten])
    pf = con["f3_progeny_tests"]["fisher_corrected_probability_segregating"]
    d.axvline(2 / 3, color=THEORY, lw=1.0, zorder=1); d.axvline(pf, color=FISHER, lw=1.2, ls=(0, (4, 2)), zorder=1)
    d.hlines(yy, l, h, color=OBS, lw=1.4, zorder=2)
    d.plot(frac[:-1], yy[:-1], "o", color=OBS, ms=4.5, zorder=3); d.plot(frac[-1:], yy[-1:], "D", color=OBS, ms=5, zorder=3)
    top = yy[0] + 0.62
    d.text(2 / 3 + 0.006, top, "2:1 (Mendel)", color=THEORY, fontsize=MID, ha="left", va="bottom")
    d.text(pf - 0.006, top, "1.70:1 (Fisher's correction)", color=FISHER, fontsize=MID, ha="right", va="bottom")
    d.set_yticks(yy); d.set_yticklabels([labels[r["experiment"]] + (f"\n{int(r['n_plants'])} plants") for r in ten])
    d.tick_params(axis="y", length=0)
    d.set_xlim(0.48, 0.82); d.set_ylim(yy[-1] - 0.7, yy[0] + 1.25)
    d.set_xlabel("Share of plants scored as hybrids, with 95% interval")
    d.set_title("Pooled progeny tests sit on 2:1")
    letter(d, "d", dx=-0.42)
    pos = d.get_position(); d.set_position([pos.x0 + 0.105, pos.y0, pos.width - 0.105, pos.height])
    return save(fig, "fig3_too_good_to_be_true")


if __name__ == "__main__":
    for f in (figure1, figure2, figure3):
        f()
    print("figures written to", FIG)
