#!/usr/bin/env python3
"""
FAW biopesticide study (Dlamini, Ngadze, Chiuraise) -- reanalysis script, October 2026 revision.

Reproduces every number, table and figure in the revised manuscript.
Inputs (same folder): FAW_field_counts_tidy.csv, FAW_bioassay_exp1_per_vial.csv
Outputs: results/  (CSV/TXT tables, Fig1_field_efficacy.{png,tiff}, Fig2_bioassay_time_course.{png,tiff})
Requires: Python >= 3.10, numpy, pandas, scipy, statsmodels, matplotlib, jax (CPU), pillow.
Run:  python FAW_reanalysis.py        (about 3-5 minutes on a laptop)

Only the Muzarabani field trial is analysed. The numeric treatment key of the second field trial (RARS)
could not be verified, so RARS rows in the tidy file are deliberately ignored.
"""
import itertools, os, sys, time
from fractions import Fraction
from math import comb
import numpy as np, pandas as pd
from scipy.optimize import minimize
from scipy.stats import chi2, norm, kstest
import jax, jax.numpy as jnp
from jax.scipy.special import gammaln, logsumexp
import statsmodels.api as sm
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
jax.config.update("jax_enable_x64", True)
HERE = os.path.dirname(os.path.abspath(__file__)); os.chdir(HERE); os.makedirs("results", exist_ok=True)
rng = np.random.default_rng(20261002)
OUT = open("results/analysis_log.txt", "w")
def log(*a):
    s = " ".join(str(x) for x in a); print(s); OUT.write(s + "\n"); OUT.flush()

# =====================================================================================================
# 1. LABORATORY BIOASSAY (Experiment 1): vial = experimental unit, 4 second-instar larvae per vial
# =====================================================================================================
TRT = ["Untreated", "Super Dash", "Delfin", "Dynamo", "ACHTA"]
bio = pd.read_csv("FAW_bioassay_exp1_per_vial.csv")
bio["Treatment"] = pd.Categorical(bio["Treatment"], TRT)
DAYS = [1, 3, 7, 10, 14]; DCOL = ["d1", "d3", "d7", "d10", "d14"]
for i, day in enumerate(DAYS):                       # cumulative recorded deaths per vial (capped at 4)
    bio[f"c{day}"] = np.minimum(bio[DCOL[: i + 1]].sum(axis=1), 4)
bio["y"] = bio["c14"]

cum = bio.groupby("Treatment", observed=True)[[f"c{d}" for d in DAYS]].mean() * 25.0       # % mortality
ctl = cum.loc["Untreated", "c14"] / 100
cum["Abbott14"] = 100 * (cum["c14"] / 100 - ctl) / (1 - ctl)
cum.loc["Untreated", "Abbott14"] = np.nan
cum.round(2).to_csv("results/bioassay_cumulative_mortality.csv")
log("Cumulative mortality (%) by DAT and Abbott-corrected 14 DAT\n", cum.round(2))

# omnibus quasi-binomial GLM F test (Pearson-based dispersion), as car::Anova(test='F')
X = pd.get_dummies(bio["Treatment"], drop_first=True).astype(float); X.insert(0, "const", 1.0)
endog = np.column_stack([bio.y, 4 - bio.y])
g1 = sm.GLM(endog, X, family=sm.families.Binomial()).fit(scale="X2")
g0 = sm.GLM(endog, X[["const"]], family=sm.families.Binomial()).fit(scale="X2")
Fval = ((g0.deviance - g1.deviance) / 4) / (g1.pearson_chi2 / g1.df_resid)
log(f"Quasi-binomial omnibus F(4,{int(g1.df_resid)}) = {Fval:.3f}, P = {__import__('scipy').stats.f.sf(Fval, 4, g1.df_resid):.1e}")

def exact_perm_p(x, y):
    """Exact two-sided randomisation test (difference in mean deaths per vial); vial counts take values 0..4."""
    pool = np.concatenate([x, y]); n, N = len(x), len(pool)
    cnt = [int((pool == k).sum()) for k in range(5)]; tot = comb(N, n); obs = abs(x.mean() - y.mean()); S = pool.sum()
    p = Fraction(0)
    def rec(k, rem, a, s):
        nonlocal p
        if k == 5:
            if rem == 0 and abs(s / n - (S - s) / (N - n)) >= obs - 1e-12:
                w = 1
                for kk in range(5): w *= comb(cnt[kk], a[kk])
                p += Fraction(w, tot)
            return
        for ak in range(0, min(cnt[k], rem) + 1): rec(k + 1, rem - ak, a + [ak], s + k * ak)
    rec(0, n, [], 0); return float(p)

