Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion carbon-signal-atlas/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```
2 changes: 1 addition & 1 deletion hc-sweep/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
2 changes: 1 addition & 1 deletion tariff-explorer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
105 changes: 105 additions & 0 deletions tools/check_figures.py
Original file line number Diff line number Diff line change
@@ -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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include staged figure changes in the comparison

When a contributor stages regenerated PNGs before running this documented checker, git diff compares the worktree to the index, while git ls-files --others omits staged files. changed_figures() can therefore be empty and the check falsely succeeds without inspecting the staged image. CI currently runs from a clean checkout, but the local check should include staged changes when comparing against HEAD.

Useful? React with 👍 / 👎.

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())
Loading