"""Figures for the PTP1B comparison. Every panel is drawn ONLY from result tables.

No coordinates are read here. For each figure the manifest
(figures/figure_manifest.json) records the source table(s), their SHA-256 at plot
time, and the plotted key values, so verification_tests.py can confirm that the
figures correspond to the current tables. Captions: figures/figure_captions.md
"""
import json, hashlib, textwrap
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

ROOT = Path(__file__).resolve().parents[1]
RES, FIG = ROOT / "results", ROOT / "figures"
FIG.mkdir(exist_ok=True)
COL = {"5K9W": "#1f4e79", "5K9V": "#d9822b", "1T49": "#2a9d8f", "1SUG": "#8a8f98"}
PAIRCOL = {("5K9V", "5K9W"): "#b5532a", ("1T49", "5K9W"): "#1f7a6d", ("1T49", "5K9V"): "#7a6ca8"}
LAB = {"5K9W": "5K9W (TCS401, closed)", "5K9V": "5K9V (apo, open)", "1T49": "1T49 (ligand 892)", "1SUG": "1SUG (apo, suppl.)"}
plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False, "axes.titlesize": 11,
                     "axes.titleweight": "bold", "figure.dpi": 110, "savefig.dpi": 170, "font.family": "DejaVu Sans"})
MANIFEST, CAPTIONS = {}, []


def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def finish(fig, name, title, caption, sources, key_values, entries="5K9W, 5K9V, 1T49"):
    src = "Source table: " + ", ".join(sources) + f" (computed from wwPDB entries {entries}; chain A)"
    fig.text(0.01, 0.005, src, fontsize=7.5, color="#555555", ha="left", va="bottom")
    fig.savefig(FIG / f"{name}.png", bbox_inches="tight", facecolor="white")
    plt.close(fig)
    MANIFEST[name] = dict(file=f"figures/{name}.png", title=title, caption=caption, source_tables={s: sha(ROOT / s) for s in sources},
                          key_values=key_values)
    CAPTIONS.append(f"## {name} — {title}\n\n![{title}]({name}.png)\n\n{caption}\n\n*Data source:* " + ", ".join(f"`{s}`" for s in sources) + "\n")


def pair_label(m, r):
    return f"{m} → {r}"


def fig1():
    d = pd.read_csv(RES / "per_residue_displacement.csv")
    d = d[d.fit_definition.str.startswith("core")]
    fig, axes = plt.subplots(3, 1, figsize=(10, 7.6), sharex=True)
    kv = {}
    for ax, ((m, r), g) in zip(axes, d.groupby(["mobile", "reference"], sort=False)):
        ax.axvspan(175.5, 187.5, color="#f2d9a0", alpha=0.7, lw=0)
        ax.plot(g.resnum, g.ca_displacement_A, color=PAIRCOL[(m, r)], lw=1.2)
        ax.axhline(1.0, color="#999999", lw=0.6, ls=":")
        top = g.loc[g.ca_displacement_A.idxmax()]
        a181 = g[g.resnum == 181].ca_displacement_A.iloc[0]
        ax.annotate(f"{top.resname.title()}{top.resnum}: {top.ca_displacement_A:.2f} Å", (top.resnum, top.ca_displacement_A),
                    xytext=(top.resnum + 12 if top.resnum < 240 else top.resnum - 60, top.ca_displacement_A * 0.9), fontsize=8.5,
                    arrowprops=dict(arrowstyle="-", color="#444444", lw=0.6))
        out = g[~g.in_loop_window]
        t2 = out.loc[out.ca_displacement_A.idxmax()]
        if t2.resnum != top.resnum and t2.ca_displacement_A > 2.0:
            ax.annotate(f"{t2.resname.title()}{t2.resnum}: {t2.ca_displacement_A:.2f} Å\n(inside fit set)", (t2.resnum, t2.ca_displacement_A),
                        xytext=(t2.resnum + 7, t2.ca_displacement_A * 0.62), fontsize=8.5, arrowprops=dict(arrowstyle="-", color="#444444", lw=0.6))
        ax.set_title(f"{pair_label(m, r)}   (Asp181 Cα: {a181:.2f} Å)", loc="left")
        ax.set_ylabel("Cα displacement (Å)")
        ax.set_ylim(0, max(6.6, g.ca_displacement_A.max() * 1.1))
        kv[f"{m}->{r}"] = dict(max_A=float(top.ca_displacement_A), max_res=int(top.resnum), asp181_A=float(a181))
    axes[0].text(174.5, 6.45, "176–187 window\n(excluded from fit)", ha="right", va="top", fontsize=8, color="#7a5a00")
    axes[-1].set_xlabel("Residue number (native PTP1B numbering, chain A)")
    axes[-1].set_xlim(0, 282)
    fig.suptitle("Per-residue Cα displacement after the common-core fit", x=0.01, ha="left", fontweight="bold", fontsize=12.5)
    fig.tight_layout(rect=(0, 0.02, 1, 0.97))
    finish(fig, "fig1_per_residue_displacement", "Per-residue Cα displacement after the common-core fit",
           "Cα displacement of each residue 2–280 after a rigid Kabsch fit on 267 Cα atoms (residues 2–280 excluding 176–187). "
           "The shaded band is the 176–187 loop window, which did not contribute to the fit. The dotted line marks 1 Å. "
           "The largest displacements against 5K9W are in the loop window (Phe182) and, inside the fit set, in the 237–243 loop (Lys239); smaller "
           "peaks occur near residues 61–63, 116 and 152. 1T49 and 5K9V are nearly superimposable in the loop window. Only residues modelled in all three entries are shown, so the C-terminal α7 segment does not appear.",
           ["results/per_residue_displacement.csv"], kv)