def pairwise_table(d):
    rows = []
    for a, b in itertools.combinations(TRT, 2):
        x = d[d.Treatment == a].y.values; y = d[d.Treatment == b].y.values
        rows.append((a, b, 100 * (x.mean() - y.mean()) / 4, exact_perm_p(x, y)))
    r = pd.DataFrame(rows, columns=["A", "B", "diff_pct_points_A_minus_B", "P_exact"]).sort_values("P_exact").reset_index(drop=True)
    m = len(r); adj = []; prev = 0.0
    for i, p in enumerate(r.P_exact): prev = max(prev, min(1.0, (m - i) * p)); adj.append(prev)      # Holm
    r["P_Holm"] = adj; return r
pw = pairwise_table(bio); pw.to_csv("results/bioassay_pairwise_exact_Holm.csv", index=False)
log("\nExact randomisation tests, Holm-adjusted across ten pairs (all recorded deaths)\n", pw.round(5))

flag = {("ACHTA", 3), ("ACHTA", 6), ("ACHTA", 15), ("Delfin", 44), ("Super Dash", 49)}
b2 = bio[~bio.apply(lambda r: (r.Treatment, r.vial) in flag, axis=1)]
pw2 = pairwise_table(b2); pw2.to_csv("results/bioassay_pairwise_exact_Holm_omit5vials.csv", index=False)
m2 = (b2.groupby("Treatment", observed=True).y.sum() / (b2.groupby("Treatment", observed=True).y.count() * 4) * 100)
log("\nSensitivity: five vials with inconsistent counts omitted; mortality %\n", m2.round(2).to_dict(), b2.groupby("Treatment", observed=True).y.count().to_dict(), "\n", pw2.round(5))
b3 = bio.copy()
for t, v in [("ACHTA", 15), ("Delfin", 44), ("Super Dash", 49)]: b3.loc[(b3.Treatment == t) & (b3.vial == v), "y"] += 1
log("\nBound: the three larvae unaccounted for at 14 DAT (vials 15, 44, 49) counted as dead; mortality %",
    (b3.groupby("Treatment", observed=True).y.sum() / 64 * 100).round(2).to_dict())
bio[bio.vial.isin([3, 6, 15, 44, 49])].query("Treatment in ['ACHTA','Delfin','Super Dash']")[["Treatment", "vial"] + DCOL + ["l1", "l3", "l7", "l10", "l14"]].to_csv("results/bioassay_flagged_vials.csv", index=False)

# ---- speed of kill: interval-censored Weibull AFT (cluster-robust, vial) ----
tb = [0, 1, 3, 7, 10, 14]; rows = []
for _, r in bio.iterrows():
    dd = [r.d1, r.d3, r.d7, r.d10, r.d14]; left = 4
    for k in range(5):
        n = int(min(dd[k], left)); rows += [((r.Treatment, r.vial), r.Treatment, max(tb[k], 0.01), tb[k + 1])] * n; left -= n
    rows += [((r.Treatment, r.vial), r.Treatment, 14.0, np.inf)] * left          # unaccounted larvae: right-censored at 14 d
S = pd.DataFrame(rows, columns=["vial", "Treatment", "t1", "t2"]); S = S[S.Treatment != "Untreated"].reset_index(drop=True)
lv = ["Super Dash", "Delfin", "Dynamo", "ACHTA"]
XL = np.column_stack([np.ones(len(S))] + [(S.Treatment == l).astype(float).values for l in lv[1:]])
t1, t2 = S.t1.values, S.t2.values
def _surv(t, mu, s):
    with np.errstate(over="ignore", divide="ignore"): return np.where(np.isinf(t), 0.0, np.exp(-np.exp((np.log(t) - mu) / s)))
def _contrib(par):
    mu = XL @ par[:4]; s = np.exp(par[4]); return np.log(np.maximum(_surv(t1, mu, s) - _surv(t2, mu, s), 1e-300))
