"""Why the front bends where it does: saving against κ, from fig4_data.json.

The same encoding as the study's figures.py (fig_kappa): both axes log, one mark
per fitted model, the earlier sweep's bands for the weights and the factor. Kind
and origin are told apart by shape and fill: dense circle, sparse square, earlier
sweep hollow. Colour tells the five test functions apart (series 1 to 5).

derive() adds, for every drawn model, its cheapest passing point from the study's
fronts.json (bytes, the format of each stored part, the best single format), so
the interactive reading can say what each model stores, part by part. Nothing in
it is computed beyond a lookup by stem.
"""
import json
import math

from figlib import FONT, LogScale, Svg, decade, legend, sci, variant

FUNCTIONS = ["forrester", "branin", "ishigami", "hartmann6", "borehole"]
NAME = {"forrester": "Forrester", "branin": "Branin", "ishigami": "Ishigami", "hartmann6": "Hartmann 6",
        "borehole": "Borehole"}


def points(data):
    return data["fig4_data.json"]["points"]


def problem(stem):
    return stem.split("_n")[0]


def derive(files):
    pts = json.loads(files["fig4_data.json"])["points"]
    fronts = {r["stem"]: r for r in json.loads(files["fronts.json"])}
    models = {}
    for p in pts:
        r = fronts[p["stem"]]
        lp = r["allocation_last_pass"]
        models[p["stem"]] = {"bytes_f64": r["bytes_f64"], "bytes": lp["bytes"], "assignment": lp["assignment"],
                             "saving_vs_f64": r["saving_vs_f64"], "saving_vs_uniform": r["saving_vs_uniform"],
                             "uniform_best_pass": r["uniform_best_pass"]}
    return {"source": "results/allocation/fronts.json: allocation_last_pass, uniform_best_pass and the savings, "
                      "for each model drawn", "models": models}


def series(stem):
    p = problem(stem)
    return FUNCTIONS.index(p) + 1 if p in FUNCTIONS else None


def mark(svg, p, x, y, i=None, small=False):
    """A data point carries class fig-pt and data-i (its row in fig4_data.json); a legend mark does not.
    Filled marks are see-through (fig-see-through), so models that coincide show as a darker
    overlap instead of hiding one another; no mark is moved off its value."""
    extra = f' data-i="{i}"' if i is not None else ""
    pt = "fig-pt " if i is not None else ""
    k = 0.85 if small else 1.0
    s = series(p["stem"]) if p.get("stem") else p.get("series")
    if not p["bench"]:
        cls, sw = "fig-mark-ink fig-hollow", "1.6"
    else:
        cls, sw = (f"fig-series-{s}" if s else "fig-mark-ink") + " fig-see-through", "1"
    if p["kind"] == "sparse":
        svg.square(x, y, 8.4 * k, pt + cls, extra + f' stroke-width="{sw}"')
    else:
        svg.circle(x, y, 4.4 * k, pt + cls, extra + f' stroke-width="{sw}"')


