#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Decode the port-race probe's save (probes/port_race): the grid, and the window it implies. python -I scripts/port_race_results.py SAVE/port-race.srm python -I scripts/port_race_results.py console.srm --compare board.srm [--compare mesen.srm] The save holds 286 cells: an S-SMP variant (the $F5 read D S-SMP cycles after the CONTROL clear, D = 3..12, and "Z", Zenki's own four-port sequence) against an S-CPU loop rewriting $2141 every M master clocks (26 loops, FastROM and SlowROM), T trials each, counting the reads that were not zero. The grid printed is hits (reads of zero) as a percentage of T. The window. If a trial's phase against the S-CPU's writes is uniform (the probe randomises it), a trial reads zero when no write lands in the W master clocks from the clear taking effect to the read sampling. The S-CPU writes every M clocks, except that the line's 40-clock DRAM refresh (DOC anomie's timing document) stretches one gap a line to M + 40, so hits / T = [(1324 / M - 1) max(0, M - W) + max(0, M + 40 - W)] / 1364 For every variant the W with the greatest binomial likelihood over its 26 cells is printed, with W - D x 20.974 (an S-SMP cycle is 20.974 master clocks at the nominal 24.576 MHz): the part of the window the cycle count does not explain, which is what the board must get right. The fit is a model (HYPOTHESIS: uniform phase, writes as instants, one refresh a line); the cells are the measurement. """ from __future__ import annotations import argparse import math from dataclasses import dataclass from pathlib import Path MAGIC = b"SNESPRB6" FORMAT = 1 CELLS = 0x40 CELL = 12 LINE = 1364 # master clocks a line (DOC: anomie, fullsnes) REFRESH = 40 # DRAM refresh a line (DOC: anomie's timing document) SMP_CLOCK = 236_250_000 / 11 / 1_024_000 # master clocks per S-SMP cycle, nominal STATUS = {0: "not run", 1: "started", 2: "done", 3: "interrupted"} ZENKI_LOOP = 12 ZENKI_VAR = 10 @dataclass(frozen=True) class Cell: loop: int fast: bool var: int d: int trials: int m: int misses: int status: int @property def hits(self) -> int: return self.trials - self.misses @property def label(self) -> str: return "Z" if self.var == ZENKI_VAR else f"D{self.d}" @dataclass(frozen=True) class Save: boots: int runs: int interrupted: int no_answer: int state: int next: int cells: list[Cell] def read(path: Path) -> Save: return parse(path.read_bytes(), str(path)) def parse(data: bytes, name: str = "save") -> Save: if data[:8] != MAGIC: raise SystemExit(f"{name}: not a port-race save (starts {data[:8]!r})") if data[8] != FORMAT: raise SystemExit(f"{name}: format {data[8]}, this script reads {FORMAT}") word = lambda o: int.from_bytes(data[o : o + 2], "little") # noqa: E731 cells = [] for i in range(word(0x0E)): o = CELLS + CELL * i cells.append(Cell(loop=data[o], fast=bool(data[o + 1]), var=data[o + 2], d=data[o + 3], trials=data[o + 4] * 256, m=word(o + 5), misses=word(o + 7), status=data[o + 9])) # fmt: skip return Save(boots=word(0x0A), runs=word(0x0C), interrupted=word(0x12), no_answer=data[0x14], state=data[9], next=word(0x10), cells=cells) # fmt: skip def predicted(w: float, m: int) -> float: """The fraction of trials that read zero for a window of ``w`` master clocks.""" writes = (LINE - REFRESH) / m return ((writes - 1) * max(0.0, m - w) + max(0.0, m + REFRESH - w)) / LINE def fit(cells: list[Cell]) -> tuple[float, float, float] | None: """(best W, lower, upper): the likelihood's peak and where it falls by 2 (about 2 sigma).""" done = [c for c in cells if c.status == 2] if not done: return None grid = [i / 4 for i in range(0, 4 * 400)] scores = [] for w in grid: ll = 0.0 for c in done: p = min(max(predicted(w, c.m), 1e-7), 1 - 1e-7) ll += c.hits * math.log(p) + c.misses * math.log(1 - p) scores.append(ll) best = max(range(len(grid)), key=scores.__getitem__) inside = [grid[i] for i, s in enumerate(scores) if s >= scores[best] - 2] return grid[best], min(inside), max(inside) def columns(save: Save) -> list[tuple[int, bool, int]]: keys = {(c.m, c.fast, c.loop) for c in save.cells} return sorted(keys, key=lambda k: (k[0], not k[1], k[2])) def variants(save: Save) -> list[tuple[int, str, int]]: return sorted({(c.var, c.label, c.d) for c in save.cells}) def grid(save: Save, name: str) -> None: print(f"{name}: run {save.runs}, boots {save.boots}, state {save.state} " f"({'complete' if save.state == 2 else 'unfinished'}), {save.next} of " f"{len(save.cells)} cells, {save.interrupted} cut by reset, " f"S-SMP silent {save.no_answer}x") # fmt: skip vs = variants(save) by = {(c.m, c.fast, c.loop, c.var): c for c in save.cells} print("hits (reads of zero) per 100 trials; rows: S-CPU loop (M master clocks a write, " "f FastROM / s SlowROM), columns: S-SMP variant") print(f"{'M':>4} {'':2} {'loop':>4} {'T':>5} " + "".join(f"{lab:>6}" for _, lab, _ in vs)) for m, fast, loop in columns(save): row = [] trials = 0 for var, _, _ in vs: c = by.get((m, fast, loop, var)) if c is None or c.status != 2: row.append(f"{'-' if c is None else STATUS[c.status][:3]:>6}") continue trials = c.trials pct = 100 * c.hits / c.trials row.append(f"{pct:6.1f}" if c.hits else f"{'0':>6}") mark = " <- Zenki's loop" if loop == ZENKI_LOOP else "" print(f"{m:4} {'f' if fast else 's':2} {loop:4} {trials:5} " + "".join(row) + mark) print("window W per variant (binomial fit over the 26 loops; +-: likelihood within 2):") print(f"{'var':>4} {'D':>3} {'W':>7} {'range':>15} {'W/cycle':>8} {'W - D x 20.974':>15}") for var, lab, d in vs: f = fit([c for c in save.cells if c.var == var]) if f is None: print(f"{lab:>4} {d:3} (no cells done)") continue w, lo, hi = f print(f"{lab:>4} {d:3} {w:7.2f} {f'{lo:.2f}-{hi:.2f}':>15} {w / SMP_CLOCK:8.3f} " f"{w - d * SMP_CLOCK:+15.2f}") # fmt: skip for c in save.cells: if c.loop == ZENKI_LOOP and c.var in (5, ZENKI_VAR) and c.status == 2: print(f"Zenki's loop ({'FastROM' if c.fast else 'SlowROM'}, M = {c.m}) against " f"{'Zenki' + chr(39) + 's S-SMP sequence' if c.var == ZENKI_VAR else 'D = 8'}: " f"{c.hits} of {c.trials} reads were zero") # fmt: skip def compare(saves: list[tuple[str, Save]]) -> None: base_name, base = saves[0] keyed = [{(c.loop, c.fast, c.var): c for c in s.cells} for _, s in saves] print("side by side, hits per 100 trials, cells where any differs by more than 3 sigma:") print(" loop speed var M " + "".join(f"{n:>12}" for n, _ in saves)) shown = 0 for c in base.cells: key = (c.loop, c.fast, c.var) others = [k.get(key) for k in keyed] if any(o is None or o.status != 2 for o in others): continue ps = [o.hits / o.trials for o in others] sig = [math.sqrt(max(p * (1 - p), 1 / o.trials) / o.trials) for p, o in zip(ps, others)] if max(abs(p - ps[0]) / math.hypot(s, sig[0]) for p, s in zip(ps, sig)) > 3: shown += 1 print(f" {c.loop:4} {'fast' if c.fast else 'slow':5} {c.label:>3} {c.m:5} " + "".join(f"{100 * p:12.1f}" for p in ps)) print(f" {shown} cells differ (of {len(base.cells)}), {base_name} first") def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("srm", type=Path) parser.add_argument("--compare", type=Path, action="append", default=[]) args = parser.parse_args() saves = [(p.name, read(p)) for p in [args.srm, *args.compare]] for name, save in saves: grid(save, name) print() if len(saves) > 1: compare(saves) if __name__ == "__main__": main()