#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fit the sprite engine's row-cost constants on some sprite tests; report the others. The fitted constants are ``suzy.engine.COSTS`` ``row``, ``pen16``, ``out16`` and ``bus16`` (the rest come from the LT guide's measurements). The objective is the sum, over the fitting tests, of how far each Timer 1/3 duration falls outside its hardware window (0 inside), then the distance from the window's middle. A coordinate descent from the current values; the held-out suites are only reported. python -I scripts/m5_fit.py [--fit sprites1] [--hold sprites2,...] [--rounds 3] """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from lynx_python import testrom from lynx_python.machine import MACHINES from lynx_python.suzy import engine KEYS = {"row": 2, "pen16": 1, "out16": 1, "bus16": 1} def durations(suite: str, machine) -> list[tuple[int, int, int]]: outcome = testrom.run(suite, machine) spec = testrom.parse_suite(suite) out = [] for t, (low, high) in enumerate(spec.timings): d = outcome.results[4 * t] | (outcome.results[4 * t + 1] << 8) out.append((d, low, high)) return out def score(suites: list[str], machine) -> tuple[int, int, int]: outside = middle = inside = 0 for suite in suites: for d, low, high in durations(suite, machine): outside += max(0, low - d, d - high) middle += abs(d - (low + high) // 2) inside += low <= d <= high return outside, middle, inside def main(argv: list[str]) -> int: parser = argparse.ArgumentParser() parser.add_argument("--fit", default="sprites1") parser.add_argument("--hold", default="sprites2,sprites3,sprites4,sprites5") parser.add_argument("--rounds", type=int, default=3) parser.add_argument("--row", default="lynx2") args = parser.parse_args(argv) machine = MACHINES[args.row] fit = args.fit.split(",") best = score(fit, machine) print("start", {k: engine.COSTS[k] for k in KEYS}, best, flush=True) for _ in range(args.rounds): improved = False for key, step in KEYS.items(): for direction in (1, -1): while True: engine.COSTS[key] += direction * step trial = score(fit, machine) if trial[:2] < best[:2]: best = trial improved = True print(" ", {k: engine.COSTS[k] for k in KEYS}, best, flush=True) continue engine.COSTS[key] -= direction * step break if not improved: break print("fitted", {k: engine.COSTS[k] for k in KEYS}, "fit", best) for suite in args.hold.split(","): if suite: print("held out", suite, score([suite], machine)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))