def draw(data, width):
    pts = points(data)
    thr = data["fig4_data.json"]["f1_thresholds_first_sweep"]
    narrow = width < 470
    plot_h = {"s": 230, "m": 280, "l": 330}[variant(width)]
    left, right, top = 46, 10, 26
    svg = Svg(width)
    xs = [p["kappa"] for p in pts] + [v for t in thr.values() for v in (t["largest_pass"], t["smallest_fail"])]
    x0 = 10 ** (math.floor(math.log10(min(xs))) - 0.3)
    x1 = 10 ** (math.ceil(math.log10(max(xs))) + 0.3)
    ys = [p["saving_vs_f64"] for p in pts]
    y0, y1 = min(0.9, min(ys) * 0.9), max(5, max(ys) * 1.3)
    X = LogScale(x0, x1, left, width - right)
    Y = LogScale(y0, y1, top + plot_h, top)
    bottom = top + plot_h

    for q, name, side in (("alpha", "weights", "end"), ("L", "factor", "start")):
        if q in thr:
            a, b = X(thr[q]["largest_pass"]), X(thr[q]["smallest_fail"])
            svg.rect(a, top, max(b - a, 1.5), plot_h, f"fig-band fig-band-{q}")
            svg.text(a - 5 if side == "end" else b + 5, top - 9, name, side, extra=f' data-band="{q}"')
    e = math.ceil(math.log10(x0))
    while 10 ** e <= x1:
        if (e - 1) % 3 == 0:
            gx = X(10 ** e)
            svg.line(gx, top, gx, bottom, "fig-grid")
            svg.text(gx, bottom + 17, decade(e), "middle")
        e += 1
    for v in (1, 2, 4, 8):
        if y0 <= v <= y1:
            svg.line(left, Y(v), width - right, Y(v), "fig-grid")
            svg.text(left - 7, Y(v) + 4.5, f"{v}×", "end")
    svg.line(left, bottom, width - right, bottom, "fig-axis")
    svg.line(left, top, left, bottom, "fig-axis")
    xt = "κ of the training covariance" if narrow else "κ, the conditioning of the training covariance (worst output)"
    svg.text((left + width - right) / 2, bottom + 36, xt, "middle")
    svg.add(f'<text x="0" y="0" text-anchor="middle" font-size="{FONT}" transform="translate(13 {top + plot_h / 2}) '
            f'rotate(-90)">times smaller than at 64 bits</text>')
    svg.add('<g class="fig-pts">')
    # Larger groups first, so a group with few marks (Forrester has one) is never covered.
    count = {}
    for p in pts:
        key = series(p["stem"]) if p["bench"] else "earlier"
        count[key] = count.get(key, 0) + 1
    for i, p in sorted(enumerate(pts), key=lambda ip: (-count[series(ip[1]["stem"]) if ip[1]["bench"] else "earlier"],
                                                       ip[1]["kind"] == "sparse", ip[0])):
        mark(svg, p, X(p["kappa"]), Y(p["saving_vs_f64"]), i, small=narrow)
    svg.add("</g>")
    # Two legends: the functions (colour) and the kinds (shape and fill). An interactive page shows
    # the function legend as its filter buttons instead, so that one is a group of its own.
    svg.add('<g class="fig-legend-series">')
    y = legend(svg, [((lambda k: lambda s, x, yy: mark(s, {"kind": "dense", "bench": True, "series": k}, x, yy))(k + 1),
                      NAME[f]) for k, f in enumerate(FUNCTIONS)], left - 6, bottom + 62, width - left)
    svg.add("</g>")
    end = legend(svg, [
        (lambda s, x, yy: mark(s, {"kind": "dense", "bench": True, "series": None}, x, yy), "dense"),
        (lambda s, x, yy: mark(s, {"kind": "sparse", "bench": True, "series": None}, x, yy), "sparse"),
        (lambda s, x, yy: mark(s, {"kind": "dense", "bench": False}, x, yy), "earlier sweep"),
    ], left - 6, y + 20, width - left)
    return svg.svg(end + 6, variant(width))


def describe(data):
    """Rounded as the article states them: savings to two significant figures (three below 1.5),
    κ bounds outward to two or three."""
    pts = [p for p in points(data) if p["bench"]]
    big = [p for p in pts if p["saving_vs_f64"] >= 1.5]
    small = [p for p in pts if p["saving_vs_f64"] < 1.5]

    def outward(v, n, up):
        e = math.floor(math.log10(v)) - n + 1
        k = 10 ** e
        r = (math.ceil(v / k - 1e-9) if up else math.floor(v / k + 1e-9)) * k
        e2 = math.floor(math.log10(r) + 1e-12)
        return f"{r / 10 ** e2:.{n - 1}f} × {decade(e2)}"
    return (f"A scatter plot of {len(pts)} models of the five test functions, and two from an earlier sweep. "
            f"The models fall into two groups with a wide gap between them: with κ up to "
            f"{outward(max(p['kappa'] for p in big), 2, True)} they are stored {min(p['saving_vs_f64'] for p in big):.2g} to "
            f"{max(p['saving_vs_f64'] for p in big):.2g} times smaller; with κ from "
            f"{outward(min(p['kappa'] for p in small), 3, False)}, at most {max(p['saving_vs_f64'] for p in small):.3g} "
            f"times smaller.")
