# (c) 2026 William J. Dwyer. Free and open-source software under the MIT License (see LICENSE).
# If you use or build upon this software, please retain this notice and cite the accompanying
# methodology paper together with the archived software (Zenodo DOI: 10.5281/zenodo.20709963).
"""Figure: where CV-ratio departures from 1 break the pooled log-t, by n-imbalance."""
import json, numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt

d = json.load(open("cvratio_cutoffs.json"))
cur = d["curves"]
ms = ["1.0","1.5","2.0","3.0","4.0"]
labels = {"1.0":"1 : 1 (balanced)","1.5":"1.5 : 1","2.0":"2 : 1","3.0":"3 : 1","4.0":"4 : 1"}
cols = ["#3a7d44","#7DA0CA","#f0a500","#e8702a","#c0392b"]

fig, ax = plt.subplots(figsize=(9.2, 5.6))
# tolerance band 0.04-0.06
ax.axhspan(0.04, 0.06, color="#2e7d32", alpha=0.10, zorder=0)
ax.axhline(0.05, color="#555", lw=1.0, ls="-", zorder=1)
ax.axvline(1.0, color="#888", lw=1.0, ls=":", zorder=1)

for m, c in zip(ms, cols):
    r = cur[m]["ratio"]; p = cur[m]["pool"]
    ax.plot(r, p, color=c, lw=2.4, label=labels[m], zorder=3)
# Welch reference (flat) from the 3:1 curve's welch
ax.plot(cur["3.0"]["ratio"], cur["3.0"]["welch"], color="#444", lw=1.4, ls="--",
        label="Welch (any imbalance)", zorder=2)

ax.set_xlim(0.35, 3.2); ax.set_ylim(0, 0.18)
ax.set_xlabel("CV ratio  =  CV(smaller-n arm) / CV(larger-n arm)", fontsize=11)
ax.set_ylabel("Pooled log-t type-I error (nominal 0.05)", fontsize=11)
ax.set_title("Where heteroscedasticity breaks the pooled log-t: CV-ratio cutoffs by sample-size imbalance",
             fontsize=11.5, fontweight="bold")
ax.text(0.55, 0.165, "← conservative\n   (power lost)", fontsize=9, color="#1f5130", va="top")
ax.text(2.05, 0.165, "liberal →\n(false positives)", fontsize=9, color="#7a1414", va="top")
ax.text(0.37, 0.067, "tolerance band 0.04–0.06", fontsize=8.5, color="#2e7d32", ha="left")
ax.grid(alpha=0.25)
ax.legend(title="n imbalance (larger : smaller)", fontsize=9, title_fontsize=9, loc="upper left", framealpha=0.9)
fig.tight_layout()
fig.savefig("fig_cvratio_cutoffs.png", dpi=200, bbox_inches="tight", metadata={"Author": "William J. Dwyer (ORCID 0009-0004-0855-7222)", "Title": "fig_cvratio_cutoffs", "Subject": "Generated by fig_cvratio_cutoffs.py for the Comparable-Strata Designer; MIT License; cite Zenodo DOI 10.5281/zenodo.20709963"})
print("saved fig_cvratio_cutoffs.png")
