"""Compose one per-round field render. Usage: python3 compose_round.py <1|2|3|4>

Same 1080x1350 dark ink layout as the rounds 3/4 render. Every number is
read from the render meta JSONs, never typed by hand, except the lab-data
figures quoted in the footer lines, which come from the verified round
reports (torelon values, greedy timings, theorem counts).
"""
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"
ROUND = sys.argv[1]

meta_r1 = json.load(open("%s/render_meta.json" % OUT))
meta_r34 = json.load(open("%s/render_meta_r34.json" % OUT))
meta_r2r3 = None
if ROUND in ("2", "3"):
    meta_r2r3 = json.load(open("%s/render_meta_r2r3.json" % OUT))
INK = "#111418"
PAPER = "#f4efe6"
BRASS = "#a9803e"
MUTED = "#8a8a80"

CONFIG = {
    "1": {
        "header": "MILLENNIUM LAB  |  ROUND 1",
        "headline": "The first field",
        "subtitle": "Kida-Pelz vorticity, 48 cubed, viscosity 0.001, at "
                    "peak enstrophy.",
        "vort": "kida_peak_vortmag.npy",
        "u": "kida_peak_u.npy",
        "v": "kida_peak_v.npy",
        "ns_meta": meta_r1["kida_pelz"],
        "takeaway": "First Kida-Pelz run. Stayed smooth, no blowup "
                    "signal.",
        "weaves": [("ym_plaquette_r1.npy", -0.5, 1.0,
                    "PLAQUETTE, BETA 2.2")],
        "weave_caption": "Below: the plaquette weave at beta 2.2. The "
                         "torelon is nonzero here and at beta 2.4.",
        "footer1": "P vs NP: the defeater-free fragment is polynomial, "
                   "greedy in 0.07 seconds. Yang-Mills: torelon nonzero "
                   "at beta 2.2 and 2.4.",
    },
    "2": {
        "header": "MILLENNIUM LAB  |  ROUND 2",
        "headline": "Resolution climbs",
        "subtitle": "Kida-Pelz vorticity, 64 cubed, viscosity 0.001, at "
                    "peak enstrophy.",
        "vort": "kida_peak_vortmag_r2.npy",
        "u": "kida_peak_u_r2.npy",
        "v": "kida_peak_v_r2.npy",
        "ns_meta": ("r2r3", "r2_ns"),
        "takeaway": "Growth saturating with resolution: 14.23, 18.29, "
                    "18.86.",
        "weaves": [("ym_plaquette_slice.npy", -0.5, 1.0,
                    "PLAQUETTE, BETA 2.3")],
        "weave_caption": "Below: the plaquette weave at beta 2.3. "
                         "Torelon 1.86, the third beta point.",
        "footer1": "P vs NP: greedy 0.57 seconds against exhaustive "
                   "567,586. Hodge: the group-level sequence "
                   "formalized, 9 theorems.",
    },
    "3": {
        "header": "MILLENNIUM LAB  |  ROUND 3",
        "headline": "Out to t = 20",
        "subtitle": "Kida-Pelz vorticity, 64 cubed, viscosity 0.001, "
                    "evolved to t = 20, at peak enstrophy.",
        "vort": "kida_peak_vortmag_r3.npy",
        "u": "kida_peak_u_r3.npy",
        "v": "kida_peak_v_r3.npy",
        "ns_meta": ("r2r3", "r3_ns"),
        "takeaway": "Out to t = 20 the peak retraced round 2 exactly, "
                    "then decayed.",
        "weaves": [("ym_plaquette_r3.npy", -0.5, 1.0,
                    "PLAQUETTE, BETA 2.5")],
        "weave_caption": "Below: the plaquette weave at beta 2.5. "
                         "Torelon 1.280, the fourth beta point.",
        "footer1": "P vs NP: the full fragment with defeaters is "
                   "polynomial, 8,876 checks, 0 violations. Hodge: O_X "
                   "formalized, 13 theorems.",
    },
    "4": {
        "header": "MILLENNIUM LAB  |  ROUND 4",
        "headline": "The field at half viscosity",
        "subtitle": "Kida-Pelz vorticity, 64 cubed, viscosity 0.0005, "
                    "at peak enstrophy.",
        "vort": "kida_peak_vortmag_r34.npy",
        "u": "kida_peak_u_r34.npy",
        "v": "kida_peak_v_r34.npy",
        "ns_meta": meta_r34["kida_pelz"],
        "takeaway": "At half the viscosity the growth more than doubled, "
                    "then decayed. Transient, not runaway.",
        "weaves": [("ym_plaquette_plain_r34.npy", -0.5, 1.0,
                    "PLAQUETTE, UNSMEARED"),
                   ("ym_plaquette_smeared_r34.npy", 0.70, 1.0,
                    "PLAQUETTE, APE SMEARED, 4 STEPS")],
        "weave_caption": "The plaquette weave before and after APE "
                         "smearing. Smoothing cleaned up the 0++ gap: "
                         "1.653 at beta 2.3.",
        "footer1": "P vs NP: the defeater fragment is polynomial, 1400 "
                   "of 1400 trials. Hodge: degree-zero Dolbeault "
                   "formalized, 14 theorems, 0 sorries.",
    },
}

cfg = CONFIG[ROUND]
km = cfg["ns_meta"]
if isinstance(km, tuple):
    km = meta_r2r3[km[1]]
vort = np.load("%s/%s" % (OUT, cfg["vort"]))
u = np.load("%s/%s" % (OUT, cfg["u"]))
v = np.load("%s/%s" % (OUT, cfg["v"]))

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")


weaves = cfg["weaves"]
if len(weaves) == 1:
    name, vmin, vmax, label = weaves[0]
    vals = np.load("%s/%s" % (OUT, name))
    ax1 = fig.add_axes([0.28, 0.045, 0.40, 0.195])
    weave(ax1, vals, vmin, vmax, label)
else:
    name, vmin, vmax, label = weaves[0]
    vals = np.load("%s/%s" % (OUT, name))
    ax1 = fig.add_axes([0.06, 0.045, 0.40, 0.195])
    weave(ax1, vals, vmin, vmax, label)
    name, vmin, vmax, label = weaves[1]
    vals = np.load("%s/%s" % (OUT, name))
    ax2 = fig.add_axes([0.54, 0.045, 0.40, 0.195])
    weave(ax2, vals, vmin, vmax, label)

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)
