#!/usr/bin/env python3
"""Goodness-of-fit analysis of Mendel's (1866) pea data and of the Mendel-Fisher controversy.

Reads  : data/curated/*.csv, data/published_benchmarks/*.csv
Writes : results/*.csv, results/*.json
Set MENDEL_MC_REPS to change the number of Monte Carlo replicates (default 1,000,000).

Terminology. "Consistent with 3:1" below always means "a goodness-of-fit test does not reject 3:1".
It never means "3:1 has been proved"; see section B and the report.
"""
import csv, json, math, os, pathlib, re
from fractions import Fraction
from itertools import product

import numpy as np
from scipy import stats

ROOT = pathlib.Path(__file__).resolve().parents[1]
CUR, PUB, RES = ROOT / "data/curated", ROOT / "data/published_benchmarks", ROOT / "results"
RES.mkdir(exist_ok=True)
SEED = 1866
MC_REPS = int(os.environ.get("MENDEL_MC_REPS", "1000000"))
P_FISHER = (2 / 3) * (1 - 0.75 ** 10)   # Fisher's corrected probability of scoring a plant as segregating


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


def jdump(obj):
    def default(o):
        if isinstance(o, np.generic):
            return o.item()
        raise TypeError(type(o).__name__)
    return json.dumps(obj, indent=2, default=default)