def fig2():
    c = pd.read_csv(RES / "structural_comparison.csv")
    c = c[c.fit_definition.str.startswith("core")]
    metrics = [("fit_rmsd_A", "Fit RMSD\n(267 Cα)"), ("rmsd_all_CA_2_280_A", "All Cα 2–280\n(279 Cα)"),
               ("loop_176_187_rmsd_fitted_frame_A", "Loop 176–187\n(12 Cα, fitted frame)"),
               ("loop_176_187_rmsd_local_refit_A", "Loop 176–187\n(12 Cα, local refit)"),
               ("asp181_CA_displacement_A", "Asp181 Cα\ndisplacement"), ("asp181_CG_displacement_A", "Asp181 Cγ\ndisplacement")]
    fig, ax = plt.subplots(figsize=(10, 4.8))
    w = 0.26
    kv = {}
    for k, row in enumerate(c.itertuples()):
        vals = [getattr(row, m) for m, _ in metrics]
        x = np.arange(len(metrics)) + (k - 1) * w
        ax.bar(x, vals, w * 0.92, color=PAIRCOL[(row.mobile, row.reference)], label=pair_label(row.mobile, row.reference))
        for xi, v in zip(x, vals):
            ax.text(xi, v + 0.12, f"{v:.2f}", ha="center", va="bottom", fontsize=8)
        kv[f"{row.mobile}->{row.reference}"] = dict(zip([m for m, _ in metrics], map(float, vals)))
    ax.set_xticks(np.arange(len(metrics)), [l for _, l in metrics], fontsize=8.8)
    ax.set_ylabel("Distance (Å)")
    ax.set_ylim(0, 10)
    ax.legend(frameon=False, title="mobile → reference", loc="upper left")
    ax.set_title("Core-definition comparison: global agreement, loop-window difference", loc="left")
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    finish(fig, "fig2_rmsd_summary", "Core-definition RMSD and Asp181 displacement",
           "Principal comparison using the research-plan definition: rigid fit on 267 Cα atoms (2–280 excluding 176–187). "
           "'Fitted frame' loop RMSD measures loop displacement relative to the rest of the domain; 'local refit' re-superposes only the 12 loop "
           "Cα atoms and therefore measures change in loop shape. Asp181 displacements are single-atom distances in the fitted frame.",
           ["results/structural_comparison.csv"], kv)


