"""Compose the per-round field renders for rounds 5, 6, and 7.
Usage: python3 compose_r567.py <5|6|7>

Same 1080x1350 dark ink layout as compose_round.py. Every number is
read from the render meta JSONs and the round data files, never typed
by hand, except the lab-data figures quoted in the footer lines for
rounds 5 and 6, which come from the verified round reports. The
round 7 footer is built from the round 7 data files at compose time.
"""

import json
import sys

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

OUT = "/home/hatch/workspace/millennium-lab/poster"
DATA = "/home/hatch/workspace/millennium-lab/data"
ROUND = sys.argv[1]

INK = "#111418"
PAPER = "#f4efe6"
BRASS = "#a9803e"
MUTED = "#8a8a80"

meta = json.load(open("%s/render_meta_r%s.json" % (OUT, ROUND)))
km = meta["kida_pelz"]

if ROUND == "7":
    ns7 = json.load(open("%s/navier_stokes_hunt_r7.json" % DATA))
    ym7 = json.load(open("%s/yang_mills_r7.json" % DATA))
    kp96 = [c for c in ns7["cases"]
            if c["name"].startswith("kida-pelz-type-96")][0]
    tg96 = [c for c in ns7["cases"]
            if c["name"].startswith("taylor-green-96")][0]
    tg20 = [c for c in ns7["cases"] if c["name"].endswith("-T20")][0]
    c25 = ym7["three_seed_comparison"]["2.5"]
    c26 = ym7["three_seed_comparison"]["2.6"]
    ext_verdict = ym7["continuum_extrapolation_torelon"]["verdict"]
    ext_short = ("OVERTURNED STANDS" if ext_verdict.startswith("OVERTURNED")
                 else "REVISED")
    takeaway7 = ("At 96 cubed the Kida-Pelz growth is %.2f, Taylor-Green "
                 "%.2f; Taylor-Green to t = 20 %s."
                 % (kp96["enstrophy_growth_factor"],
                    tg96["enstrophy_growth_factor"],
                    "peaked and decayed"
                    if tg20["enstrophy_final"] < tg20["enstrophy_peak"]
                    else "was still rising"))
    footer7 = ("Yang-Mills: third seed torelon %.3f at beta 2.5 and %.3f "
               "at beta 2.6. The extrapolation verdict: %s."
               % (c25["seed3"]["torelon"]["value"],
                  c26["seed3"]["torelon"]["value"], ext_short))
    CONFIG = {
        "header": "MILLENNIUM LAB  |  ROUND 7",
        "headline": "Ninety-six cubed",
        "subtitle": "Kida-Pelz vorticity, 96 cubed, viscosity 0.000125, "
                    "at peak enstrophy.",
        "takeaway": takeaway7,
        "weave_caption": "The plaquette weave at beta 2.6. The third "
                         "seed tests whether the torelon moves are "
                         "statistics or estimator.",
        "footer1": footer7,
    }
elif ROUND == "5":
    CONFIG = {
        "header": "MILLENNIUM LAB  |  ROUND 5",
        "headline": "A quarter of the viscosity",
        "subtitle": "Kida-Pelz vorticity, 64 cubed, viscosity 0.00025, "
                    "at peak enstrophy.",
        "takeaway": "At a quarter the viscosity the growth rose again "
                    "to 64.46, then decayed. Transient, not runaway.",
        "weave_caption": "Below: the plaquette weave at beta 2.6. "
                         "Torelon 1.608, the fifth beta point.",
        "footer1": "P vs NP: wider fragment, greedy extends to 5 of "
                   "6 ops, 0 violations. Hodge: sheaf LES proved, "
                   "18 results, 0 sorries.",
    }
else:
    CONFIG = {
        "header": "MILLENNIUM LAB  |  ROUND 6",
        "headline": "Lower still",
        "subtitle": "Kida-Pelz vorticity, 64 cubed, viscosity 0.000125, "
                    "at peak enstrophy.",
        "takeaway": "At nu 0.000125 the growth rose again to 88.24, then "
                    "decayed by t = 20. Transient, not runaway.",
        "weave_caption": "Below: the plaquette weave at beta 2.5. The "
                         "second seed put the torelon at 0.890 there.",
        "footer1": "Yang-Mills: second seed overturns the torelon "
                   "points, 0.890 and 1.193. The five-point "
                   "extrapolation cannot support a claim.",
    }

