"""Does the Lloyd palette fitter lower the colour floor, shot by shot? The colour floor (``base`` in encode.log: the error with every cell at its best line, shade and pens, before any tile is shared) is scored per shot for the fitter as built (``encode.fit_region``: median cut, snapped, refitted twice) and for ``palette.refine`` started from it. Two sets of frames per shot: the ones the fit sees (the same sample ``codebook.fit_shot_lines`` takes) and held-out frames between them, because a palette that only fits its own sample is not a better palette. Reported per shot and as mean, median, worst change and share of shots improved, weighted by shot length for the song-level figure - a mean alone hides a technique that loses on a quarter of shots. python tools/palette_study.py fields out/full-roi/summary.json --saturation 1.3 """ from __future__ import annotations import argparse import json import sys import time from concurrent.futures import ProcessPoolExecutor from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.encode import assign_cells, fit_region, load_picture # noqa: E402 from rrmd.palette import assign, refine # noqa: E402 from rrmd.stream import SHOT_SAMPLE_FRAMES # noqa: E402 from rrmd.vdp import HEIGHT, TILE # noqa: E402 def shot_frames(start: int, end: int) -> tuple[list[int], list[int]]: """The frames the encoder fits on, and held-out frames midway between them.""" n = end - start step = max(1, n // SHOT_SAMPLE_FRAMES) fitted = list(range(start, end, step))[:SHOT_SAMPLE_FRAMES] held = sorted({min(end - 1, f + step // 2) for f in fitted if step > 1} - set(fitted)) return fitted, held def study_shot(args: tuple) -> dict: fields, start, end, saturation, bands, pen0 = args from rrmd.roi import saturate fitted, held = shot_frames(start, end) def load(i: int) -> np.ndarray: f = load_picture(fields / f"f{i + 1:05d}.png") return saturate(f, saturation) if saturation != 1.0 else f sample = np.concatenate([load(i) for i in fitted], axis=0) px_sample = sample.shape[0] * sample.shape[1] t = time.time() old, *_ = fit_region(sample) t_old = time.time() - t t = time.time() new, history = refine(sample, old) t_new = time.time() - t out = {"start": start, "end": end, "fitted": fitted, "held": held, "t_old": t_old, "t_new": t_new, "rounds": len(history) - 1, "sample_old": history[0] / px_sample, "sample_new": history[-1] / px_sample} # fmt: skip # the reference assignment (float64, the encoder's own) on the fit sample out["sample_new_ref"] = assign_cells(sample, new)[3] / px_sample if pen0: # Seeded at the worst-fitted pixel, else the refit keeps the near-black pixels' # pen where it is (measured: exactly 0.0 % change from a black start). from rrmd.encode import _cells from rrmd.vdp import LEVELS l_of, s_of, pn, _ = assign(sample, new) cells = _cells(sample) cy, cx = cells.shape[:2] pix = cells.reshape(cy * cx, 64, 3).astype(np.float64) cp = pn.reshape(cy, TILE, cx, TILE).transpose(0, 2, 1, 3).reshape(cy * cx, 64) fl, fs = l_of.reshape(-1), s_of.reshape(-1) shown = np.empty_like(pix) for ci in range(cy * cx): shown[ci] = LEVELS[int(fs[ci])][new[fl[ci]].astype(np.int64)][cp[ci]] err = np.sum((pix - shown) ** 2 * np.array([0.299, 0.587, 0.114]) * 3, axis=-1) ci, pi = divmod(int(err.argmax()), 64) seeded = new.copy() seeded[:, 0] = np.argmin(np.abs(pix[ci, pi][:, None] - LEVELS[int(fs[ci])][None, :]), axis=1) p0, hist0 = refine(sample, seeded, shared_pen0=True) out["sample_pen0"] = hist0[-1] / px_sample held_rgb = np.concatenate([load(i) for i in held], axis=0) if held else None if held_rgb is not None: px = held_rgb.shape[0] * held_rgb.shape[1] out["held_old"] = assign(held_rgb, old)[3] / px out["held_new"] = assign(held_rgb, new)[3] / px if pen0: out["held_pen0"] = assign(held_rgb, p0)[3] / px if bands > 1: # Band-local lines (PLAN 4.10: a CRAM reload per raster band), each band's fit # started from the shot's global lines so it cannot be worse than them on # that band. Rows of every sampled frame belonging to the band are fitted # together; held-out frames are scored band by band the same way. band_h = HEIGHT // bands assert band_h % TILE == 0, bands t = time.time() def band_rows(stack: np.ndarray, b: int) -> np.ndarray: n = stack.shape[0] // HEIGHT return np.concatenate([stack[f * HEIGHT + b * band_h : f * HEIGHT + (b + 1) * band_h] for f in range(n)], axis=0) total_s = total_h = 0.0 for b in range(bands): rows_s = band_rows(sample, b) band_lines, hist = refine(rows_s, new) total_s += hist[-1] if held_rgb is not None: total_h += assign(band_rows(held_rgb, b), band_lines)[3] out["sample_band"] = total_s / px_sample if held_rgb is not None: out["held_band"] = total_h / (held_rgb.shape[0] * held_rgb.shape[1]) out["t_band"] = time.time() - t return out def summarise(rows: list[dict], key_old: str, key_new: str, label: str) -> None: rows = [r for r in rows if key_old in r] if not rows: return change = np.array([100 * (r[key_new] / r[key_old] - 1) for r in rows]) weight = np.array([r["end"] - r["start"] for r in rows], dtype=np.float64) old = np.array([r[key_old] for r in rows]) new = np.array([r[key_new] for r in rows]) song = 100 * (np.sum(new * weight) / np.sum(old * weight) - 1) print(f"{label}: {len(rows)} shots, song-weighted {song:+.1f} %, mean {change.mean():+.1f} %, " f"median {np.median(change):+.1f} %, best {change.min():+.1f} %, worst {change.max():+.1f} %, " f"improved {100 * np.mean(change < 0):.0f} %") def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("fields", type=Path) ap.add_argument("summary", type=Path, help="an encode's summary.json, for its shot list") ap.add_argument("--saturation", type=float, default=1.0) ap.add_argument("--limit", type=int, help="first N shots only") ap.add_argument("--workers", type=int, default=8) ap.add_argument("--bands", type=int, default=1, help="also fit N raster bands from the global lines") ap.add_argument("--pen0", action="store_true", help="also fit the shared backdrop colour (pen 0) instead of black") ap.add_argument("--out", type=Path, help="write the per-shot rows as JSON") args = ap.parse_args(argv) summary = json.loads(args.summary.read_text()) shots = summary["shots"] ends = shots[1:] + [summary["frames"]] jobs = [(args.fields, s, e, args.saturation, args.bands, args.pen0) for s, e in zip(shots, ends)][: args.limit] rows: list[dict] = [] t0 = time.time() with ProcessPoolExecutor(args.workers) as pool: for r in pool.map(study_shot, jobs): rows.append(r) held = f"held {r['held_old']:6.1f} -> {r['held_new']:6.1f}" if "held_old" in r else "held (none) " band = f" bands {r['sample_band']:6.1f} / held {r.get('held_band', float('nan')):6.1f} ({r['t_band']:4.1f}s)" if "sample_band" in r else "" print(f"shot {r['start']:5d}-{r['end']:5d}: sample {r['sample_old']:6.1f} -> {r['sample_new']:6.1f} " f"(ref {r['sample_new_ref']:6.1f}) {held} rounds {r['rounds']:2d} " f"{r['t_old']:4.1f}s + {r['t_new']:4.1f}s{band}", flush=True) print(f"{len(rows)} shots in {time.time() - t0:.0f} s") summarise(rows, "sample_old", "sample_new", "fit sample") summarise(rows, "held_old", "held_new", "held-out ") if args.pen0: summarise(rows, "sample_new", "sample_pen0", "fitted pen 0 vs black, fit sample") summarise(rows, "held_new", "held_pen0", "fitted pen 0 vs black, held-out ") if args.bands > 1: summarise(rows, "sample_new", "sample_band", f"{args.bands} bands vs global Lloyd, fit sample") summarise(rows, "held_new", "held_band", f"{args.bands} bands vs global Lloyd, held-out ") if args.out: args.out.write_text(json.dumps(rows, indent=1)) return 0 if __name__ == "__main__": raise SystemExit(main())