def write(path, rows):
    with open(path, "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()), lineterminator="\n")
        w.writeheader(); w.writerows(rows)


def binom_gof(n1, n, p0):
    """Two-class goodness of fit of n1 successes in n trials to probability p0."""
    e1, e2 = n * p0, n * (1 - p0)
    o1, o2 = n1, n - n1
    chi2 = (o1 - e1) ** 2 / e1 + (o2 - e2) ** 2 / e2
    yates = (abs(o1 - e1) - 0.5) ** 2 / e1 + (abs(o2 - e2) - 0.5) ** 2 / e2
    g = 2 * sum(o * math.log(o / e) for o, e in ((o1, e1), (o2, e2)) if o > 0)
    z = (o1 - e1) / math.sqrt(n * p0 * (1 - p0))
    ci = stats.binomtest(n1, n).proportion_ci(confidence_level=0.95, method="wilson")
    return {
        "expected_1": e1, "expected_2": e2, "chi_square": chi2, "df": 1,
        "p_value": stats.chi2.sf(chi2, 1), "signed_z": z,
        "chi_square_yates": yates, "p_value_yates": stats.chi2.sf(yates, 1),
        "g_statistic": g, "p_value_g": stats.chi2.sf(g, 1),
        "p_value_exact_binomial": stats.binomtest(n1, n, p0).pvalue,
        "observed_fraction": n1 / n, "wilson95_low": ci.low, "wilson95_high": ci.high,
    }


# --------------------------------------------------------------------------- A. seven F2 experiments vs 3:1
f2 = read(CUR / "mendel_f2_monohybrid.csv")
f2_rows = []
for r in f2:
    d, c = int(r["dominant"]), int(r["recessive"])
    n = d + c
    t = binom_gof(d, n, 0.75)
    f2_rows.append({
        "experiment": r["experiment"], "trait": r["trait_en"], "unit": r["unit_counted"], "n": n,
        "observed_dominant": d, "observed_recessive": c,
        "expected_dominant_3to1": t["expected_1"], "expected_recessive_3to1": t["expected_2"],
        "observed_ratio_to_1": d / c, "observed_dominant_fraction": t["observed_fraction"],
        "wilson95_fraction_low": t["wilson95_low"], "wilson95_fraction_high": t["wilson95_high"],
        "ratio95_low_to_1": t["wilson95_low"] / (1 - t["wilson95_low"]),
        "ratio95_high_to_1": t["wilson95_high"] / (1 - t["wilson95_high"]),
        "chi_square": t["chi_square"], "df": 1, "p_value": t["p_value"], "signed_z": t["signed_z"],
        "chi_square_yates": t["chi_square_yates"], "p_value_yates": t["p_value_yates"],
        "g_statistic": t["g_statistic"], "p_value_g": t["p_value_g"],
        "p_value_exact_binomial": t["p_value_exact_binomial"],
        "rejects_3to1_at_0.05": t["p_value"] < 0.05,
    })
D = sum(r["observed_dominant"] for r in f2_rows); C = sum(r["observed_recessive"] for r in f2_rows); N = D + C
tp = binom_gof(D, N, 0.75)
pooled = {
    "experiment": "pooled", "trait": "All seven experiments", "unit": "seeds and plants", "n": N,
    "observed_dominant": D, "observed_recessive": C,
    "expected_dominant_3to1": tp["expected_1"], "expected_recessive_3to1": tp["expected_2"],
    "observed_ratio_to_1": D / C, "observed_dominant_fraction": tp["observed_fraction"],
    "wilson95_fraction_low": tp["wilson95_low"], "wilson95_fraction_high": tp["wilson95_high"],
    "ratio95_low_to_1": tp["wilson95_low"] / (1 - tp["wilson95_low"]),
    "ratio95_high_to_1": tp["wilson95_high"] / (1 - tp["wilson95_high"]),
    "chi_square": tp["chi_square"], "df": 1, "p_value": tp["p_value"], "signed_z": tp["signed_z"],
    "chi_square_yates": tp["chi_square_yates"], "p_value_yates": tp["p_value_yates"],
    "g_statistic": tp["g_statistic"], "p_value_g": tp["p_value_g"],
    "p_value_exact_binomial": tp["p_value_exact_binomial"], "rejects_3to1_at_0.05": tp["p_value"] < 0.05,
}
write(RES / "f2_chi_square_tests.csv", f2_rows + [pooled])

sum_chi2_7 = sum(r["chi_square"] for r in f2_rows)
het = sum_chi2_7 - tp["chi_square"]
f2_summary = {
    "n_experiments": 7, "total_n": N, "total_dominant": D, "total_recessive": C,
    "pooled_ratio_to_1": D / C,
    "pooled_ratio95_to_1": [pooled["ratio95_low_to_1"], pooled["ratio95_high_to_1"]],
    "sum_of_chi_square": sum_chi2_7, "sum_df": 7,
    "p_upper_tail_fit_this_poor_or_poorer": stats.chi2.sf(sum_chi2_7, 7),
    "p_lower_tail_fit_this_close_or_closer": stats.chi2.cdf(sum_chi2_7, 7),
    "pooled_chi_square": tp["chi_square"], "pooled_df": 1, "pooled_p_value": tp["p_value"],
    "heterogeneity_chi_square": het, "heterogeneity_df": 6, "heterogeneity_p_value": stats.chi2.sf(het, 6),
    "max_abs_signed_z": max(abs(r["signed_z"]) for r in f2_rows),
    "min_p_value": min(r["p_value"] for r in f2_rows), "max_p_value": max(r["p_value"] for r in f2_rows),
    "min_exact_binomial_p_value": min(r["p_value_exact_binomial"] for r in f2_rows),
    "n_experiments_rejecting_3to1_at_0.05": sum(r["rejects_3to1_at_0.05"] for r in f2_rows),
    "bonferroni_threshold_7_tests": 0.05 / 7,
}

# --------------------------------------------------------------------------- B. consistency is not proof
# B1. What follows deductively: IF each hybrid parent (Aa) passes A or a with probability 1/2, gametes unite
#     at random, all zygotes are equally viable and A is completely dominant, THEN P(dominant) = 3/4 exactly.
half = Fraction(1, 2)
zyg = {}
for egg, pollen in product("Aa", repeat=2):
    g = "".join(sorted(egg + pollen))
    zyg[g] = zyg.get(g, 0) + half * half
p_dom_exact = zyg["AA"] + zyg["Aa"]
deduction = {
    "premises": ["hybrid parents are Aa", "each gamete carries A or a with probability 1/2",
                 "gametes unite at random", "all zygotes equally viable and scored without error",
                 "A is completely dominant over a"],
    "genotype_probabilities": {k: str(v) for k, v in sorted(zyg.items())},
    "P_dominant_phenotype": str(p_dom_exact), "dominant_to_recessive": f"{p_dom_exact / (1 - p_dom_exact)}:1",
    "status": "exact consequence of the premises (a theorem about the model, not about peas)",
}
# B2. What the data can and cannot exclude: test the pooled counts and each experiment against other ratios.
alt_rows = []
for ratio in (2.0, 2.5, 2.8, 2.85, 2.9, 2.95, 3.0, 3.05, 3.1, 3.15, 3.2, 3.5, 4.0):
    p0 = ratio / (1 + ratio)
    tt = binom_gof(D, N, p0)
    n_rej = sum(binom_gof(r["observed_dominant"], r["n"], p0)["p_value"] < 0.05 for r in f2_rows)
    ssum = sum(binom_gof(r["observed_dominant"], r["n"], p0)["chi_square"] for r in f2_rows)
    alt_rows.append({"hypothesised_ratio_to_1": ratio, "hypothesised_dominant_fraction": p0,
                     "pooled_chi_square": tt["chi_square"], "pooled_p_value": tt["p_value"],
                     "pooled_rejected_at_0.05": tt["p_value"] < 0.05,
                     "sum_of_7_chi_squares": ssum, "sum_p_value_df7": stats.chi2.sf(ssum, 7),
                     "n_single_experiments_rejecting_at_0.05": n_rej})
write(RES / "alternative_ratio_tests.csv", alt_rows)
se0 = math.sqrt(0.75 * 0.25 / N)
delta80 = (stats.norm.ppf(0.975) + stats.norm.ppf(0.80)) * se0   # normal approximation, variance fixed at p0
not_proof = {
    "pooled_ratio_values_not_rejected_at_0.05_wilson": [pooled["ratio95_low_to_1"], pooled["ratio95_high_to_1"]],
    "single_experiment_ratio95_intervals": {r["trait"]: [r["ratio95_low_to_1"], r["ratio95_high_to_1"]] for r in f2_rows},
    "smallest_fraction_shift_detectable_with_80pct_power_pooled": delta80,
    "equivalent_ratios_to_1": [(0.75 - delta80) / (0.25 + delta80), (0.75 + delta80) / (0.25 - delta80)],
    "deduction_from_model": deduction,
}

# --------------------------------------------------------------------------- C. F3 progeny tests vs 2:1
f3 = read(CUR / "mendel_f3_progeny_tests.csv")
f3_rows = []
for r in f3:
    n, seg = int(r["n_plants_tested"]), int(r["segregating"])
    t = binom_gof(seg, n, 2 / 3)
    row = {"experiment": r["experiment"], "trait": r["trait_en"], "n_plants": n,
           "segregating": seg, "constant": n - seg, "segregating_fraction": seg / n,
           "wilson95_low": t["wilson95_low"], "wilson95_high": t["wilson95_high"],
           "expected_segregating_2to1": t["expected_1"], "chi_square_2to1": t["chi_square"],
           "p_value_2to1": t["p_value"], "signed_z_2to1": t["signed_z"],
           "p_value_exact_binomial_2to1": t["p_value_exact_binomial"],
           "ten_progeny_per_plant": r["progeny_scored_per_plant"] == "10"}
    if row["ten_progeny_per_plant"]:
        u = binom_gof(seg, n, P_FISHER)
        row.update({"expected_segregating_fisher": u["expected_1"], "chi_square_fisher": u["chi_square"],
                    "p_value_fisher": u["p_value"], "signed_z_fisher": u["signed_z"]})
    else:
        row.update({"expected_segregating_fisher": "", "chi_square_fisher": "", "p_value_fisher": "", "signed_z_fisher": ""})
    f3_rows.append(row)
ten = [r for r in f3_rows if r["ten_progeny_per_plant"]]
n6, s6 = sum(r["n_plants"] for r in ten), sum(r["segregating"] for r in ten)
t21, tfi = binom_gof(s6, n6, 2 / 3), binom_gof(s6, n6, P_FISHER)
f3_rows.append({"experiment": "pooled 3-7 + repeat", "trait": "Six plant-character progeny tests", "n_plants": n6,
                "segregating": s6, "constant": n6 - s6, "segregating_fraction": s6 / n6,
                "wilson95_low": t21["wilson95_low"], "wilson95_high": t21["wilson95_high"],
                "expected_segregating_2to1": t21["expected_1"], "chi_square_2to1": t21["chi_square"],
                "p_value_2to1": t21["p_value"], "signed_z_2to1": t21["signed_z"],
                "p_value_exact_binomial_2to1": t21["p_value_exact_binomial"], "ten_progeny_per_plant": True,
                "expected_segregating_fisher": tfi["expected_1"], "chi_square_fisher": tfi["chi_square"],
                "p_value_fisher": tfi["p_value"], "signed_z_fisher": tfi["signed_z"]})
write(RES / "f3_progeny_tests.csv", f3_rows)
one_sided = stats.norm.sf(tfi["signed_z"])
f3_summary = {
    "fisher_corrected_probability_segregating": P_FISHER,
    "fisher_corrected_ratio_segregating_to_constant": P_FISHER / (1 - P_FISHER),
    "fisher_corrected_ratio_scaled_to_3": [3 * P_FISHER, 3 * (1 - P_FISHER)],
    "probability_heterozygote_shows_no_recessive_in_10": 0.75 ** 10,
    "pooled_n": n6, "pooled_segregating": s6, "pooled_constant": n6 - s6,
    "expected_segregating_2to1": t21["expected_1"], "chi_square_vs_2to1": t21["chi_square"], "p_vs_2to1": t21["p_value"],
    "expected_segregating_fisher": tfi["expected_1"], "expected_constant_fisher": tfi["expected_2"],
    "chi_square_vs_fisher": tfi["chi_square"], "p_two_sided_vs_fisher": tfi["p_value"],
    "p_exact_binomial_vs_fisher": tfi["p_value_exact_binomial"],
    "p_one_sided_normal_vs_fisher": one_sided, "one_in_n_trials": 1 / one_sided,
    "pooled_fraction": s6 / n6, "pooled_wilson95": [t21["wilson95_low"], t21["wilson95_high"]],
    "sum_chi_square_8_tests_vs_2to1": sum(r["chi_square_2to1"] for r in f3_rows[:8]),
}

# --------------------------------------------------------------------------- D. Fisher's (1936) organisation
def parse_symbol(s):
    m = re.fullmatch(r"(Aa|A|a)(Bb|B|b)(Cc|C|c)?", s)
    if not m:
        raise ValueError(s)
    conv = lambda x: None if x is None else (x if len(x) == 2 else x * 2)
    return tuple(conv(x) for x in m.groups())

GP = {"AA": 0.25, "Aa": 0.5, "aa": 0.25, "BB": 0.25, "Bb": 0.5, "bb": 0.25, "CC": 0.25, "Cc": 0.5, "cc": 0.25}
bif = {parse_symbol(r["mendel_symbol"])[:2]: int(r["count"]) for r in read(CUR / "mendel_bifactorial_f2_plant_genotypes.csv")}
tri = {parse_symbol(r["mendel_symbol"]): int(r["count"]) for r in read(CUR / "mendel_trifactorial_f2_plant_genotypes.csv")}
seeds = {(r["seed_shape"], r["seed_colour"]): int(r["count"]) for r in read(CUR / "mendel_bifactorial_f2_seeds.csv")}
gam = read(CUR / "mendel_gametic_ratio_experiments.csv")
first10 = read(CUR / "mendel_first10_plants.csv")
assert len(bif) == 9 and len(tri) == 27 and sum(bif.values()) == 529 and sum(tri.values()) == 639 and sum(seeds.values()) == 556

def multinomial_chi2(obs, probs):
    n = sum(obs)
    return sum((o - n * p) ** 2 / (n * p) for o, p in zip(obs, probs))

chi_bif = multinomial_chi2(list(bif.values()), [GP[a] * GP[b] for a, b in bif])
chi_tri = multinomial_chi2(list(tri.values()), [GP[a] * GP[b] * GP[c] for a, b, c in tri])
chi_gam = sum(multinomial_chi2([int(r[k]) for k in ("c11", "c12", "c21", "c22")], [0.25] * 4) for r in gam)
chi_31 = sum_chi2_7
chi_21 = f3_summary["sum_chi_square_8_tests_vs_2to1"]
chi_pv = sum(binom_gof(int(r["round"]), int(r["round"]) + int(r["wrinkled"]), 0.75)["chi_square"] for r in first10) \
       + sum(binom_gof(int(r["yellow"]), int(r["yellow"]) + int(r["green"]), 0.75)["chi_square"] for r in first10)
fisher_pub = {r["group"]: r for r in read(PUB / "fisher_1936_tableV_as_reproduced_in_pires_branco_2010_table5.csv")}
groups = [("3:1 ratios", 7, chi_31), ("2:1 ratios", 8, chi_21), ("Bifactorial", 8, chi_bif),
          ("Gametic ratios", 15, chi_gam), ("Trifactorial", 26, chi_tri)]
tot64 = sum(g[2] for g in groups)
groups += [("Total (excluding illustrations)", 64, tot64), ("Illustrations of plant variation", 20, chi_pv), ("Total", 84, tot64 + chi_pv)]
fisher_rows = []
for name, df, chi in groups:
    pub = fisher_pub[name]
    fisher_rows.append({"group": name, "df": df, "chi_square_recomputed": chi,
                        "p_exceeding_recomputed": stats.chi2.sf(chi, df), "p_at_or_below_recomputed": stats.chi2.cdf(chi, df),
                        "chi_square_fisher_1936": float(pub["chi_square"]), "p_exceeding_fisher_1936": float(pub["probability_of_exceeding"]),
                        "abs_diff_chi_square": abs(chi - float(pub["chi_square"]))})
write(RES / "fisher_1936_groups_reproduction.csv", fisher_rows)
chi84_fisher = tot64 + chi_pv

# --------------------------------------------------------------------------- E. 84 binomial tests (Edwards 1986 / Pires & Branco 2010)
def tsum(pred):
    return sum(v for k, v in tri.items() if pred(k))
def bsum(pred):
    return sum(v for k, v in bif.items() if pred(k))
isdom = lambda g: g[0].isupper()          # AA or Aa (BB/Bb, CC/Cc): dominant phenotype
ishet = lambda g: g[0] != g[1]
AB_ORDER = [("Aa", "Bb"), ("Aa", "BB"), ("AA", "Bb"), ("AA", "BB"), ("Aa", "bb"), ("AA", "bb"), ("aa", "Bb"), ("aa", "BB"), ("aa", "bb")]
E = []   # (group, label, n, n1, p0)
for r in f2_rows:
    E.append(("3:1 ratios", f"F2 {r['trait']}", r["n"], r["observed_dominant"], 0.75))
for r in first10:
    E.append(("Illustrations of plant variation", f"plant {r['plant']} seed shape", int(r["round"]) + int(r["wrinkled"]), int(r["round"]), 0.75))
for r in first10:
    E.append(("Illustrations of plant variation", f"plant {r['plant']} seed colour", int(r["yellow"]) + int(r["green"]), int(r["yellow"]), 0.75))
ry, wy, rg, wg = seeds[("round", "yellow")], seeds[("wrinkled", "yellow")], seeds[("round", "green")], seeds[("wrinkled", "green")]
E += [("Bifactorial", "F2 seeds: A (shape)", ry + wy + rg + wg, ry + rg, 0.75),
      ("Bifactorial", "F2 seeds: B among round", ry + rg, ry, 0.75),
      ("Bifactorial", "F2 seeds: B among wrinkled", wy + wg, wy, 0.75)]
E += [("Trifactorial", "F2: A", 639, tsum(lambda k: isdom(k[0])), 0.75),
      ("Trifactorial", "F2: B among A-phenotype", tsum(lambda k: isdom(k[0])), tsum(lambda k: isdom(k[0]) and isdom(k[1])), 0.75),
      ("Trifactorial", "F2: B among a-phenotype", tsum(lambda k: not isdom(k[0])), tsum(lambda k: not isdom(k[0]) and isdom(k[1])), 0.75)]
for a, b in AB_ORDER:
    E.append(("Trifactorial", f"F2: C among {a}{b}", tsum(lambda k: k[:2] == (a, b)), tsum(lambda k: k[:2] == (a, b) and isdom(k[2])), 0.75))
for r in f3_rows[:8]:
    E.append(("2:1 ratios", f"F3 {r['trait']}", r["n_plants"], r["segregating"], 2 / 3))
def two_locus(S, grp):
    return [(grp, "F3: A among A,B-phenotype", S(lambda k: isdom(k[0]) and isdom(k[1])), S(lambda k: ishet(k[0]) and isdom(k[1])), 2 / 3),
            (grp, "F3: A among A,b-phenotype", S(lambda k: isdom(k[0]) and not isdom(k[1])), S(lambda k: ishet(k[0]) and not isdom(k[1])), 2 / 3),
            (grp, "F3: B among a,B-phenotype", S(lambda k: not isdom(k[0]) and isdom(k[1])), S(lambda k: not isdom(k[0]) and ishet(k[1])), 2 / 3),
            (grp, "F3: B among Aa, B-phenotype", S(lambda k: ishet(k[0]) and isdom(k[1])), S(lambda k: ishet(k[0]) and ishet(k[1])), 2 / 3),
            (grp, "F3: B among AA, B-phenotype", S(lambda k: k[0] == "AA" and isdom(k[1])), S(lambda k: k[0] == "AA" and ishet(k[1])), 2 / 3)]
E += two_locus(bsum, "Bifactorial")
E += two_locus(tsum, "Trifactorial")
for a, b in AB_ORDER:
    E.append(("Trifactorial", f"F3: C among {a}{b}, C-phenotype", tsum(lambda k: k[:2] == (a, b) and isdom(k[2])), tsum(lambda k: k[:2] == (a, b) and ishet(k[2])), 2 / 3))
for r in gam:
    c11, c12, c21, c22 = (int(r[k]) for k in ("c11", "c12", "c21", "c22"))
    l1, l2 = r["first_character_levels"].split("|")
    E += [("Gametic ratios", f"expt {r['experiment']}: first character", c11 + c12 + c21 + c22, c11 + c12, 0.5),
          ("Gametic ratios", f"expt {r['experiment']}: second character among {l1}", c11 + c12, c11, 0.5),
          ("Gametic ratios", f"expt {r['experiment']}: second character among {l2}", c21 + c22, c21, 0.5)]
assert len(E) == 84
b84 = []
for i, (grp, label, n, n1, p0) in enumerate(E, 1):
    z = (n1 - n * p0) / math.sqrt(n * p0 * (1 - p0))
    b84.append({"no": i, "group": grp, "label": label, "n": n, "n1": n1, "p0": p0, "chi": z, "chi_square": z * z,
                "p_value": stats.chi2.sf(z * z, 1)})
write(RES / "binomial84_tests.csv", b84)

pb7 = read(PUB / "pires_branco_2010_table7_84_binomial_experiments.csv")
cmp_rows, max_dchi, max_dp, n_count_mismatch = [], 0.0, 0.0, 0
for mine, pub in zip(b84, pb7):
    ok_counts = mine["n"] == int(pub["n"]) and mine["n1"] == int(pub["n1"])
    n_count_mismatch += (not ok_counts)
    dchi, dp = abs(mine["chi"] - float(pub["chi"])), abs(mine["p_value"] - float(pub["p_value"]))
    max_dchi, max_dp = max(max_dchi, dchi), max(max_dp, dp)
    cmp_rows.append({"no": mine["no"], "label": mine["label"], "n_recomputed": mine["n"], "n_published": pub["n"],
                     "n1_recomputed": mine["n1"], "n1_published": pub["n1"], "counts_match": ok_counts,
                     "chi_recomputed": round(mine["chi"], 4), "chi_published": pub["chi"],
                     "p_recomputed": round(mine["p_value"], 4), "p_published": pub["p_value"]})
write(RES / "binomial84_vs_pires_branco_table7.csv", cmp_rows)
pb6 = {r["group"]: r for r in read(PUB / "pires_branco_2010_table6_binomial_organisation.csv")}
grp_rows = []
order = ["3:1 ratios", "2:1 ratios", "Bifactorial", "Gametic ratios", "Trifactorial"]
gsum = {g: sum(r["chi_square"] for r in b84 if r["group"] == g) for g in order + ["Illustrations of plant variation"]}
gdf = {g: sum(1 for r in b84 if r["group"] == g) for g in gsum}
gsum["Total (excluding illustrations)"] = sum(gsum[g] for g in order); gdf["Total (excluding illustrations)"] = sum(gdf[g] for g in order)
gsum["Total"] = sum(r["chi_square"] for r in b84); gdf["Total"] = 84
for g in order + ["Total (excluding illustrations)", "Illustrations of plant variation", "Total"]:
    grp_rows.append({"group": g, "df": gdf[g], "chi_square_recomputed": gsum[g],
                     "p_exceeding_recomputed": stats.chi2.sf(gsum[g], gdf[g]),
                     "chi_square_pires_branco_2010": float(pb6[g]["chi_square"]), "p_pires_branco_2010": float(pb6[g]["p_value_chi2"]),
                     "abs_diff_chi_square": abs(gsum[g] - float(pb6[g]["chi_square"]))})
write(RES / "binomial84_groups_reproduction.csv", grp_rows)
chi84 = gsum["Total"]

# --------------------------------------------------------------------------- F. distribution of the 84 p-values
pv = np.array([r["p_value"] for r in b84])
ks_u = stats.kstest(pv, "uniform")
rng_j = np.random.default_rng(SEED)
pv_j = pv + rng_j.normal(0, 1e-7, pv.size)          # tie-breaking as in Pires & Branco (2010), Appendix B.2
ks_uj = stats.kstest(pv_j, "uniform")

def cdf_model_a(x, a):
    x = np.asarray(x, dtype=float)
    return np.where(x <= a, x * x, (1 + a) * x - a)

grid = np.round(np.arange(0, 1.0001, 0.001), 3)
Dg = np.array([stats.kstest(pv_j, lambda x, a=a: cdf_model_a(x, a)).statistic for a in grid])
a_hat = float(grid[Dg.argmin()])
ks_a = stats.kstest(pv_j, lambda x: cdf_model_a(x, a_hat))
pg = np.array([stats.kstest(pv_j, lambda x, a=a: cdf_model_a(x, a)).pvalue for a in grid])
keep90 = grid[pg >= 0.10]
write(RES / "selective_repeat_model_fit.csv", [{"alpha": float(a), "ks_D": float(d), "ks_p_value": float(p)} for a, d, p in zip(grid, Dg, pg)])
pvalue_dist = {
    "n_p_values": 84, "n_below_0.05": int((pv < 0.05).sum()), "expected_below_0.05_if_uniform": 84 * 0.05,
    "n_below_0.10": int((pv < 0.10).sum()), "expected_below_0.10_if_uniform": 8.4,
    "smallest_p_value": float(pv.min()), "largest_abs_chi": max(abs(r["chi"]) for r in b84),
    "probability_all_84_abs_chi_below_observed_max": float((1 - 2 * stats.norm.sf(max(abs(r["chi"]) for r in b84))) ** 84),
    "ks_uniform_D_no_jitter": float(ks_u.statistic), "ks_uniform_p_no_jitter": float(ks_u.pvalue),
    "ks_uniform_D": float(ks_uj.statistic), "ks_uniform_p": float(ks_uj.pvalue),
    "model_A_alpha_hat": a_hat, "model_A_ks_D": float(ks_a.statistic), "model_A_ks_p": float(ks_a.pvalue),
    "model_A_alpha_range_ks_p_at_least_0.10": [float(keep90.min()), float(keep90.max())],
    "expected_share_of_experiments_repeated_under_model_A": a_hat,
}

# --------------------------------------------------------------------------- G. Monte Carlo
rng = np.random.default_rng(SEED)
n84 = np.array([r["n"] for r in b84]); p84 = np.array([r["p0"] for r in b84])
v84 = n84 * p84 * (1 - p84)
idx7 = np.arange(7)
crit = stats.chi2.isf(a_hat, 1)
chunk = 100_000
cnt = {"f2_le": 0, "all_ge": 0, "all_le": 0, "modelA_ge": 0, "modelA_le": 0, "f2_all_within": 0}
edges = np.arange(0, 201, 1.0)
hist_null = np.zeros(edges.size - 1, dtype=np.int64)
hist_model_a = np.zeros(edges.size - 1, dtype=np.int64)
max_abs_obs7 = f2_summary["max_abs_signed_z"]
done = 0
while done < MC_REPS:
    m = min(chunk, MC_REPS - done)
    x = rng.binomial(n84, p84, size=(m, 84))
    c1 = (x - n84 * p84) ** 2 / v84
    tot = c1.sum(axis=1)
    cnt["all_ge"] += int((tot >= chi84).sum()); cnt["all_le"] += int((tot <= chi84).sum())
    t7 = c1[:, idx7].sum(axis=1)
    cnt["f2_le"] += int((t7 <= sum_chi2_7).sum())
    cnt["f2_all_within"] += int((np.sqrt(c1[:, idx7]).max(axis=1) <= max_abs_obs7).sum())
    x2 = rng.binomial(n84, p84, size=(m, 84))
    c2 = (x2 - n84 * p84) ** 2 / v84
    rep = np.where(c1 > crit, np.minimum(c1, c2), c1)   # repeat when p < alpha, report the closer of the two
    ta = rep.sum(axis=1)
    cnt["modelA_ge"] += int((ta >= chi84).sum()); cnt["modelA_le"] += int((ta <= chi84).sum())
    hist_null += np.histogram(tot, bins=edges)[0]
    hist_model_a += np.histogram(ta, bins=edges)[0]
    done += m
write(RES / "monte_carlo_total_chi_square_histogram.csv",
      [{"bin_low": float(lo), "bin_high": float(lo + 1), "count_chance_alone": int(h0), "count_selective_repeat_model": int(h1)}
       for lo, h0, h1 in zip(edges[:-1], hist_null, hist_model_a)])
def prop(k):
    p = cnt[k] / MC_REPS
    return {"estimate": p, "standard_error": math.sqrt(p * (1 - p) / MC_REPS)}
mc = {
    "replicates": MC_REPS, "seed": SEED, "sampling_model": "independent binomial counts with Mendel's sample sizes and the theoretical probabilities",
    "seven_F2_tests": {"observed_sum_chi_square": sum_chi2_7,
                       "P_sum_at_or_below_observed": prop("f2_le"),
                       "chi_square_approximation": stats.chi2.cdf(sum_chi2_7, 7),
                       "P_all_seven_abs_z_at_or_below_observed_max": prop("f2_all_within")},
    "all_84_tests": {"observed_sum_chi_square": chi84,
                     "P_sum_at_or_above_observed": prop("all_ge"), "P_sum_at_or_below_observed": prop("all_le"),
                     "chi_square_approximation_upper": stats.chi2.sf(chi84, 84), "chi_square_approximation_lower": stats.chi2.cdf(chi84, 84),
                     "published_pires_branco_2010_upper": 0.99998},
    "all_84_tests_selective_repeat_model_A": {"alpha": a_hat, "P_sum_at_or_above_observed": prop("modelA_ge"),
                                              "P_sum_at_or_below_observed": prop("modelA_le"),
                                              "published_pires_branco_2010_upper_alpha_0.201": 0.6577},
}

# --------------------------------------------------------------------------- H. sensitivity: Fisher's corrected expectation
chi_six_21 = sum(r["chi_square_2to1"] for r in ten)
chi_six_fi = sum(r["chi_square_fisher"] for r in ten)
chi84_corr = chi84 - chi_six_21 + chi_six_fi
tri_c = [r for r in b84 if r["label"].startswith("F3: C among")]
chi_tri_c_21 = sum(r["chi_square"] for r in tri_c)
chi_tri_c_fi = sum(binom_gof(r["n1"], r["n"], P_FISHER)["chi_square"] for r in tri_c)
chi84_corr15 = chi84_corr - chi_tri_c_21 + chi_tri_c_fi
sensitivity = {"scenario_2_fifteen_tests": {
                   "description": "Fisher's correction applied to the six single-character tests and, as an assumption of this analysis, "
                                  "to the nine trifactorial seed-coat-colour classifications (Mendel does not state how many seeds were sown for these)",
                   "total_84_chi_square": chi84_corr15, "p_at_or_below": stats.chi2.cdf(chi84_corr15, 84),
                   "edwards_1986_total_as_quoted_by_ellis_2019": 48.91,
                   "note": "Edwards used a slightly different organisation of the data; his total is quoted for comparison and is not reproduced exactly"},
               "six_tests_sum_chi_square_vs_2to1": chi_six_21, "six_tests_sum_chi_square_vs_fisher_corrected": chi_six_fi,
               "total_84_chi_square_with_fisher_correction_in_six_tests": chi84_corr,
               "p_at_or_below_with_correction": stats.chi2.cdf(chi84_corr, 84),
               "note": "correction applied only to the six single-character progeny tests that Mendel states used 10 seeds per plant"}

controversy = {
    "fisher_organisation_binomial_plus_multinomial": {"total_chi_square": chi84_fisher, "df": 84,
        "p_exceeding": stats.chi2.sf(chi84_fisher, 84), "p_at_or_below": stats.chi2.cdf(chi84_fisher, 84),
        "fisher_1936_printed_total": 41.6056, "fisher_1936_printed_probability": 0.99993},
    "binomial_organisation_84_tests": {"total_chi_square": chi84, "df": 84, "expected_value_if_chance_alone": 84,
        "p_exceeding": stats.chi2.sf(chi84, 84), "p_at_or_below": stats.chi2.cdf(chi84, 84), "one_in": 1 / stats.chi2.cdf(chi84, 84)},
    "p_value_distribution": pvalue_dist, "f3_progeny_tests": f3_summary, "sensitivity": sensitivity,
}
(RES / "f2_summary.json").write_text(jdump({"f2": f2_summary, "consistency_is_not_proof": not_proof}), encoding="utf-8")
(RES / "controversy_summary.json").write_text(jdump(controversy), encoding="utf-8")
(RES / "monte_carlo_summary.json").write_text(jdump(mc), encoding="utf-8")

# --------------------------------------------------------------------------- I. verification against published values
checks = []
def check(name, ok, detail):
    checks.append({"check": name, "passed": bool(ok), "detail": detail})
# A secondary teaching table (Huskey 1999) prints chi-squares that differ from the exact values in 4 of 7 rows.
# Both comparisons are recorded: against the exact expectation, and against the integer-rounded expected
# counts that the page itself prints. Only the second is a like-for-like reproduction of that page.
husk = {r["experiment"]: r for r in read(PUB / "huskey_1999_webpage_chi_square.csv")}
discrepancies = []
n_exact_agree = 0
for r in f2_rows:
    h = husk[r["experiment"]]
    pub = float(h["chi_square_2dp"])
    e1, e2 = int(h["expected_dominant_integer"]), int(h["expected_recessive_integer"])
    chi_int = (r["observed_dominant"] - e1) ** 2 / e1 + (r["observed_recessive"] - e2) ** 2 / e2
    exact_ok = abs(round(r["chi_square"], 2) - pub) < 1e-9
    n_exact_agree += exact_ok
    check(f"F2 expt {r['experiment']}: secondary table (Huskey 1999) reproduced from its own integer-rounded expected counts",
          abs(round(chi_int, 2) - pub) < 1e-9, f"with expected {e1}:{e2} chi-square = {chi_int:.4f}, printed {pub:.2f}")
    if not exact_ok:
        discrepancies.append({"experiment": r["experiment"], "trait": r["trait"], "exact_chi_square": r["chi_square"],
                              "secondary_table_value": pub, "exact_expected": [r["expected_dominant_3to1"], r["expected_recessive_3to1"]],
                              "secondary_table_expected": [e1, e2], "chi_square_from_secondary_expected": chi_int,
                              "explanation": "the secondary table rounds expected counts to whole numbers before computing chi-square"})
for fr in fisher_rows:
    check(f"Fisher (1936) Table V: {fr['group']}", fr["abs_diff_chi_square"] <= 1.5e-4,
          f"recomputed {fr['chi_square_recomputed']:.4f}, printed {fr['chi_square_fisher_1936']:.4f}")
for gr in grp_rows:
    check(f"Pires & Branco (2010) Table 6, binomial organisation: {gr['group']}", gr["abs_diff_chi_square"] <= 1.5e-4,
          f"recomputed {gr['chi_square_recomputed']:.4f}, printed {gr['chi_square_pires_branco_2010']:.4f}")
check("84 derived binomial experiments: n and n1 equal Pires & Branco (2010) Table 7 in all rows", n_count_mismatch == 0, f"{n_count_mismatch} mismatching rows")
check("84 signed chi values agree with Table 7 to 3 dp", max_dchi <= 6e-4, f"max abs difference {max_dchi:.5f}")
check("84 p-values agree with Table 7 to 3 dp", max_dp <= 6e-4, f"max abs difference {max_dp:.5f}")
check("KS test of 84 p-values against uniform reproduces D = 0.1913", abs(ks_uj.statistic - 0.1913) <= 6e-4, f"D = {ks_uj.statistic:.4f}, P = {ks_uj.pvalue:.4f} (published P = 0.0036)")
check("Selective-repeat model: alpha-hat reproduces 0.201", abs(a_hat - 0.201) <= 1.5e-3, f"alpha-hat = {a_hat:.3f}, D = {ks_a.statistic:.4f}, P = {ks_a.pvalue:.4f} (published 0.201, 0.0623, 0.8804)")
check("Fisher's corrected expectation for 600 plants is 377.5 : 222.5", abs(tfi["expected_1"] - 377.5) < 0.05, f"{tfi['expected_1']:.2f} : {tfi['expected_2']:.2f}")
check("Fisher's 'once in twenty-nine trials' reproduced (one-sided)", 28 <= 1 / one_sided <= 30, f"one-sided P = {one_sided:.4f}, i.e. 1 in {1 / one_sided:.1f}")
max_dev = 0.0
for r in f2_rows:                                   # no SciPy, no NumPy: chi-square (1 df) tail = erfc(sqrt(x/2))
    o1, o2 = r["observed_dominant"], r["observed_recessive"]
    e1, e2 = 3 * (o1 + o2) / 4, (o1 + o2) / 4
    x = (o1 - e1) ** 2 / e1 + (o2 - e2) ** 2 / e2
    max_dev = max(max_dev, abs(x - r["chi_square"]), abs(math.erfc(math.sqrt(x / 2)) - r["p_value"]))
check("Seven F2 chi-squares and P-values agree with an independent standard-library implementation", max_dev < 1e-12, f"max abs difference {max_dev:.1e}")
check("Selective-repeat model: alpha range with KS P >= 0.10 reproduces published 90% limits 0.094 to 0.362",
      abs(keep90.min() - 0.094) <= 1.5e-3 and abs(keep90.max() - 0.362) <= 1.5e-3, f"{keep90.min():.3f} to {keep90.max():.3f}")
if MC_REPS >= 200000:
    e = mc["all_84_tests"]["P_sum_at_or_above_observed"]
    check("Monte Carlo upper-tail probability of the 84-test total agrees with published 0.99998", abs(e["estimate"] - 0.99998) <= 5e-5, f"{e['estimate']:.6f} (se {e['standard_error']:.6f})")
    e = mc["all_84_tests_selective_repeat_model_A"]["P_sum_at_or_above_observed"]
    check("Monte Carlo under selective-repeat model agrees with published 0.6577", abs(e["estimate"] - 0.6577) <= 0.01, f"{e['estimate']:.4f} (se {e['standard_error']:.4f})")
ver = {"n_checks": len(checks), "n_passed": sum(c["passed"] for c in checks), "all_passed": all(c["passed"] for c in checks),
       "documented_discrepancies_with_secondary_table": {
           "n_rows_agreeing_with_exact_chi_square_at_2dp": int(n_exact_agree), "n_rows_differing": len(discrepancies), "rows": discrepancies},
       "checks": checks}
(RES / "verification_report.json").write_text(jdump(ver), encoding="utf-8")

print(f"F2: sum chi2 = {sum_chi2_7:.4f} (7 df), upper P = {f2_summary['p_upper_tail_fit_this_poor_or_poorer']:.4f}, lower P = {f2_summary['p_lower_tail_fit_this_close_or_closer']:.4f}")
print(f"pooled {D}:{C} = {D / C:.4f}:1, chi2 = {tp['chi_square']:.4f}, P = {tp['p_value']:.4f}; heterogeneity chi2 = {het:.4f} (6 df), P = {f2_summary['heterogeneity_p_value']:.4f}")
print(f"84 tests: Fisher organisation {chi84_fisher:.4f}; binomial organisation {chi84:.4f}; lower-tail P = {stats.chi2.cdf(chi84, 84):.2e}")
print(f"verification: {ver['n_passed']}/{ver['n_checks']} checks passed")
for c in checks:
    if not c["passed"]:
        print("  FAILED:", c["check"], "|", c["detail"])