def fig3():
    c = pd.read_csv(RES / "structural_comparison.csv")
    metrics = [("fit_rmsd_A", "Fit RMSD"), ("rmsd_all_CA_2_280_A", "All Cα 2–280 RMSD"),
               ("loop_176_187_rmsd_fitted_frame_A", "Loop 176–187 RMSD"), ("asp181_CA_displacement_A", "Asp181 Cα displacement")]
    fig, axes = plt.subplots(1, 4, figsize=(11, 3.9))
    kv = {}
    for ax, (m, lab) in zip(axes, metrics):
        for k, ((mob, ref), g) in enumerate(c.groupby(["mobile", "reference"], sort=False)):
            a = g[g.fit_definition.str.startswith("core")][m].iloc[0]
            b = g[g.fit_definition.str.startswith("loop_included")][m].iloc[0]
            ax.plot([0, 1], [a, b], "-o", color=PAIRCOL[(mob, ref)], lw=1.4, ms=5, label=pair_label(mob, ref))
            ax.text(1.06, b, f"{b - a:+.3f}", va="center", fontsize=8, color=PAIRCOL[(mob, ref)])
            kv[f"{mob}->{ref}|{m}"] = dict(core=float(a), loop_included=float(b), delta=float(b - a))
        ax.set_xticks([0, 1], ["loop excluded\n(267 Cα)", "loop included\n(279 Cα)"], fontsize=8.5)
        ax.set_xlim(-0.25, 1.5)
        ax.set_title(lab, loc="left", fontsize=10)
        ax.set_ylim(0, None)
    axes[0].set_ylabel("Distance (Å)")
    axes[2].legend(frameon=False, fontsize=8, loc="center left", bbox_to_anchor=(0.0, 0.42))
    fig.suptitle("Fit-sensitivity control: does including 176–187 in the fit change the result?", x=0.01, ha="left", fontweight="bold")
    fig.tight_layout(rect=(0, 0.03, 1, 0.94))
    finish(fig, "fig3_fit_sensitivity", "Fit-sensitivity control",
           "Each quantity recomputed with the 176–187 window included in the superposition (279 Cα) instead of excluded (267 Cα). "
           "Numbers at right are the change (loop-included minus core), in Å. Including the loop raises the fit RMSD, as expected, "
           "and lowers the measured loop displacement by about 0.1 Å or less; the conclusions do not depend on this choice.",
           ["results/structural_comparison.csv"], kv)


def fig4():
    m = pd.read_csv(ROOT / "structure_mapping.csv")
    a7 = pd.read_csv(RES / "alpha7_coverage.csv")
    fig, ax = plt.subplots(figsize=(10.5, 3.9))
    ids = ["5K9W", "5K9V", "1T49"]
    kv = {}
    for k, pid in enumerate(ids):
        y = len(ids) - 1 - k
        mod = m[m[f"{pid}_modelled"]]
        ax.bar(mod.native_resnum, 0.62, bottom=y - 0.31, width=1.0, color=COL[pid], lw=0)
        st = a7.set_index("native_resnum")[f"{pid}_status"]
        nm = st[st == "in construct, not modelled"].index
        ax.bar(nm, 0.62, bottom=y - 0.31, width=1.0, color="white", edgecolor="#aaaaaa", hatch="////", lw=0.3)
        lo, hi = int(mod.native_resnum.min()), int(mod.native_resnum.max())
        ax.text(-9, y, pid, ha="right", va="center", fontweight="bold", color=COL[pid])
        ax.text(304, y, f"modelled {lo}–{hi}", va="center", fontsize=8.5)
        kv[pid] = dict(first=lo, last=hi, n_modelled=int(len(mod)), alpha7_285_296_modelled=int(((mod.native_resnum >= 285) & (mod.native_resnum <= 296)).sum()))
    for (a, b, lab, c) in ((176, 187, "loop window\n176–187", "#f2d9a0"), (285, 296, "α7 285–296\n(5K9W helix record)", "#d7c5ee")):
        ax.axvspan(a - 0.5, b + 0.5, color=c, alpha=0.55, lw=0, zorder=0)
        ax.text((a + b) / 2, 2.62, lab, ha="center", va="bottom", fontsize=8.5)
    ax.set_yticks([])
    ax.set_ylim(-0.6, 3.25)
    ax.set_xlim(-8, 338)
    ax.set_xlabel("Residue number (native PTP1B numbering)")
    ax.spines["left"].set_visible(False)
    ax.legend(handles=[Patch(facecolor="#777777", label="coordinates deposited"),
                       Patch(facecolor="white", edgecolor="#aaaaaa", hatch="////", label="in crystallised construct, no coordinates (276–301 shown)")],
              frameon=False, loc="lower left", bbox_to_anchor=(0.0, -0.42), ncol=2, fontsize=8.5)
    ax.set_title("Which residues have coordinates? α7 is observable only in 5K9W", loc="left")
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    finish(fig, "fig4_residue_coverage_alpha7", "Residue coverage and α7 observability",
           "Residues with deposited coordinates in chain A of each entry. Hatched cells are residues that were part of the crystallised construct "
           "but have no coordinates. The α7 helix (285–296 in the 5K9W helix records) is modelled only in 5K9W. Its absence from 5K9V and 1T49 "
           "means the segment was not resolved in those crystals; this is missing data, not an observed position, and no α7 displacement can be "
           "measured between these three entries.",
           ["structure_mapping.csv", "results/alpha7_coverage.csv"], kv)