def _grad(f, x, h=1e-5):
    g = np.zeros(len(x))
    for i in range(len(x)): e = np.zeros(len(x)); e[i] = h; g[i] = (f(x + e) - f(x - e)) / (2 * h)
    return g
nll_w = lambda p: -_contrib(p).sum()
o = minimize(nll_w, [1.2, 1, 1, 1, -0.3], method="BFGS"); o = minimize(nll_w, o.x, method="Nelder-Mead", options=dict(xatol=1e-10, fatol=1e-12, maxiter=20000))
pw_par = o.x
Hm = np.array([(_grad(nll_w, pw_par + e) - _grad(nll_w, pw_par - e)) / 2e-4 for e in np.eye(5) * 1e-4]); Hm = (Hm + Hm.T) / 2; Hi = np.linalg.inv(Hm)
sc = np.column_stack([(_contrib(pw_par + e) - _contrib(pw_par - e)) / 2e-5 for e in np.eye(5) * 1e-5])
Gv = pd.DataFrame(sc).groupby(S.vial.astype(str).values).sum().values; Vrob = Hi @ (Gv.T @ Gv) @ Hi
def LTq(par, k, p): return par[0] + (par[k] if k > 0 else 0) + np.exp(par[4]) * np.log(-np.log(1 - p))
lt = []
for k, l in enumerate(lv):
    row = {"Treatment": l}
    for p in (0.5, 0.9):
        f = lambda q: LTq(q, k, p); gr = _grad(f, pw_par); se = np.sqrt(gr @ Vrob @ gr); e = f(pw_par)
        row.update({f"LT{int(p*100)}": np.exp(e), f"LT{int(p*100)}_lo": np.exp(e - 1.96 * se), f"LT{int(p*100)}_hi": np.exp(e + 1.96 * se)})
    lt.append(row)
lt = pd.DataFrame(lt); lt.round(3).to_csv("results/bioassay_LT50_LT90.csv", index=False); log("\nLethal times (days), Weibull AFT, 95% CI on log scale, cluster-robust by vial\n", lt.round(2))
Lm = np.array([[0, 1, -1, 0, 0], [0, 0, 1, -1, 0]], float); bb = Lm @ pw_par; W = bb @ np.linalg.solve(Lm @ Vrob @ Lm.T, bb)
log(f"Equality of the three biopesticides (cluster-robust Wald): chi2(2) = {W:.2f}, P = {chi2.sf(W, 2):.3f}")
zs = pw_par[1:4] / np.sqrt(np.diag(Vrob)[1:4]); log("Each biopesticide vs Super Dash on log-time scale: z =", zs.round(2), "P =", (2 * norm.sf(abs(zs))).round(6))

# =====================================================================================================
# 2. FIELD TRIAL -- Muzarabani only
# =====================================================================================================
ORDER = ["UC", "SD", "DE1", "DE2", "DE3", "D1", "D2", "D3", "A1", "A2", "A3"]
LABEL = {"UC": "Untreated control", "SD": "Super Dash", "DE1": "Delfin +10%", "DE2": "Delfin label", "DE3": "Delfin −10%",
         "D1": "Dynamo +10%", "D2": "Dynamo label", "D3": "Dynamo −10%", "A1": "ACHTA +10%", "A2": "ACHTA label", "A3": "ACHTA −10%"}
F = pd.read_csv("FAW_field_counts_tidy.csv"); M = F[F.Site == "Muzarabani"].copy()
PLOTS = [(b, t) for t in ORDER for b in (1, 2, 3)]; P = len(PLOTS); Y = np.zeros((P, 15, 3))
for i, (b, t) in enumerate(PLOTS):
    s = M[(M.Block == b) & (M.Treatment == t)].sort_values("Plant"); assert len(s) == 15; Y[i] = s[["Live7", "Live10", "Live14"]].values