cfg = CONFIG
vort = np.load("%s/kida_peak_vortmag_r%s.npy" % (OUT, ROUND))
u = np.load("%s/kida_peak_u_r%s.npy" % (OUT, ROUND))
v = np.load("%s/kida_peak_v_r%s.npy" % (OUT, ROUND))

fig = plt.figure(figsize=(10.8, 13.5), dpi=100)
fig.patch.set_facecolor(INK)
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)

fig.text(0.06, 0.945, cfg["header"], fontsize=13, color=BRASS,
         weight="bold", family="monospace", ha="left", va="center")
fig.text(0.06, 0.905, cfg["headline"], fontsize=30, color=PAPER,
         weight="bold", ha="left", va="center")
fig.text(0.06, 0.868, cfg["subtitle"], fontsize=13.5, color=MUTED,
         ha="left", va="center")

ax = fig.add_axes([0.06, 0.315, 0.88, 0.53])
ax.set_facecolor(INK)
ax.imshow(np.flipud(vort.T), cmap="magma", origin="lower",
          extent=[0, 2 * np.pi, 0, 2 * np.pi], aspect="auto")
n = vort.shape[0]
x = np.linspace(0, 2 * np.pi, n)
y = np.linspace(0, 2 * np.pi, n)
ax.streamplot(x, y, u.T, v.T, density=1.4, color="white", linewidth=0.45,
              arrowsize=0.5)
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(0, 2 * np.pi)
ax.set_xticks([])
ax.set_yticks([])
for s in ax.spines.values():
    s.set_color("#33383f")
ax.text(0.02, 0.97, "VORTICITY MAGNITUDE | z = pi PLANE | t = %.1f"
        % km["peak_time"], transform=ax.transAxes, fontsize=11,
        color="white", family="monospace", ha="left", va="top")
ax.text(0.02, 0.03, "STREAMLINES: IN-PLANE VELOCITY",
        transform=ax.transAxes, fontsize=11, color="white",
        family="monospace", ha="left", va="bottom")

fig.text(0.06, 0.292,
         "ENSTROPHY GROWTH %.2f x  |  PEAK t = %.1f  |  MAX |omega| %.2f"
         % (km["enstrophy_growth"], km["peak_time"],
            km["max_vorticity_peak_slice"]),
         fontsize=15, color=PAPER, weight="bold", family="monospace",
         ha="left", va="center")
fig.text(0.06, 0.270, cfg["takeaway"], fontsize=12.5, color=MUTED,
         ha="left", va="center")
fig.text(0.06, 0.256, cfg["weave_caption"], fontsize=11.5, color=MUTED,
         ha="left", va="center")


def weave(ax, values, vmin, vmax, label):
    n = values.shape[0]
    xs, ys, cs, sizes = [], [], [], []
    for i in range(n):
        for j in range(n):
            xs.append(i)
            ys.append(j)
            cs.append(values[i, j])
            sizes.append(5200)
    ax.scatter(xs, ys, c=cs, s=sizes, cmap="RdBu_r", marker="D",
               norm=Normalize(vmin=vmin, vmax=vmax),
               edgecolors="#111418", linewidths=0.7)
    ax.set_xlim(-0.6, n - 0.4)
    ax.set_ylim(-0.6, n - 0.4)
    ax.set_aspect("equal")
    ax.set_xticks([])
    ax.set_yticks([])
    for s in ax.spines.values():
        s.set_color("#33383f")
    ax.text(0.03, 0.97, label, transform=ax.transAxes, fontsize=11,
            color="white", family="monospace", ha="left", va="top")


plain = np.load("%s/ym_plaquette_plain_r%s.npy" % (OUT, ROUND))
smeared = np.load("%s/ym_plaquette_smeared_r%s.npy" % (OUT, ROUND))
ax1 = fig.add_axes([0.06, 0.045, 0.40, 0.195])
weave(ax1, plain, -0.5, 1.0, "PLAQUETTE, UNSMEARED")
ax2 = fig.add_axes([0.54, 0.045, 0.40, 0.195])
weave(ax2, smeared, 0.70, 1.0, "PLAQUETTE, APE SMEARED, 4 STEPS")

fig.text(0.06, 0.030, cfg["footer1"], fontsize=11, color=MUTED,
         ha="left", va="center")
fig.text(0.06, 0.011,
         "All fields computed from the lab's own solvers. A research "
         "render, not a solution. Others did the work.",
         fontsize=11, color=MUTED, ha="left", va="center")

fig.savefig("%s/millennium-field-render-r%s.png" % (OUT, ROUND), dpi=100,
            facecolor=INK)
print("saved millennium-field-render-r%s.png" % ROUND)