def fig5():
    nb = pd.read_csv(RES / "ligand892_neighbourhood.csv").sort_values("resnum")
    lab = [f"{r.resname.title()}{r.resnum}" for r in nb.itertuples()]
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(10.5, 5.2), sharey=True)
    y = np.arange(len(nb))[::-1]
    hel = nb.deposited_1T49_helix.fillna("")
    cols = ["#2a9d8f" if "alpha3" in h else "#7a6ca8" if "alpha6" in h else "#999999" for h in hel]
    a1.barh(y, nb.min_heavy_atom_distance_A, color=cols, height=0.7)
    for c, ls in ((3.5, ":"), (4.0, "-"), (4.5, ":"), (5.0, ":")):
        a1.axvline(c, color="#333333", lw=1.0 if c == 4.0 else 0.6, ls=ls)
    a1.text(4.0, len(nb) - 0.25, "4.0 Å (declared cutoff)", fontsize=8, ha="center", va="bottom")
    a1.set_ylim(-0.7, len(nb) + 0.6)
    for yi, r in zip(y, nb.itertuples()):
        a1.text(r.min_heavy_atom_distance_A + 0.06, yi, f"{r.min_heavy_atom_distance_A:.2f}  {r.protein_atom}···{r.ligand_atom}", va="center", fontsize=7.8)
    a1.set_yticks(y, lab)
    a1.set_xlim(0, 6.6)
    a1.set_xlabel("Minimum heavy-atom distance to ligand 892 (Å)")
    a1.set_title("Closest approach", loc="left")
    a2.barh(y, nb.sasa_buried_by_ligand_A2, color=cols, height=0.7)
    for yi, v in zip(y, nb.sasa_buried_by_ligand_A2):
        a2.text(v + 1.5, yi, f"{v:.1f}", va="center", fontsize=7.8)
    a2.set_xlabel("Residue surface occluded by the ligand (Å², Shrake–Rupley)")
    a2.set_title("Solvent-accessible surface buried", loc="left")
    a2.set_xlim(0, 135)
    a2.legend(handles=[Patch(color="#2a9d8f", label="α3 (188–201)"), Patch(color="#7a6ca8", label="α6 (263–282)"), Patch(color="#999999", label="other")],
              frameon=False, loc="lower right", fontsize=8.5)
    fig.suptitle("Ligand 892 neighbourhood in 1T49 (a declared-cutoff neighbourhood, not a cavity boundary)", x=0.01, ha="left", fontweight="bold")
    fig.tight_layout(rect=(0, 0.03, 1, 0.95))
    finish(fig, "fig5_ligand892_neighbourhood", "Ligand 892 neighbourhood in 1T49",
           "Left: minimum heavy-atom distance between each listed residue and ligand 892, with the closest atom pair; vertical lines mark the 3.5, 4.0 "
           "(declared), 4.5 and 5.0 Å cutoffs. Twelve residues fall within 4.0 Å and fourteen within 5.0 Å, all on α3 or α6 or the residue preceding α3. "
           "Right: per-residue solvent-accessible surface occluded by the ligand in the deposited coordinates. These are geometric quantities from one "
           "crystal model (ligand occupancy 0.70); they are not binding energies, and no pocket volume is reported.",
           ["results/ligand892_neighbourhood.csv"],
           dict(n_within_4A=int(nb["within_4.0A"].sum()), n_within_5A=int(nb["within_5.0A"].sum()),
                closest=dict(res=lab[int(nb.min_heavy_atom_distance_A.values.argmin())], d=float(nb.min_heavy_atom_distance_A.min()))))