def make_nll(Y, Xp, K=25, fix_lsd=None):
    """NB2 GLMM: random intercepts for plot and for plant within plot, integrated by Gauss-Hermite quadrature (K nodes per level)."""
    z, w = np.polynomial.hermite_e.hermegauss(K); lw = jnp.log(jnp.asarray(w / np.sqrt(2 * np.pi))); z = jnp.asarray(z)
    Y = jnp.asarray(Y, dtype=jnp.float64); Xp = jnp.asarray(Xp, dtype=jnp.float64); k = Xp.shape[2]; lgY = gammaln(Y + 1.0)
    def nll(par):
        beta = par[:k]; lth = par[k]; sp = jnp.exp(par[k + 1]); sd = jnp.exp(par[k + 2] if fix_lsd is None else fix_lsd); th = jnp.exp(lth)
        eta = jnp.einsum("ptk,k->pt", Xp, beta)
        lm = eta[:, None, None, None, :] + sp * z[None, :, None, None, None] + sd * z[None, None, None, :, None]
        Yb = Y[:, None, :, None, :]; lse = jnp.logaddexp(lth, lm)
        lp = gammaln(Yb + th) - gammaln(th) - lgY[:, None, :, None, :] + th * (lth - lse) + Yb * (lm - lse)
        inner = logsumexp(lp.sum(-1) + lw[None, None, None, :], axis=3)
        return -logsumexp(inner.sum(-1) + lw[None, :], axis=1).sum()
    return jax.jit(nll), jax.jit(jax.grad(nll)), jax.jit(jax.hessian(nll))
def fit(Y, Xp, K=25, x0=None, fix_lsd=None):
    nll, g, h = make_nll(Y, Xp, K, fix_lsd); k = Xp.shape[2]
    if x0 is None:
        x0 = np.zeros(k + (3 if fix_lsd is None else 2)); x0[0] = -1.0; x0[k + 1] = np.log(0.4)
        if fix_lsd is None: x0[k + 2] = np.log(0.5)
    f = lambda p: float(nll(jnp.asarray(p))); gr = lambda p: np.asarray(g(jnp.asarray(p)))
    r = minimize(f, x0, jac=gr, method="BFGS", options=dict(gtol=1e-6, maxiter=3000)); r = minimize(f, r.x, jac=gr, method="BFGS", options=dict(gtol=1e-7, maxiter=3000))
    H = np.asarray(h(jnp.asarray(r.x))); return dict(par=r.x, nll=r.fun, V=np.linalg.inv(H), k=k, grad=float(np.abs(gr(r.x)).max()), mineig=float(np.linalg.eigvalsh(H).min()))
def design(plots, levels, block=True, date=True):
    out = []
    for (b, t) in plots:
        per = []
        for ti in range(3):
            x = [1.0] + [float(t == l) for l in levels[1:]]
            if block: x += [float(b == 2), float(b == 3)]
            if date: x += [float(ti == 1), float(ti == 2)]
            per.append(x)
        out.append(per)
    return np.array(out)
def mvn_adj(z, C, nsim=400000):
    """Simultaneous (Dunnett / Tukey-type) adjustment from the joint asymptotic normal distribution of the estimates."""
    se = np.sqrt(np.diag(C)); dr = rng.multivariate_normal(np.zeros(len(z)), C, nsim) / se; mx = np.abs(dr).max(1)
    return np.quantile(mx, 0.95), np.array([(mx >= abs(v)).mean() for v in z])
def wald(par, V, idx): bb = par[idx]; W = bb @ np.linalg.solve(V[np.ix_(idx, idx)], bb); return W, len(idx), chi2.sf(W, len(idx))

nT = 10; Xp = design(PLOTS, ORDER); res = fit(Y, Xp); k = res["k"]; par, V = res["par"], res["V"]
log(f"\nPRIMARY FIELD MODEL (Muzarabani): theta={np.exp(par[k]):.2f}, SD plot={np.exp(par[k+1]):.3f}, SD plant={np.exp(par[k+2]):.3f}; max|gradient|={res['grad']:.1e}; smallest Hessian eigenvalue={res['mineig']:.3f}")
b = par[1:1 + nT]; C = V[1:1 + nT, 1:1 + nT]; se = np.sqrt(np.diag(C)); crit, padj = mvn_adj(b / se, C)
eff = pd.DataFrame({"Treatment": ORDER[1:], "rate_ratio": np.exp(b), "efficacy_pct": 100 * (1 - np.exp(b)), "lo": 100 * (1 - np.exp(b + crit * se)),
                    "hi": 100 * (1 - np.exp(b - crit * se)), "P_Dunnett": padj})
