{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The measurements behind the figures\n",
    "\n",
    "Every number in the [quantum nonogram solver](/projects/quantum-nonogram-solver/) and\n",
    "[tiny skill linker](/projects/tiny-skill-linker/) writeups comes out of one of the JSON\n",
    "files in this directory, and every figure on those pages is a drawing of one.\n",
    "\n",
    "This notebook recomputes the published claims from those files and then redraws the\n",
    "figures from the same data, so a reader can check a figure rather than take it.\n",
    "\n",
    "It needs only the Python standard library. The last section shells out to Node to redraw\n",
    "the figures, which needs a checkout of the site; everything before it runs anywhere."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import hashlib\n",
    "import json\n",
    "import subprocess\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "HERE = Path.cwd()\n",
    "MANIFEST = json.loads((HERE / \"manifest.json\").read_text())\n",
    "\n",
    "\n",
    "def load(path):\n",
    "    \"\"\"Read a published file and check it against the hash the manifest records.\"\"\"\n",
    "    entry = next(f for f in MANIFEST[\"files\"] if f[\"path\"] == path)\n",
    "    body = (HERE / path).read_bytes()\n",
    "    digest = hashlib.sha256(body).hexdigest()\n",
    "    if digest != entry[\"sha256\"]:\n",
    "        raise ValueError(\n",
    "            f\"{path}: sha256 {digest[:12]}, manifest says {entry['sha256'][:12]}\")\n",
    "    return json.loads(body)\n",
    "\n",
    "\n",
    "FAILURES = []\n",
    "\n",
    "\n",
    "def check(claim, got, want, tolerance=0.0):\n",
    "    \"\"\"Print a published claim beside what this file actually says.\"\"\"\n",
    "    if isinstance(want, (int, float)) and not isinstance(want, bool):\n",
    "        ok = abs(got - want) <= tolerance\n",
    "    else:\n",
    "        ok = got == want\n",
    "    if not ok:\n",
    "        FAILURES.append(claim)\n",
    "    print(f\"{'ok  ' if ok else 'FAIL'}  {claim:<58} {got!r}\")\n",
    "\n",
    "\n",
    "for f in MANIFEST[\"files\"]:\n",
    "    print(f\"{f['path']:<34} {f['bytes']:>8,} bytes\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The nonogram oracles\n",
    "\n",
    "`nonogram/oracle-sweep.json` carries the whole run under `run` and the fields the figures\n",
    "read above it. The first thing to check is that the two agree: every point plotted is the\n",
    "median of the eight transpiler seeds the run recorded."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sweep = load(\"nonogram/oracle-sweep.json\")\n",
    "run = sweep[\"run\"]\n",
    "\n",
    "for row in sweep[\"widths\"]:\n",
    "    shape = f\"2x{row['width']}\"\n",
    "    cost = run[\"cost\"][shape]\n",
    "    for arm in (\"clue\", \"automaton\"):\n",
    "        check(f\"{shape} {arm} two-qubit gates\", row[arm], cost[arm][\"two_qubit\"][\"median\"])\n",
    "    check(f\"{shape} fillings allowed\", row[\"fillings\"], run[\"boards\"][shape][\"fillings\"])\n",
    "\n",
    "print()\n",
    "check(\"transpiler seeds\", run[\"seeds\"], 8)\n",
    "check(\"optimization level\", run[\"optimization_level\"], 3)\n",
    "check(\"device model\", run[\"backend\"], \"fake_torino\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What the writeup says\n",
    "\n",
    "> the clue oracle grows x1.53 per width and the automaton x1.18\n",
    "\n",
    "> the automaton is **still 1.8x the oracle it was meant to replace at width 14**\n",
    "\n",
    "> the clue oracle is exponential in line width \u2014 R^2 0.989 against 0.970 for a polynomial\n",
    "> \u2014 and the automaton is polynomial at W^1.82, R^2 0.995 against 0.933\n",
    "\n",
    "The growth rates are fitted over the last six widths and the models over all of them. Both\n",
    "fits are least squares on the logarithm, which is what makes the two comparable: an\n",
    "exponential is a straight line against width, a polynomial a straight line against its\n",
    "logarithm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import math\n",
    "\n",
    "\n",
    "def least_squares(xs, ys):\n",
    "    \"\"\"Slope, intercept and R^2 for a straight line through the points.\"\"\"\n",
    "    n = len(xs)\n",
    "    mx, my = sum(xs) / n, sum(ys) / n\n",
    "    sxx = sum((x - mx) ** 2 for x in xs)\n",
    "    slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys, strict=True)) / sxx\n",
    "    intercept = my - slope * mx\n",
    "    residual = sum((y - (intercept + slope * x)) ** 2 for x, y in zip(xs, ys, strict=True))\n",
    "    total = sum((y - my) ** 2 for y in ys)\n",
    "    return slope, intercept, 1 - residual / total\n",
    "\n",
    "\n",
    "rows = sweep[\"widths\"]\n",
    "lo, hi = sweep[\"growth_per_width\"][\"fitted_over_widths\"]\n",
    "window = [r for r in rows if lo <= r[\"width\"] <= hi]\n",
    "\n",
    "for arm in (\"clue\", \"automaton\"):\n",
    "    slope, _, _ = least_squares([r[\"width\"] for r in window], [math.log(r[arm]) for r in window])\n",
    "    check(f\"{arm}: growth per width\", round(math.exp(slope), 3),\n",
    "          sweep[\"growth_per_width\"][arm])\n",
    "\n",
    "print()\n",
    "widths = [r[\"width\"] for r in rows]\n",
    "for arm in (\"clue\", \"automaton\"):\n",
    "    ys = [math.log(r[arm]) for r in rows]\n",
    "    _, _, r2_exponential = least_squares(widths, ys)\n",
    "    _, _, r2_polynomial = least_squares([math.log(w) for w in widths], ys)\n",
    "    recorded = sweep[\"fits\"][arm]\n",
    "    check(f\"{arm}: R^2 of an exponential\", round(r2_exponential, 4),\n",
    "          recorded[\"exponential\"][\"r2\"])\n",
    "    check(f\"{arm}: R^2 of a polynomial\", round(r2_polynomial, 4),\n",
    "          recorded[\"polynomial\"][\"r2\"])\n",
    "    better = \"exponential\" if r2_exponential > r2_polynomial else \"polynomial\"\n",
    "    print(f\"      {arm} is better described as {better}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "last = rows[-1]\n",
    "check(\"width 14: automaton over clue\", round(last[\"automaton\"] / last[\"clue\"], 1),\n",
    "      run[\"ratios\"][\"2x14\"][\"automaton_over_clue\"])\n",
    "\n",
    "print()\n",
    "print(\"projected past the widest board that fits:\")\n",
    "for step in sweep[\"projected_ratio\"]:\n",
    "    print(f\"  width {step['width']}: {step['ratio']}x\")\n",
    "a, b = sweep[\"projected_ratio\"][1], sweep[\"projected_ratio\"][2]\n",
    "crossing = a[\"width\"] + math.log(a[\"ratio\"]) / math.log(a[\"ratio\"] / b[\"ratio\"])\n",
    "check(\"projection reaches equal cost at width\", round(crossing, 2),\n",
    "      sweep[\"projected_parity_width\"], 0.01)\n",
    "print(f\"      so between widths {a['width']} and {b['width']}\")\n",
    "check(\"memory the machine has, GB\", sweep[\"memory_wall\"][\"machine_gb\"], 549)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The oracle was checked on every grid, not a sample\n",
    "\n",
    "> across 19 shapes every one of **392,619,856 grids** was evaluated, with no phase\n",
    "> mismatch and no workspace qubit left entangled"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "correctness = run[\"correctness\"]\n",
    "check(\"shapes checked\", len(correctness), sweep[\"verification\"][\"shapes\"])\n",
    "check(\"grids evaluated\", sum(c[\"grids_checked\"] for c in correctness.values()),\n",
    "      sweep[\"verification\"][\"grids_checked\"])\n",
    "check(\"phase mismatches\", sum(c[\"phase_mismatches\"] for c in correctness.values()), 0)\n",
    "check(\"workspace qubits left entangled\", sum(c[\"workspace_leaks\"] for c in correctness.values()), 0)\n",
    "check(\"grids at the widest board\", correctness[\"2x14\"][\"grids_checked\"], 2 ** 28)\n",
    "\n",
    "print()\n",
    "print(\"the bit-level evaluation against a full statevector:\")\n",
    "for shape, result in run[\"cross_check\"].items():\n",
    "    print(f\"  {shape}: agree={result['agree']}, \"\n",
    "          f\"largest workspace amplitude {result['statevector']['max_workspace_leak']:.1e}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Enumerating the puzzles\n",
    "\n",
    "> Every solvable board up to 4x4 was enumerated and deduplicated by clue pair \u2014\n",
    "> **62,535 puzzles**\n",
    "\n",
    "The same run enumerated 5x5 exhaustively as well, which is where the puzzle counts under\n",
    "the `queries.svg` axis come from."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "boards = run[\"boards\"]\n",
    "up_to_4x4 = [\"2x2\", \"2x3\", \"2x4\", \"3x3\", \"3x4\", \"4x4\"]\n",
    "check(\"distinct clue pairs up to 4x4\",\n",
    "      sum(boards[s][\"distinct_clue_pairs\"] for s in up_to_4x4), 62535)\n",
    "\n",
    "print()\n",
    "print(f\"{'shape':>6}  {'clue pairs':>12}  {'one solution':>13}\")\n",
    "for shape in [*up_to_4x4, \"4x5\", \"5x5\"]:\n",
    "    b = boards[shape]\n",
    "    print(f\"{shape:>6}  {b['distinct_clue_pairs']:>12,}  {b['single_solution_boards']:>13,}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What the solver asks, against what Grover needs\n",
    "\n",
    "> a backtracking solver's *worst* board asks fewer questions than Grover needs rounds:\n",
    "> 15 against 17 at 3x3, 56 against 201 at 4x4, and 246 against 4,549\n",
    "\n",
    "`placements` is an upper bound on whole-grid queries and a Grover round is exact, which is\n",
    "why `queries.svg` plots them as two different marks rather than one ratio."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "spread = load(\"nonogram/query-spread.json\")\n",
    "shapes = {s[\"shape\"]: s for s in spread[\"shapes\"]}\n",
    "\n",
    "for shape, worst, rounds in [(\"3x3\", 15, 17), (\"4x4\", 56, 201), (\"5x5\", 246, 4549)]:\n",
    "    s = shapes[shape]\n",
    "    check(f\"{shape}: the backtracker's worst board\", s[\"placementsM1\"][\"max\"], worst)\n",
    "    check(f\"{shape}: rounds Grover needs\", s[\"groverRoundsM1\"], rounds)\n",
    "    check(f\"{shape}: boards the backtracker wins, %\", s[\"winPctM1\"], 100.0)\n",
    "\n",
    "print()\n",
    "five = shapes[\"5x5\"]\n",
    "print(f\"5x5 is the one sample: {five['sampled']['grids']:,} grids drawn at seed \"\n",
    "      f\"{five['sampled']['seed']}, giving {five['puzzles']:,} distinct puzzles, \"\n",
    "      f\"{five['puzzlesM1']:,} of them with one solution.\")\n",
    "print(\"Every other shape is every solvable board of that shape.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What the circuit costs\n",
    "\n",
    "> at 3x3 not one of the 17 required rounds survives a 200-layer coherence budget\n",
    "\n",
    "> **5.97x the gates, 7.91x the depth** between the two compiler decisions"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "costs = load(\"nonogram/hardware-cost.json\")\n",
    "split = load(\"nonogram/compile-split.json\")[\"split\"]\n",
    "three = next(r for r in costs[\"rows\"] if (r[\"rows\"], r[\"cols\"], r[\"solutions\"]) == (3, 3, 1))\n",
    "\n",
    "check(\"3x3: rounds Grover needs\", three[\"iterations\"], 17)\n",
    "check(\"3x3: depth with spare qubits lent\", three[\"depth\"], 6246)\n",
    "check(\"3x3: depth with nothing to borrow\", three[\"depth_noaux\"], 49468)\n",
    "print(f\"      one round is {three['depth'] / 200:.0f}x a 200-layer budget at best\")\n",
    "\n",
    "print()\n",
    "check(\"gates, nothing to borrow\",\n",
    "      split[\"synthesis_no_ancilla_all_to_all\"] + split[\"routing_net\"], 19357)\n",
    "check(\"gates, two spare qubits lent\",\n",
    "      split[\"synthesis_anc2_all_to_all\"] + split[\"shipped_routing_net\"], 3240)\n",
    "check(\"the ratio between them\", round(19357 / 3240, 2),\n",
    "      split[\"shipped_vs_reference_two_qubit_factor\"], 0.01)\n",
    "print(f\"      routing added {split['routing_net']:,} of the dearer total and \"\n",
    "      f\"{split['shipped_routing_net']:,} of the cheaper one\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Every summary row is one whole seed\n",
    "\n",
    "`hardware-cost.json` is a summary: one row a shape, picked from the twenty-four transpiler\n",
    "seeds in `hardware-runs.json`. The rule it states is that the shallowest run is reported\n",
    "whole, so depth, gate count and two-qubit count all come from the same circuit. Taking\n",
    "each metric's own best across seeds would read better and describe no circuit that was\n",
    "ever compiled, so it is worth checking that the published rows did not do that."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "runs = load(\"nonogram/hardware-runs.json\")\n",
    "arms = [\n",
    "    (\"marker\", (\"depth\", \"gates\", \"two_qubit\")),\n",
    "    (\"marker_noaux\", (\"depth_noaux\", \"gates_noaux\", \"two_qubit_noaux\")),\n",
    "    (\"clue\", (\"depth_clue\", \"gates_clue\", \"two_qubit_clue\")),\n",
    "]\n",
    "\n",
    "whole, cherry_picked = 0, 0\n",
    "for entry in runs[\"rows\"]:\n",
    "    key = (entry[\"rows\"], entry[\"cols\"], entry[\"solutions\"])\n",
    "    row = next((r for r in costs[\"rows\"]\n",
    "                if (r[\"rows\"], r[\"cols\"], r[\"solutions\"]) == key), None)\n",
    "    if row is None:\n",
    "        continue\n",
    "    for arm, fields in arms:\n",
    "        measured = entry[arm]\n",
    "        if not measured:\n",
    "            continue\n",
    "        flat = [e for board in measured for e in board] if isinstance(\n",
    "            measured[0][0], list) else measured\n",
    "        shallowest = min(flat, key=lambda e: e[0])\n",
    "        if [row[f] for f in fields] == shallowest:\n",
    "            whole += 1\n",
    "        else:\n",
    "            cherry_picked += 1\n",
    "            print(f\"  {key} {arm}: {[row[f] for f in fields]} is not any one seed\")\n",
    "\n",
    "check(\"summary rows that are one whole seed\", cherry_picked, 0)\n",
    "print(f\"      {whole} arms checked across {runs['seeds']} seeds each\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What a round costs to compile\n",
    "\n",
    "> one many-controlled X over c controls costs exactly 6(c - 1) with a qubit to borrow\n",
    "\n",
    "> Before routing it costs exactly 12n - 25 at every size measured\n",
    "\n",
    "Both are closed forms, so they are worth checking at every size rather than quoting from\n",
    "the two ends."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "per_round = load(\"nonogram/per-round.json\")\n",
    "\n",
    "off = [p for p in per_round[\"mcx\"] if p[\"twoSpare\"] != 6 * (p[\"controls\"] - 1)]\n",
    "check(\"control counts where 6(c - 1) does not hold\", len(off), 0)\n",
    "off = [p for p in per_round[\"perRound\"] if p[\"allToAll\"] != 12 * p[\"qubits\"] - 25]\n",
    "check(\"register sizes where 12n - 25 does not hold\", len(off), 0)\n",
    "\n",
    "print()\n",
    "widest = per_round[\"perRound\"][-1]\n",
    "check(\"routing multiplies a round at 16 qubits by\", widest[\"routingFactor\"], 2.69)\n",
    "check(\"refusing the spare qubits multiplies it by\",\n",
    "      round(widest[\"deviceNoSpare\"] / widest[\"device\"], 1), 15.5)\n",
    "check(\"the penalty at 25 controls\", per_round[\"mcx\"][-1][\"ratio\"], 20.8)\n",
    "print(f\"      and at 3 controls it is only {per_round['mcx'][0]['ratio']}x\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The unit decides the verdict\n",
    "\n",
    "`unit-choice.svg` prices the same 3x3 circuit against exhaustive search three ways. The\n",
    "circuit wins in one unit, draws in another and loses in the third, which is the reason the\n",
    "writeup reports placements and rounds separately instead of dividing one by the other."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "work = 2 ** 9 * shapes[\"3x3\"][\"predicateGatesMedianM1\"]\n",
    "print(f\"exhaustive search: 2^9 grids x {shapes['3x3']['predicateGatesMedianM1']} \"\n",
    "      f\"gate-steps a check = {work:,} gate-steps\\n\")\n",
    "\n",
    "held = 9 + three[\"ancillas\"]\n",
    "for label, value in [\n",
    "    (\"two-qubit gates\", three[\"two_qubit\"]),\n",
    "    (\"all gates\", three[\"gates\"]),\n",
    "    (\"qubit-layers\", held * three[\"depth\"]),\n",
    "]:\n",
    "    print(f\"  {label:<16} {value / work:>6.2f}x\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The skill linker\n",
    "\n",
    "> a fifth the parameters ... **RP@5 within 1 point** of the published 110M model on two of\n",
    "> three evaluation sets\n",
    "\n",
    "The three figures on that page are drawn from `skill-linker/benchmarks.json`. The\n",
    "fine-tuned and int8 arms are means over three training seeds; the stock and published\n",
    "arms are single models, so they carry no spread."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bench = load(\"skill-linker/benchmarks.json\")\n",
    "rp5 = bench[\"rp5\"]\n",
    "\n",
    "print(f\"{'set':<10} {'stock':>7} {'fine-tuned':>18} {'int8':>18} {'published':>10}\")\n",
    "for name, n in bench[\"sets\"].items():\n",
    "    ft, i8 = rp5[\"fine_tuned\"][name], rp5[\"int8\"][name]\n",
    "    print(f\"{name:<10} {rp5['stock'][name]:>7.2f} {ft['mean']:>11.2f} +- {ft['sd']:<4.2f}\"\n",
    "          f\" {i8['mean']:>11.2f} +- {i8['sd']:<4.2f} {rp5['published'][name]:>10.2f}\"\n",
    "          f\"   (n={n})\")\n",
    "\n",
    "print()\n",
    "for name in bench[\"sets\"]:\n",
    "    behind = rp5[\"published\"][name] - rp5[\"fine_tuned\"][name][\"mean\"]\n",
    "    print(f\"  {name:<10} {behind:+.2f} points against the 110M model\")\n",
    "check(\"parameters, fine-tuned, millions\", bench[\"params_millions\"][\"fine_tuned\"], 22)\n",
    "check(\"parameters, published, millions\", bench[\"params_millions\"][\"published\"], 110)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Skills the model never trained on\n",
    "\n",
    "> fine-tuning lifts skills it never saw by **8.2 points**\n",
    "\n",
    "The held-out arm removed 2,765 skills from training, so the pairs scored as `unseen` are\n",
    "ones no training example mentioned."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "unseen = bench[\"unseen\"]\n",
    "# The arm that answers the question is the one those 2,765 skills were kept out of:\n",
    "# the model trained on all of them had seen the skill the pair asks about.\n",
    "for label, key in [(\"unseen\", \"unseen\"), (\"seen\", \"seen\")]:\n",
    "    gain = unseen[\"held_out\"][key] - unseen[\"stock\"][key]\n",
    "    check(f\"gain on {label} skills, points\", round(gain, 2),\n",
    "          unseen[f\"gain_{label}\"][\"points\"], 0.02)\n",
    "print()\n",
    "check(\"skills held out of training\", unseen[\"held_out_skills\"], 2765)\n",
    "check(\"pairs scored as unseen\", unseen[\"n_unseen\"], 282)\n",
    "check(\"pairs scored as seen\", unseen[\"n_seen\"], 1414)\n",
    "\n",
    "print()\n",
    "lo, hi = unseen[\"gain_unseen\"][\"ci\"]\n",
    "print(f\"  the interval on that gain is {lo} to {hi} points, on {unseen['n_unseen']} pairs\")\n",
    "print(f\"  trained on those skills instead, they score \"\n",
    "      f\"{unseen['trained_on_all']['unseen']['mean']}, so most of the lift survives \"\n",
    "      f\"holding them out\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Claims these files do not carry\n",
    "\n",
    "Two numbers in the nonogram writeup cannot be reproduced from this directory.\n",
    "\n",
    "The **227.5 two-qubit gates** that a solution-marking oracle compiles to across thirty\n",
    "distinct 4x4 boards was measured in the solver's own repository, and only its conclusion\n",
    "was carried over. The sweep here records the same oracle at 4x4 under a different\n",
    "convention \u2014 the whole Grover circuit rather than the oracle alone \u2014 so the two are not\n",
    "comparable, as the cell below shows.\n",
    "\n",
    "The **run on `ibm_fez`** that resolved the correct state in 377 of 1,024 shots is a record\n",
    "held by IBM against job `db4m98imb58s7389da60`. Nothing in this directory is a run on a\n",
    "quantum device: every cost above is a fit to the `fake_torino` device model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "marking = run[\"cost\"][\"4x4\"][\"marking\"]\n",
    "print(\"4x4, solution-marking oracle, whole circuit, median of 8 seeds:\")\n",
    "print(f\"  two-qubit gates {marking['two_qubit']['median']:,} \"\n",
    "      f\"(min {marking['two_qubit']['min']:,}, max {marking['two_qubit']['max']:,})\")\n",
    "print(f\"  qubits {marking['qubits']}\")\n",
    "print(\"\\nThe 227.5 figure is the oracle gate alone and is not in this directory.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Redrawing the figures\n",
    "\n",
    "The figures are drawn by the site's own scripts, so this runs those rather than a second\n",
    "implementation: a drawing that could disagree with the published one would be worse than\n",
    "no drawing at all.\n",
    "\n",
    "This needs a checkout of the site and Node 22 or newer. Everything above does not."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "root = HERE.parents[1]\n",
    "scripts = [\"figures.mjs\", \"figures-nonogram-oracles.mjs\", \"figures-skill-linker.mjs\"]\n",
    "\n",
    "if not (root / \"scripts\" / scripts[0]).exists():\n",
    "    print(f\"No checkout at {root}; skipping. The published figures are under /figures/.\")\n",
    "else:\n",
    "    for name in scripts:\n",
    "        done = subprocess.run([ \"node\", f\"scripts/{name}\"], cwd=root,\n",
    "                              capture_output=True, text=True, check=False)\n",
    "        print(done.stdout.strip() or done.stderr.strip())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "try:\n",
    "    from IPython.display import SVG\n",
    "    from IPython.display import display as show\n",
    "except ImportError:\n",
    "    show = None\n",
    "\n",
    "figures = sorted({f for entry in MANIFEST[\"files\"] for f in entry[\"figures\"]})\n",
    "for name in figures:\n",
    "    path = HERE.parents[0] / \"figures\" / name\n",
    "    print(name)\n",
    "    if show and path.exists():\n",
    "        show(SVG(filename=str(path)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Result"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "if FAILURES:\n",
    "    print(f\"{len(FAILURES)} claims do not match the data:\")\n",
    "    for claim in FAILURES:\n",
    "        print(f\"  {claim}\")\n",
    "    sys.exit(1)\n",
    "print(\"Every published claim matches the data in this directory.\")"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