def fig6():
    o = pd.read_csv(RES / "ligand892_site_occupancy.csv")
    o = o[o.min_distance_to_superposed_ligand_A <= 3.0]
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4.8), gridspec_kw=dict(width_ratios=[1.45, 1]))
    kv = {}
    for ax, pid in zip(axes, ("5K9W", "5K9V")):
        g = o[o.structure == pid].sort_values("min_distance_to_superposed_ligand_A")
        y = np.arange(len(g))[::-1]
        cols = ["#7b3fa0" if not m else COL[pid] for m in g.modelled_in_1T49]
        ax.barh(y, g.min_distance_to_superposed_ligand_A, color=cols, height=0.7)
        for yi, r in zip(y, g.itertuples()):
            ax.text(r.min_distance_to_superposed_ligand_A + 0.05, yi, f"{r.min_distance_to_superposed_ligand_A:.2f}", va="center", fontsize=8)
        ax.set_yticks(y, [f"{r.resname.title()}{r.resnum}" for r in g.itertuples()])
        ax.axvline(2.5, color="#333333", lw=0.7, ls=":")
        ax.set_xlim(0, 3.7)
        ax.set_xlabel("Min. distance to superposed ligand-892 atoms (Å)")
        ax.set_title(f"{LAB[pid]}", loc="left")
        kv[pid] = {f"{r.resname}{r.resnum}": float(r.min_distance_to_superposed_ligand_A) for r in g.itertuples()}
    axes[0].legend(handles=[Patch(color="#7b3fa0", label="residue has no coordinates in 1T49 (283–298)"), Patch(color=COL["5K9W"], label="residue also modelled in 1T49")],
                   frameon=False, fontsize=8.5, loc="upper left", bbox_to_anchor=(0.0, -0.16), ncol=1)
    fig.suptitle("What occupies the ligand-892 position in the other two crystal structures?", x=0.01, ha="left", fontweight="bold")
    fig.tight_layout(rect=(0, 0.03, 1, 0.95))
    fig.subplots_adjust(bottom=0.27)
    finish(fig, "fig6_site_occupancy", "Occupancy of the ligand-892 position in 5K9W and 5K9V",
           "Ligand 892 coordinates were carried into the 5K9W and 5K9V frames with the core Cα fit, and protein heavy atoms closer than 3.0 Å to any "
           "ligand atom are listed (dotted line: 2.5 Å, well inside any non-bonded contact distance). In 5K9W the position is occupied mainly by "
           "α7-segment residues (Trp291, Gln290, Gln288, Val287, Asp284) that have no coordinates in 1T49; in 5K9V, where that segment is also "
           "unmodelled, the overlaps come from α3/α6 side chains (Phe196, Asn193, Glu200, Glu276) that adopt different positions in 1T49. "
           "This is a geometric incompatibility between static models, not a measurement of displacement kinetics or causality.",
           ["results/ligand892_site_occupancy.csv"], kv)