obs = M.assign(live=M[["Live7", "Live10", "Live14"]].sum(axis=1)).groupby("Treatment").live.sum() / 135.0
eff["observed_mean_live_per_plant_visit"] = eff.Treatment.map(obs); eff["observed_reduction_pct"] = 100 * (1 - eff.Treatment.map(obs) / obs["UC"])
eff.round(5).to_csv("results/field_efficacy_vs_control_Muzarabani.csv", index=False); log(f"Dunnett critical value {crit:.3f}\n", eff.round(3))
log("Observed mean live larvae per plant visit (7-14 DAT):", obs.reindex(ORDER).round(3).to_dict())
log("Wald treatment %.1f (df %d) P=%.2e | date %.2f (df %d) P=%.2e | block %.2f (df %d) P=%.3f" % (*wald(par, V, list(range(1, 11))), *wald(par, V, [13, 14]), *wald(par, V, [11, 12])))
Xp0 = design(PLOTS, ORDER, block=False); r0 = fit(Y, Xp0, x0=np.r_[par[:11], par[13:15], par[k:]])
lr = 2 * (r0["nll"] - res["nll"]); log(f"No-block model: efficacy {(100*(1-np.exp(r0['par'][1:11]))).round(1)}; LR test for block chi2(2)={lr:.2f}, P={chi2.sf(lr,2):.3f}")
idx = {t: i for i, t in enumerate(ORDER)}
def lincon(par, V, L): e = L @ par; s = np.sqrt(L @ V @ L); return np.exp(e), np.exp(e - 1.96 * s), np.exp(e + 1.96 * s), 2 * norm.sf(abs(e / s))
rows = []
for name, mem in [("Delfin (3 rates)", ["DE1", "DE2", "DE3"]), ("Dynamo (3 rates)", ["D1", "D2", "D3"]), ("ACHTA (3 rates)", ["A1", "A2", "A3"])]:
    L = np.zeros(len(par)); [L.__setitem__(idx[m], 1 / 3) for m in mem]; L[idx["SD"]] -= 1; rows.append((name + " vs Super Dash", *lincon(par, V, L)))
for t in ORDER[2:]:
    L = np.zeros(len(par)); L[idx[t]] = 1; L[idx["SD"]] -= 1; rows.append((LABEL[t] + " vs Super Dash", *lincon(par, V, L)))
vs = pd.DataFrame(rows, columns=["contrast", "rate_ratio", "lo95", "hi95", "P_unadjusted"]); vs.round(4).to_csv("results/field_vs_SuperDash_Muzarabani.csv", index=False); log("\nDirect contrasts with Super Dash (not adjusted)\n", vs.round(3))
keep = [i for i, (bk, t) in enumerate(PLOTS) if not (t == "SD" and bk == 3)]; rk = fit(Y[keep], Xp[keep], x0=par)
log("Sensitivity, Super Dash block-3 plot (30 of 34 live larvae) omitted: efficacy", (100 * (1 - np.exp(rk["par"][1:11]))).round(1))
for name, mem in [("Delfin", ["DE1", "DE2", "DE3"]), ("Dynamo", ["D1", "D2", "D3"])]:
    L = np.zeros(len(par)); [L.__setitem__(idx[m], 1 / 3) for m in mem]; L[idx["SD"]] -= 1; r_, lo_, hi_, p_ = lincon(rk["par"], rk["V"], L)
    log(f"   {name} (3 rates) / Super Dash: rate ratio {r_:.2f} (95% CI {lo_:.2f}-{hi_:.2f})")
# ---- time course: one model per assessment date (plot random effect; plant effect not identifiable with one count per plant) ----
rows = []
for di, dat in enumerate([7, 10, 14]):
    Xd = design(PLOTS, ORDER, date=False)[:, di:di + 1, :]; rd = fit(Y[:, :, di:di + 1], Xd, x0=np.r_[-1, np.zeros(12), 0.0, np.log(0.4)], fix_lsd=-12.0)
    e = rd["par"][1:11]; Cd = rd["V"][1:11, 1:11]; sd_ = np.sqrt(np.diag(Cd)); cr, pa = mvn_adj(e / sd_, Cd)
    for j in range(10): rows.append(dict(DAT=dat, Treatment=ORDER[1 + j], efficacy_pct=100 * (1 - np.exp(e[j])), lo=100 * (1 - np.exp(e[j] + cr * sd_[j])), hi=100 * (1 - np.exp(e[j] - cr * sd_[j])), P_Dunnett=pa[j]))
