diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2552905..75deb68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,12 +80,16 @@ jobs: python tools/check_bundle.py python tools/check_bundle.py --self-test - - name: Committed figures are exactly what the code produces + - name: Committed figures match what the code produces # Every figure is regenerated from the committed results and compared - # byte-for-byte with the committed PNG. This exists because a release - # candidate once shipped figures from an earlier commit, including one - # whose title had already been found to be wrong. Byte equality holds - # only under constraints.txt, which is why that file is mandatory. + # with the committed PNG. This exists because a release candidate once + # shipped figures from an earlier commit, including one whose title had + # already been found to be wrong. Byte equality turned out not to be + # stable even here (commit 4071c1e failed on Nov 29 and passed on + # Nov 30, same image and pins), so tools/check_figures.py fails on any + # content change (a swapped digit moves ~200 pixels) and passes + # antialiasing noise (25 pixels or fewer). constraints.txt is still + # mandatory so that real differences stay rare. run: | (cd hc-sweep && python tools/make_figures.py \ && python tools/make_voltvar_figures.py \ @@ -96,8 +100,9 @@ jobs: && python tools/make_epri_figures.py) (cd carbon-signal-atlas && PYTHONPATH=src python tools/make_figures.py) (cd tariff-explorer && PYTHONPATH=src python tools/make_figures.py) - git diff --exit-code --stat -- '*/figures/*.png' \ - || (echo "Figures in the repo do not match the code. Regenerate and commit."; exit 1) + git diff --stat -- '*/figures/*.png' + python tools/check_figures.py --self-test + python tools/check_figures.py - name: Upload the regenerated figures if they differ # When the check above fails, the fix is to commit the figures this diff --git a/carbon-signal-atlas/README.md b/carbon-signal-atlas/README.md index 267aa83..e4edf9b 100644 --- a/carbon-signal-atlas/README.md +++ b/carbon-signal-atlas/README.md @@ -110,6 +110,6 @@ tools/ run_robustness.py, make_figures.py, check_claims.py results/ robustness_table.csv, robustness_per_region.csv docs/ METHODS.md: full method narrative tests/ test suite; counts in ../MANIFEST.md -figures/ every figure is regenerated by tools/, checked byte-for-byte in CI +figures/ every figure is regenerated by tools/, checked against the code in CI data/ 13 region files from CarbonCast (Apache-2.0) ``` diff --git a/hc-sweep/README.md b/hc-sweep/README.md index 1b3648b..9ff8d64 100644 --- a/hc-sweep/README.md +++ b/hc-sweep/README.md @@ -224,6 +224,6 @@ docs/ METHODS.md: full method narrative PREREGISTRATION-DEVIATION.md: the same for the voltage-deviation criteria PREREGISTRATION-EPRI.md: the same for EPRI's test circuits, with one amendment tests/ test suite; counts in ../MANIFEST.md -figures/ every figure is regenerated by tools/, checked byte-for-byte in CI +figures/ every figure is regenerated by tools/, checked against the code in CI data/ epri_manifest.sha256 pins the fetched circuits; the circuits themselves are not committed ``` diff --git a/tariff-explorer/README.md b/tariff-explorer/README.md index bb3eb34..e956320 100644 --- a/tariff-explorer/README.md +++ b/tariff-explorer/README.md @@ -112,5 +112,5 @@ src/tarifflab/ tools/ make_fixtures.py, make_figures.py, check_claims.py docs/ METHODS.md: full method narrative tests/ test suite; counts in ../MANIFEST.md -figures/ every figure is regenerated by tools/, checked byte-for-byte in CI +figures/ every figure is regenerated by tools/, checked against the code in CI ``` diff --git a/tools/check_figures.py b/tools/check_figures.py new file mode 100644 index 0000000..05299f3 --- /dev/null +++ b/tools/check_figures.py @@ -0,0 +1,105 @@ +"""Fail when a regenerated figure differs from the committed one in content. + +The figure step used to require byte equality. On Nov 29 commit 4071c1e failed +it (tariff-explorer 01_regime_bill_curves.png, 141094 -> 141097 bytes) and on +Nov 30 the same commit passed it, with identical runner image, Python and +library versions. Byte equality is therefore not stable even in CI, and a red +badge from it says nothing about whether a figure is stale. + +This check keeps the purpose (catch a figure that was not regenerated after a +code or results change, such as a corrected title) and drops the flake: a +figure fails if its size changes or if more of its pixels +move by more than PIXEL_TOLERANCE on any channel than MAX_PIXELS. One changed digit +in an annotation moves well over a hundred pixels; antialiasing noise moves a few. + +Usage, after the make_figures scripts have run: + python tools/check_figures.py # compare working tree to HEAD + python tools/check_figures.py --self-test +""" +from __future__ import annotations + +import io +import subprocess +import sys +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +ROOT = Path(__file__).resolve().parents[1] +PIXEL_TOLERANCE = 16 # out of 255, per channel +MAX_PIXELS = 25 # a single changed digit in a 10 pt label moves far more + + +def _git(*args: str) -> bytes: + return subprocess.run(["git", *args], cwd=ROOT, check=True, capture_output=True).stdout + + +def changed_figures() -> list[str]: + out = _git("diff", "--name-only", "--", "*/figures/*.png").decode().split() + untracked = _git("ls-files", "--others", "--exclude-standard", "--", "*/figures/*.png") + return sorted(set(out) | set(untracked.decode().split())) + + +def compare(old: Image.Image, new: Image.Image) -> tuple[bool, str]: + if old.size != new.size: + return False, f"size {old.size} -> {new.size}" + a = np.asarray(old.convert("RGBA"), dtype=np.int16) + b = np.asarray(new.convert("RGBA"), dtype=np.int16) + moved = (np.abs(a - b).max(axis=2) > PIXEL_TOLERANCE) + frac = float(moved.mean()) + return int(moved.sum()) <= MAX_PIXELS, f"{int(moved.sum())} pixels moved ({frac:.4%})" + + +def check() -> int: + failures = [] + for rel in changed_figures(): + new = Image.open(ROOT / rel) + try: + old = Image.open(io.BytesIO(_git("show", f"HEAD:{rel}"))) + except subprocess.CalledProcessError: + failures.append(f"{rel}: not committed") + continue + ok, detail = compare(old, new) + print(f"{'ok ' if ok else 'FAIL'} {rel}: bytes differ, {detail}") + if not ok: + failures.append(rel) + if failures: + print("\nFigures in the repo do not match the code. Regenerate and commit:") + for f in failures: + print(f" {f}") + return 1 + print("figures match the code (byte-identical or within rendering noise)") + return 0 + + +def self_test() -> int: + title = ImageFont.load_default(size=28) # about a 13.5 pt title at 150 dpi + label = ImageFont.load_default(size=20) # about a 10 pt annotation + + def draw(title_text: str, label_text: str) -> Image.Image: + img = Image.new("RGB", (1400, 800), "white") + d = ImageDraw.Draw(img) + d.text((100, 50), title_text, fill="black", font=title) + d.text((600, 400), label_text, fill="black", font=label) + return img + + base = draw("Original title", "$1,234/yr spread") + noisy = base.copy() + noisy.putpixel((10, 10), (240, 240, 240)) + cases = [ + ("identical", base, True), + ("one faint pixel", noisy, True), + ("changed title", draw("Corrected title text", "$1,234/yr spread"), False), + ("one digit swapped in a label", draw("Original title", "$1,243/yr spread"), False), + ("changed size", base.resize((1401, 800)), False), + ] + for name, img, want in cases: + print(f" {name}: {compare(base, img)[1]}") + bad = [name for name, img, want in cases if compare(base, img)[0] != want] + print("figure check self-test:", "passed" if not bad else f"FAILED on {bad}") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(self_test() if "--self-test" in sys.argv else check())