def fig7():
    d = pd.read_csv(RES / "region_distances.csv")
    sel = ["Asp181 CA - Cys215 CA", "Asp181 CG - Cys215 SG", "Phe182 CZ - Cys215 SG", "Tyr152 OH - Asn193 (min heavy atom)",
           "Phe196 side chain - Phe280 side chain (min)", "Trp179 side chain - Phe269 side chain (min)",
           "alpha3 189-201 - alpha7 285-296 (min heavy atom)"]
    short = ["Asp181 Cα –\nCys215 Cα", "Asp181 Cγ –\nCys215 Sγ", "Phe182 Cζ –\nCys215 Sγ", "Tyr152 OH –\nAsn193 (min)", "Phe196 – Phe280\nside chains (min)",
             "Trp179 – Phe269\nside chains (min)", "α3 (189–201) –\nα7 (285–296) (min)"]
    ids = [i for i in ("5K9W", "1SUG", "5K9V", "1T49") if i in set(d.structure)]
    fig, ax = plt.subplots(figsize=(11, 5))
    w = 0.8 / len(ids)
    kv = {}
    for k, pid in enumerate(ids):
        for j, name in enumerate(sel):
            v = d[(d.structure == pid) & (d.distance == name)].value_A
            v = float(v.iloc[0]) if len(v) else np.nan
            x = j + (k - (len(ids) - 1) / 2) * w
            if np.isfinite(v):
                ax.bar(x, v, w * 0.92, color=COL[pid])
                ax.text(x, v + 0.2, f"{v:.1f}", ha="center", va="bottom", fontsize=7.5)
            else:
                ax.text(x, 0.25, "not\nmodelled", ha="center", va="bottom", fontsize=6.5, color=COL[pid], rotation=90)
            kv[f"{pid}|{name}"] = None if not np.isfinite(v) else v
    ax.set_xticks(range(len(sel)), short, fontsize=8.5)
    ax.set_ylabel("Distance (Å)")
    ax.set_ylim(0, 18.5)
    ax.legend(handles=[Patch(color=COL[i], label=LAB[i]) for i in ids], frameon=False, ncol=len(ids), loc="upper right", fontsize=8.5)
    ax.set_title("Declared atom–atom and group distances in each deposited model", loc="left")
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    finish(fig, "fig7_region_distances", "Catalytic-loop and allosteric-region distances per structure",
           "Selected distances measured in each deposited model (no superposition involved). The Asp181–Cys215 separations split the entries into two "
           "groups: 5K9W and the supplementary apo entry 1SUG (about 8.3 Å Cα–Cα) versus 5K9V and 1T49 (12.3–12.9 Å). Two apo crystals therefore sit on "
           "opposite sides, so ligand state alone does not define the loop state. Tyr152–Asn193 and Phe196–Phe280 separate only in 1T49. "
           "'Not modelled' marks distances that cannot be measured because one group has no coordinates. 1SUG was retrieved by the independent "
           "technician and is outside the three-entry core set.",
           ["results/region_distances.csv"], kv, entries="5K9W, 5K9V, 1T49 and supplementary 1SUG")


def fig8():
    d = pd.read_csv(RES / "contact_differences.csv")
    d = d[d.robust_gt_1A & d.involves_loop_window].copy()
    d["label"] = [f"{a.title()}{i} – {b.title()}{j}" for a, i, b, j in zip(d.resname_i, d.res_i, d.resname_j, d.res_j)]
    cols = ["min_dist_5K9W_A", "min_dist_5K9V_A", "min_dist_1T49_A"]
    d = d.sort_values(["contact_5K9W", "res_i", "res_j"], ascending=[False, True, True])
    M = d[cols].values
    fig, ax = plt.subplots(figsize=(7.4, 6.4))
    im = ax.imshow(M, cmap="viridis_r", vmin=2.5, vmax=9, aspect="auto")
    for i in range(M.shape[0]):
        for j in range(M.shape[1]):
            ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=8.5, color="white" if M[i, j] < 5.6 else "black",
                    fontweight="bold" if M[i, j] <= 4.0 else "normal")
    ax.set_xticks(range(3), ["5K9W\n(closed)", "5K9V\n(open)", "1T49\n(ligand 892)"])
    ax.set_yticks(range(len(d)), d.label)
    n_closed = int(d.contact_5K9W.sum())
    ax.axhline(n_closed - 0.5, color="white", lw=2.5)
    for s in ("top", "right", "left", "bottom"):
        ax.spines[s].set_visible(False)
    cb = fig.colorbar(im, ax=ax, fraction=0.05, pad=0.03)
    cb.set_label("Minimum heavy-atom distance (Å)")
    ax.set_title("Loop-window residue contacts that differ between structures\n(bold: ≤ 4.0 Å contact; rows above the white line are contacts in 5K9W)", loc="left", fontsize=10)
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    finish(fig, "fig8_loop_contact_differences", "Loop-window contact differences",
           "Residue pairs involving the 176–187 window whose contact state (minimum heavy-atom distance ≤ 4.0 Å, sequence separation ≥ 3) differs among "
           "the three models and whose distance changes by more than 1 Å. In 5K9W, Asp181 and Phe182 contact Lys120, Arg221, Thr263 and Gln266; in 5K9V "
           "and 1T49 these contacts are absent and Arg112–Trp179/Asp181 and Trp179–Phe269 contacts appear instead. 5K9V and 1T49 show the same pattern.",
           ["results/contact_differences.csv"],
           dict(n_pairs=int(len(d)), n_contacts_in_5K9W=n_closed, pairs={r.label: [float(r.min_dist_5K9W_A), float(r.min_dist_5K9V_A), float(r.min_dist_1T49_A)] for r in d.itertuples()}))