ts = pd.DataFrame(rows); ts.round(4).to_csv("results/field_efficacy_by_DAT_Muzarabani.csv", index=False)
log("\nEfficacy % by assessment date\n", ts.pivot(index="Treatment", columns="DAT", values="efficacy_pct").reindex(ORDER[1:]).round(0), "\nP (Dunnett)\n", ts.pivot(index="Treatment", columns="DAT", values="P_Dunnett").reindex(ORDER[1:]).round(3))
# ---- product x dose among the biopesticide plots ----
bio_t = [t for t in ORDER if t not in ("UC", "SD")]; bp = [(b_, t) for t in bio_t for b_ in (1, 2, 3)]; Yb = np.array([Y[PLOTS.index(p)] for p in bp])
def Xpd(inter):
    out = []
    for (b_, t) in bp:
        pr, ds = t[:-1], int(t[-1]); per = []
        for ti in range(3):
            x = [1.0, float(pr == "D"), float(pr == "A"), float(ds == 2), float(ds == 3), float(b_ == 2), float(b_ == 3), float(ti == 1), float(ti == 2)]
            if inter: x += [float(pr == "D" and ds == 2), float(pr == "D" and ds == 3), float(pr == "A" and ds == 2), float(pr == "A" and ds == 3)]
            per.append(x)
        out.append(per)
    return np.array(out)
ra = fit(Yb, Xpd(False)); pa_, Va = ra["par"], ra["V"]; ri = fit(Yb, Xpd(True), x0=np.r_[pa_[:9], np.zeros(4), pa_[9:]])
log("\nPRODUCT x DOSE (biopesticide plots): product chi2(2)=%.2f P=%.2e | dose chi2(2)=%.2f P=%.3f | date chi2(2)=%.2f P=%.4f | product x dose chi2(4)=%.2f P=%.3f" % (
    wald(pa_, Va, [1, 2])[0], wald(pa_, Va, [1, 2])[2], wald(pa_, Va, [3, 4])[0], wald(pa_, Va, [3, 4])[2], wald(pa_, Va, [7, 8])[0], wald(pa_, Va, [7, 8])[2],
    wald(ri["par"], ri["V"], [9, 10, 11, 12])[0], wald(ri["par"], ri["V"], [9, 10, 11, 12])[2]))
Ls = np.zeros((3, len(pa_))); Ls[0, 1] = 1; Ls[1, 2] = 1; Ls[2, 1] = -1; Ls[2, 2] = 1; est = Ls @ pa_; Cp = Ls @ Va @ Ls.T; sp_ = np.sqrt(np.diag(Cp))
dr = rng.multivariate_normal(np.zeros(2), Va[np.ix_([1, 2], [1, 2])], 400000); Zs = np.column_stack([dr[:, 0], dr[:, 1], dr[:, 1] - dr[:, 0]]) / sp_
mx = np.abs(Zs).max(1); cr = np.quantile(mx, 0.95)
for n, e, s_ in zip(["Dynamo/Delfin", "ACHTA/Delfin", "ACHTA/Dynamo"], est, sp_): log(f"   {n}: rate ratio {np.exp(e):.2f} (95% CI {np.exp(e-cr*s_):.2f}-{np.exp(e+cr*s_):.2f}); Tukey-type P = {(mx>=abs(e/s_)).mean():.4f}")
# ---- model checks by simulation ----
eta = np.einsum("ptk,k->pt", Xp, par[:k]); th = np.exp(par[k]); sp, sdv = np.exp(par[k + 1]), np.exp(par[k + 2]); NS = 2000
tots = np.zeros((NS, P)); z0 = np.zeros(NS); mc = np.zeros(NS); ot = Y.sum((1, 2))
for s in range(NS):
    mu = np.exp(eta[:, None, :] + rng.normal(0, sp, P)[:, None, None] + rng.normal(0, sdv, (P, 15, 1))); ys = rng.negative_binomial(th, th / (th + mu))
    tots[s] = ys.sum((1, 2)); z0[s] = (ys == 0).mean(); mc[s] = ys.max()
