#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Every licensed dump whose scheme is implemented, frame-compared with Stella. Milestone 4's sweep (docs/handoff-brief.md). The dumps are read in place from the No-Intro sets under ``$NO_INTRO_DIR`` (as ``count_bankswitch.py`` found them: the zip set first, a 7z set for any dump the first lacks), one per SHA-1; licensed means no Proto/Beta/Demo/Sample/Program, Unl/Pirate or Aftermarket/Homebrew tag (scripts/count_bankswitch.py's classification). A dump whose scheme the board does not build yet is listed as skipped, and so is one the board would identify by size alone as a scheme other than the one Stella's census gives (``count_bankswitch.py --json tests/detector_runs/coverage.json``): MAME's list lacks four such dumps (FE, E7, 3F and E0 cartridges the size rule calls F8). Each of the others goes through ``scripts/picture_compare.py --detector stella --keep-going`` for ``--frames`` frames, ``--jobs`` at a time under ``nice``, and one row per dump lands in ``tests/detector_runs/sweep/results.tsv`` (ignored: it names commercial games' frames, nothing more, but stays with the detector output): name, sha1, scheme, frames compared, frames agreed, first divergent frame, pixels and lines differing there, the first pixel's line and clock. ``--explain`` then reruns each divergent dump with the board made to act on writes as Stella does where the die has shown Stella wrong (colour writes two half clocks late, C25; GRP three, C30; VBLANK two, C31; ENAM and ENABL three, C33; REFP three, C37), and writes ``explain.tsv``: whether that run agrees on every frame, and the TIA writes near the first pixel still differing. ``--summary`` prints the table of divergent dumps from both files. ``--smoke`` runs only the dumps named in ``tests/smoke_dumps.txt`` (the residue, the dumps milestone 4's fixes turned clean, classics, carts that stress the TIA, and every scheme and PAL), about an eighth of the corpus, and keeps its rows in ``results-smoke.tsv`` and ``explain-smoke.tsv`` so the full sweep's tables stay whole; every option above takes it. The full sweep is for when a milestone is thought done. nice python3 scripts/sweep_stella.py --frames 300 --jobs 8 nice python3 scripts/sweep_stella.py --smoke --frames 150 --jobs 12 && \ nice python3 scripts/sweep_stella.py --smoke --explain --frames 150 --jobs 12 """ from __future__ import annotations import argparse import hashlib import json import re import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from count_bankswitch import classify, sets # noqa: E402 from a2600_python import gates # noqa: E402 from a2600_python.cartridge import UnsupportedCartridge, identify, read_image # noqa: E402 OUT = ROOT / "tests" / "detector_runs" / "sweep" PYTHON = ROOT / ".venv-pypy" / "bin" / "python" FIRST = re.compile( r"^frame (\d+): (\d+) pixels differ on (\d+) lines; first at board line (-?\d+) clock (\d+)" ) SUMMARY = re.compile(r": (\d+) of (\d+) frames agree") COLUMNS = ( "name", "sha1", "scheme", "compared", "agreed", "first_bad", "pixels", "lines", "line", "clock", ) EXPLAIN_COLUMNS = ("name", "sha1", "compared", "agreed", "first_bad", "pixels", "writes") STELLA_DEPARTURES = [ "COLUP0,COLUP1,COLUPF,COLUBK:2", "GRP0,GRP1:3", "VBLANK:2", "ENAM0,ENAM1,ENABL:3", "REFP0,REFP1:3", ] # C25, C30, C31, C33, C37 WRITES = re.compile(r"writes near: (.*)$") def stella_schemes() -> dict[str, str]: """SHA-1 -> Stella's scheme, from scripts/count_bankswitch.py's census (``--json tests/detector_runs/coverage.json``), when it has been run.""" census = ROOT / "tests" / "detector_runs" / "coverage.json" if not census.exists(): return {} return { r["sha1"]: r["stella"] for r in json.loads(census.read_text())["dumps"] if r.get("stella") } def dumps() -> list[tuple[str, Path, str, str]]: """(name, path, sha1, scheme or 'skip: why') for each licensed dump, once.""" seen, found = set(), [] for folder in sets(): for path in sorted(folder.glob("*.zip")) + sorted(folder.glob("*.7z")): name = path.stem if classify(name) != "licensed": continue try: image, _ = read_image(path) except ValueError: continue # an archive with no ROM in it (the Kid Vid tapes) sha1 = hashlib.sha1(image).hexdigest() if sha1 in seen: continue seen.add(sha1) try: family, super_chip, _, _ = identify(image) scheme = family + ("SC" if super_chip else "") except UnsupportedCartridge as error: scheme = f"skip: {error}" theirs = stella_schemes().get(sha1) if theirs and not scheme.startswith("skip") and theirs != scheme: # MAME's list lacks the dump and the size rule guessed: the # board would run the wrong scheme (milestone 5 adds detectors). scheme = f"skip: the board says {scheme}, Stella says {theirs}" found.append((name, path, sha1, scheme)) return found def compare(path: Path, frames: int, extra: list[str] = ()) -> dict[str, str]: command = [ "nice", str(PYTHON), str(ROOT / "scripts" / "picture_compare.py"), str(path), "--detector", "stella", "--frames", str(frames), "--keep-going", "--runs", str(OUT), *extra, ] # fmt: skip result = subprocess.run(command, capture_output=True, text=True) row = {"compared": "", "agreed": "", "first_bad": "", "pixels": "", "lines": "", "line": "", "clock": "", "writes": ""} # fmt: skip for line in result.stdout.splitlines(): m = FIRST.match(line) if m and not row["first_bad"]: row.update(zip(("first_bad", "pixels", "lines", "line", "clock"), m.groups())) w = WRITES.search(line) row["writes"] = w.group(1) if w else "" m = SUMMARY.search(line) if m: row["agreed"], row["compared"] = m.groups() if not row["compared"]: row["first_bad"] = "error: " + (result.stderr.strip().splitlines() or ["?"])[-1][:120] return row def smoke_names() -> set[str]: """The dump names in tests/smoke_dumps.txt (read by ``gates.smoke_names``).""" return set(gates.smoke_names(ROOT)) def summary(path: Path, explained_path: Path) -> None: rows = [dict(zip(COLUMNS, line.split("\t"))) for line in path.read_text().splitlines()[1:]] explained = {} if explained_path.exists(): for line in explained_path.read_text().splitlines()[1:]: row = dict(zip(EXPLAIN_COLUMNS, line.split("\t"))) explained[row["sha1"]] = row run = [r for r in rows if not r["scheme"].startswith("skip")] clean = [r for r in run if r["compared"] and r["agreed"] == r["compared"]] divergent = [r for r in run if r not in clean] known = [ r for r in divergent if (e := explained.get(r["sha1"])) and e["compared"] and e["agreed"] == e["compared"] ] rest = [r for r in divergent if r not in known] frames = sum(int(r["compared"] or 0) for r in run) print( f"{len(rows)} licensed dumps: {len(run)} run ({frames:,} frames compared), {len(rows) - len(run)} skipped; " f"{len(clean)} agree on every frame, {len(known)} more once Stella's die-settled departures " f"(C25 colour, C30 GRP, C31 VBLANK, C33 enables, C37 REFP) are applied, {len(rest)} left" ) print( "\n| Dump | Scheme | Frames agreed | With C25/C30/C31/C33/C37 | First divergent frame | Pixels (lines) | Writes near |" ) print("| --- | --- | ---: | ---: | ---: | ---: | --- |") for r in sorted(rest, key=lambda r: r["name"]): e = explained.get(r["sha1"], {}) print( f"| {r['name']} | {r['scheme']} | {r['agreed']}/{r['compared']} | " f"{e.get('agreed', '')}/{e.get('compared', '')} | {e.get('first_bad') or r['first_bad']} | " f"{e.get('pixels') or r['pixels']} ({r['lines']}) | {e.get('writes', '')} |" ) print("\nSkipped:") for r in sorted(rows, key=lambda r: r["name"]): if r["scheme"].startswith("skip"): print(f"- {r['name']}: {r['scheme'][6:]}") def explain(frames: int, jobs: int, results: Path, out: Path) -> None: """The second pass: each divergent dump again, with Stella's die-settled departures.""" rows = [dict(zip(COLUMNS, line.split("\t"))) for line in results.read_text().splitlines()[1:]] paths = {sha1: path for _, path, sha1, _ in dumps()} todo = [ r for r in rows if not r["scheme"].startswith("skip") and r["compared"] and r["agreed"] != r["compared"] ] extra = [a for spec in STELLA_DEPARTURES for a in ("--delay-writes", spec)] + ["--reuse"] done = {} if out.exists(): for line in out.read_text().splitlines()[1:]: row = dict(zip(EXPLAIN_COLUMNS, line.split("\t"))) done[row["sha1"]] = row pending = [r for r in todo if r["sha1"] not in done] print(f"{len(todo)} divergent dumps, {len(pending)} to explain", flush=True) def one(r): row = {"name": r["name"], "sha1": r["sha1"]} row.update(compare(paths[r["sha1"]], frames, extra)) return row with ThreadPoolExecutor(jobs) as pool: for count, row in enumerate(pool.map(one, pending), 1): done[row["sha1"]] = row with out.open("w") as f: f.write("\t".join(EXPLAIN_COLUMNS) + "\n") for r in sorted(done.values(), key=lambda r: r["name"]): f.write("\t".join(r.get(c, "") for c in EXPLAIN_COLUMNS) + "\n") print( f"[{count}/{len(pending)}] {row['name']}: {row.get('agreed')}/{row.get('compared')} " f"{row.get('writes', '')}", flush=True, ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--frames", type=int, default=300) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--only", help="regular expression on the dump name") parser.add_argument( "--summary", action="store_true", help="print the divergence table and stop" ) parser.add_argument( "--explain", action="store_true", help="rerun divergent dumps with Stella's departures" ) parser.add_argument( "--smoke", action="store_true", help="only the dumps in tests/smoke_dumps.txt, in their own tables", ) args = parser.parse_args() suffix = "-smoke" if args.smoke else "" results, explained = OUT / f"results{suffix}.tsv", OUT / f"explain{suffix}.tsv" if args.summary: summary(results, explained) return 0 if args.explain: explain(args.frames, args.jobs, results, explained) summary(results, explained) return 0 OUT.mkdir(parents=True, exist_ok=True) todo = dumps() if args.smoke: names = smoke_names() missing = names - {d[0] for d in todo} if missing: print(f"not licensed dumps here: {', '.join(sorted(missing))}", file=sys.stderr) return 2 todo = [d for d in todo if d[0] in names] if args.only: todo = [d for d in todo if re.search(args.only, d[0])] done = {} if results.exists(): for line in results.read_text().splitlines()[1:]: row = dict(zip(COLUMNS, line.split("\t"))) done[row["sha1"]] = row started = time.time() def one(item): name, path, sha1, scheme = item row = {"name": name, "sha1": sha1, "scheme": scheme} row.update(compare(path, args.frames) if not scheme.startswith("skip") else {}) return row pending = [d for d in todo if d[2] not in done] print(f"{len(todo)} licensed dumps, {len(pending)} to run", flush=True) if not results.exists(): results.write_text("\t".join(COLUMNS) + "\n") with ThreadPoolExecutor(args.jobs) as pool: for count, row in enumerate(pool.map(one, pending), 1): done[row["sha1"]] = row with results.open("w") as out: out.write("\t".join(COLUMNS) + "\n") for r in sorted(done.values(), key=lambda r: r["name"]): out.write("\t".join(r.get(c, "") for c in COLUMNS) + "\n") print( f"[{count}/{len(pending)} {time.time() - started:.0f} s] {row['name']}: " f"{row.get('agreed', '-')}/{row.get('compared', '-')} {row.get('first_bad', '')}", flush=True, ) summary(results, explained) return 0 if __name__ == "__main__": sys.exit(main())