def fig9():
    c = pd.read_csv(RES / "crystal_contacts.csv")
    groups = ["loop window 176-187", "residues 237-243", "ligand-892 site residues (4 A set)", "alpha7 285-297"]
    short = ["Loop window\n176–187", "Residues\n237–243", "Ligand-892 site\nresidues (12)", "α7 segment\n285–297"]
    ids = ["5K9W", "5K9V", "1T49"]
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.6))
    w = 0.26
    kv = {}
    for k, pid in enumerate(ids):
        for j, gname in enumerate(groups):
            r = c[(c.structure == pid) & (c.group == gname)].iloc[0]
            x = j + (k - 1) * w
            if r.status != "measured":
                for ax in (a1, a2):
                    ax.text(x, 0.15, "not modelled", rotation=90, ha="center", va="bottom", fontsize=7, color=COL[pid])
                kv[f"{pid}|{gname}"] = None
                continue
            a1.bar(x, r.n_group_atoms_within_4A_of_mate, w * 0.92, color=COL[pid])
            a1.text(x, r.n_group_atoms_within_4A_of_mate + 0.25, f"{int(r.n_group_atoms_within_4A_of_mate)}", ha="center", fontsize=8.5)
            a2.bar(x, r.min_distance_to_symmetry_mate_A, w * 0.92, color=COL[pid])
            a2.text(x, r.min_distance_to_symmetry_mate_A + 0.12, f"{r.min_distance_to_symmetry_mate_A:.1f}", ha="center", fontsize=8.5)
            kv[f"{pid}|{gname}"] = dict(n_atoms_within_4A=int(r.n_group_atoms_within_4A_of_mate), min_A=float(r.min_distance_to_symmetry_mate_A))
    for ax in (a1, a2):
        ax.set_xticks(range(len(groups)), short, fontsize=8.8)
    a1.set_ylabel("Atoms within 4.0 Å of a symmetry mate")
    a1.set_title("Lattice contacts per region", loc="left")
    a1.set_ylim(0, 13.5)
    a2.axhline(4.0, color="#333333", lw=0.7, ls=":")
    a2.set_ylabel("Closest symmetry-mate atom (Å)")
    a2.set_title("Closest approach", loc="left")
    a2.set_ylim(0, 7.4)
    a1.legend(handles=[Patch(color=COL[i], label=LAB[i]) for i in ids], frameon=False, fontsize=8.5, loc="upper right")
    fig.suptitle("Crystal-lattice environment of the compared regions", x=0.01, ha="left", fontweight="bold")
    fig.tight_layout(rect=(0, 0.03, 1, 0.95))
    finish(fig, "fig9_crystal_contacts", "Crystal-lattice contacts of the compared regions",
           "Symmetry mates were generated from the REMARK 290 operators and unit cell of each legacy PDB file. Left: number of atoms in each region "
           "within 4.0 Å of any symmetry-mate atom; right: closest symmetry-mate atom (dotted line 4.0 Å). The closed loop of 5K9W makes no lattice "
           "contact, whereas the open loops of 5K9V (11 atoms; residues 178–181, 186–187) and 1T49 (Phe182) do, and residues 237–243 contact a mate "
           "in all three crystals. Differences between these entries therefore cannot be attributed to ligand state alone.",
           ["results/crystal_contacts.csv"], kv)


def main():
    for f in (fig1, fig2, fig3, fig4, fig5, fig6, fig7, fig8, fig9):
        f()
    (FIG / "figure_manifest.json").write_text(json.dumps(MANIFEST, indent=1))
    (FIG / "figure_captions.md").write_text("# Figure captions\n\nAll figures are drawn by `analysis/make_figures.py` from the result tables listed under each caption.\n\n" + "\n".join(CAPTIONS))
    print("wrote", sorted(p.name for p in FIG.glob("*.png")))


if __name__ == "__main__":
    main()