pit = np.array([(tots[:, i] < ot[i]).mean() + rng.uniform() * (tots[:, i] == ot[i]).mean() for i in range(P)])
log(f"\nModel checks: proportion of zero counts observed {(Y==0).mean():.3f}, simulated {z0.mean():.3f} (95% {np.quantile(z0,.025):.3f}-{np.quantile(z0,.975):.3f}); maximum count observed {int(Y.max())}, simulated median {np.median(mc):.0f} (95% {np.quantile(mc,.025):.0f}-{np.quantile(mc,.975):.0f})")
log(f"   plot totals: {np.mean((ot>=np.quantile(tots,.025,axis=0))&(ot<=np.quantile(tots,.975,axis=0))):.2f} inside simulated 95% intervals; PIT uniformity KS P = {kstest(pit,'uniform').pvalue:.2f}")
# ---- block-restricted randomisation tests on plot totals ----
tot = Y.sum((1, 2)); bl = np.array([b_ for b_, t in PLOTS]); tri0 = np.array([ORDER.index(t) for b_, t in PLOTS])
def ss_trt(v, tri):
    vb = v.astype(float).copy()
    for b_ in (1, 2, 3): vb[bl == b_] -= vb[bl == b_].mean()
    return sum(vb[tri == j].sum() ** 2 / (tri == j).sum() for j in range(11))
for name, v in [("raw totals", tot), ("log(1+total)", np.log1p(tot))]:
    o_ = ss_trt(v, tri0); N = 200000; c = 0
    for _ in range(N):
        tri = tri0.copy()
        for b_ in (1, 2, 3): m = np.where(bl == b_)[0]; tri[m] = rng.permutation(tri0[m])
        c += ss_trt(v, tri) >= o_ - 1e-9
    log(f"Block-restricted randomisation test, overall treatment effect ({name}): P = {(c+1)/(N+1):.4f}")
bi = np.array([i for i, (b_, t) in enumerate(PLOTS) if t not in ("UC", "SD")]); btot = tot[bi]; pr_a = np.array([PLOTS[i][1][:-1] for i in bi]); bk_a = bl[bi]; ds_a = np.array([int(PLOTS[i][1][-1]) for i in bi])
def ss_dose(v, d):
    vv = v.astype(float).copy()
    for pr in ("DE", "D", "A"):
        for b_ in (1, 2, 3): m = (pr_a == pr) & (bk_a == b_); vv[m] -= vv[m].mean()
    return sum(vv[d == j].sum() ** 2 / (d == j).sum() for j in (1, 2, 3))
for name, v in [("raw totals", btot), ("log(1+total)", np.log1p(btot))]:
    o_ = ss_dose(v, ds_a); N = 100000; c = 0
    for _ in range(N):
        d_ = ds_a.copy()
        for pr in ("DE", "D", "A"):
            for b_ in (1, 2, 3): m = np.where((pr_a == pr) & (bk_a == b_))[0]; d_[m] = rng.permutation(ds_a[m])
        c += ss_dose(v, d_) >= o_ - 1e-9
    log(f"Dose-label permutation within product and block ({name}): P = {(c+1)/(N+1):.3f}")
pt = pd.DataFrame([(t, b_, tot[i], tot[i] / 45) for i, (b_, t) in enumerate(PLOTS)], columns=["Treatment", "Block", "live_total_7_14DAT", "mean_per_plant_visit"]); pt.to_csv("results/field_plot_totals_Muzarabani.csv", index=False)

# =====================================================================================================
# 3. FIGURES
# =====================================================================================================
plt.rcParams.update({"font.family": ["Arial", "Liberation Sans", "DejaVu Sans"], "font.size": 8, "axes.linewidth": 0.7})
cols = {"UC": "#555555", "SD": "#D55E00", "DE": "#0072B2", "D": "#009E73", "A": "#CC79A7"}
col_of = lambda t: cols[t] if t in cols else cols[t[:-1]]
fig, ax = plt.subplots(1, 2, figsize=(17 / 2.54, 10 / 2.54), sharey=True, gridspec_kw=dict(width_ratios=[1.15, 1], wspace=0.12))
ys = {t: len(ORDER) - 1 - i for i, t in enumerate(ORDER)}
e_ = eff.set_index("Treatment")
for t in ORDER[1:]:
    r = e_.loc[t]; c = col_of(t); sig = r.P_Dunnett < 0.05
    ax[0].plot([max(r.lo, -130), r.hi], [ys[t]] * 2, color=c, lw=1.2); ax[0].plot(r.efficacy_pct, ys[t], "o", color=c, mfc=c if sig else "white", ms=5.5, mew=1.2)
ax[0].axvline(0, color="grey", ls="--", lw=0.8); ax[0].set_xlim(-130, 100); ax[0].set_yticks([ys[t] for t in ORDER]); ax[0].set_yticklabels([LABEL[t] for t in ORDER])
ax[0].set_xlabel("Reduction in live larvae per plant\nvs untreated control (%; 95% CI)"); ax[0].text(0.01, 0.99, "a", transform=ax[0].transAxes, fontweight="bold", va="top", fontsize=10)
ax[0].annotate("reference", (0, ys["UC"]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=7, color="#555555")
for t in ORDER:
    v = pt[pt.Treatment == t].mean_per_plant_visit.values; jit = np.array([-0.12, 0, 0.12])
    ax[1].plot(v, ys[t] + jit, "o", color=col_of(t), ms=4, alpha=0.85, mew=0); ax[1].plot([v.mean()] * 2, [ys[t] - 0.3, ys[t] + 0.3], color="black", lw=1.2)
ax[1].set_xlabel("Live larvae per plant visit, each plot\n(mean of 45 visits, 7–14 DAT)"); ax[1].set_xlim(-0.05, 2.0); ax[1].text(0.01, 0.99, "b", transform=ax[1].transAxes, fontweight="bold", va="top", fontsize=10)
for a in ax: a.spines[["top", "right"]].set_visible(False)
fig.savefig("results/Fig1_field_efficacy.png", dpi=600, bbox_inches="tight"); fig.savefig("results/Fig1_field_efficacy.pdf", bbox_inches="tight"); fig.savefig("results/Fig1_field_efficacy.tiff", dpi=600, bbox_inches="tight", pil_kwargs={"compression": "tiff_lzw"}); plt.close(fig)

fig, axs = plt.subplots(2, 3, figsize=(17 / 2.54, 10.5 / 2.54), sharex=True, sharey=True); axs = axs.ravel()
tc = {"Untreated": "#555555", "Super Dash": "#D55E00", "Delfin": "#0072B2", "Dynamo": "#009E73", "ACHTA": "#CC79A7"}; xs = np.array(DAYS)
for a, t in zip(axs[:5], TRT):
    d = bio[bio.Treatment == t]
    for _, r in d.iterrows(): a.plot(xs + rng.uniform(-0.25, 0.25), [r[f"c{x}"] * 25 for x in DAYS], "-", color=tc[t], alpha=0.25, lw=0.8)
    a.plot(xs, d[[f"c{x}" for x in DAYS]].mean() * 25, "-o", color=tc[t], lw=2, ms=4, zorder=5)
    a.set_title(t, fontsize=8.5, loc="left", fontweight="bold")
for t in TRT: axs[5].plot(xs, bio[bio.Treatment == t][[f"c{x}" for x in DAYS]].mean() * 25, "-o", color=tc[t], lw=1.6, ms=3.5, label=t)
axs[5].set_title("Treatment means", fontsize=8.5, loc="left", fontweight="bold"); axs[5].legend(frameon=False, fontsize=7, loc="upper center", bbox_to_anchor=(0.5, -0.32), ncol=3, columnspacing=0.8, handlelength=1.6)
for a in axs: a.set_xticks(DAYS); a.spines[["top", "right"]].set_visible(False); a.set_ylim(-3, 103)
for a in axs[3:]: a.set_xlabel("Days after treatment")
for a in axs[::3]: a.set_ylabel("Cumulative mortality (%)")
fig.tight_layout(); fig.savefig("results/Fig2_bioassay_time_course.png", dpi=600, bbox_inches="tight"); fig.savefig("results/Fig2_bioassay_time_course.pdf", bbox_inches="tight"); fig.savefig("results/Fig2_bioassay_time_course.tiff", dpi=600, bbox_inches="tight", pil_kwargs={"compression": "tiff_lzw"}); plt.close(fig)
log("\nDone.")
