"""Palette fitting on the hardware's own lattice, under the encoder's own metric. The colour floor - the error left once every cell has its best line, shade and pens, before any tile is shared - is two thirds of the full-song error, and no byte budget touches it. It is set by the four palette lines, which ``encode.fit_region`` fits with PIL's median cut: unweighted RGB, snapped to the DAC ramp afterwards (which merges pens and wastes them), refitted twice and kept only when the refit happened to help. That is not the metric the cells are then assigned with, and it is not a descent. This is the generalised Lloyd algorithm on the real problem: - E-step: ``assign`` gives every cell its best (line, shade) and every pixel its best pen, exactly, under the luma-weighted squared error (the encoder's ``LUMA_W``). - M-step: ``refit`` gives every (line, pen) the raw 0-7 channel values that minimise the summed error of the pixels using it, *each seen through its own cell's ramp*: a pen is one CRAM entry but two colours, normal and shadow, and the best entry for a pen shared by a normal cell and a shadow cell is neither cell's nearest colour. The metric is a sum of independent per-channel terms, so each channel's level is an argmin over 8 values from four sums; nothing is searched. - A pen no pixel uses is reseeded at the worst-fitted pixel of its line. Both steps are exact minimisations given the other, so the error never rises; the loop stops at convergence. Started from the median-cut fit it can only improve on it, which is also what makes a *band-local* fit safe later (PLAN 4.10): started from the frame's global lines, a band's own fit cannot be worse than the global one on that band. """ from __future__ import annotations import numpy as np from .encode import LINES, LUMA_W, PENS, _cells, fit_region from .vdp import LEVELS, NORMAL, SHADOW, TILE MAX_ROUNDS = 40 #: Stop when a round improves the total error by less than this fraction. MIN_GAIN = 2e-4 _W32 = LUMA_W.astype(np.float32) _SHADES = (NORMAL, SHADOW) def assign(rgb: np.ndarray, lines: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: """Exact per-cell (line, shade) and per-pixel pen under the weighted metric: the same answer as ``encode.assign_cells`` by the expanded form |p|^2 - 2 p.c + |c|^2, which is a (P, 3) x (3, 16) product instead of a (P, 16, 3) difference, so a round over a shot sample costs tenths of a second, not seconds. Returns (line_of (cy, cx), shade_of (cy, cx), pens (H, W) uint8, total error).""" h, w, _ = rgb.shape cy, cx = h // TILE, w // TILE pix = rgb.reshape(-1, 3).astype(np.float32) pw = np.einsum("pc,pc,c->p", pix, pix, _W32) best_cell = np.full((cy, cx), np.inf, dtype=np.float32) line_of = np.zeros((cy, cx), dtype=np.int64) shade_of = np.zeros((cy, cx), dtype=np.int64) pens = np.zeros((h, w), dtype=np.uint8) for line in range(LINES): for shade in _SHADES: pal = LEVELS[shade][lines[line].astype(np.int64)].astype(np.float32) # (16, 3) d = pw[:, None] - 2.0 * (pix @ (pal * _W32).T) + np.einsum("kc,kc,c->k", pal, pal, _W32)[None] idx = d.argmin(axis=1) err = np.take_along_axis(d, idx[:, None], axis=1)[:, 0] cell_err = err.reshape(cy, TILE, cx, TILE).sum(axis=(1, 3)) better = cell_err < best_cell if not better.any(): continue best_cell = np.where(better, cell_err, best_cell) line_of[better] = line shade_of[better] = shade mask = np.repeat(np.repeat(better, TILE, axis=0), TILE, axis=1) pens[mask] = idx.reshape(h, w)[mask] return line_of, shade_of, pens, float(np.maximum(best_cell, 0).sum()) def refit(rgb: np.ndarray, lines: np.ndarray, line_of: np.ndarray, shade_of: np.ndarray, pens: np.ndarray, shared_pen0: bool = False) -> tuple[np.ndarray, np.ndarray]: # fmt: skip """The exact M-step: new raw values for every used pen; ``used`` says which. ``shared_pen0``: pen 0 of a plane cell is transparent and shows the backdrop, CRAM entry 0, under the cell's own shade (the priority of a transparent pixel still decides shadow - Kabuto, as render.py models it). So pen 0 is one colour shared by all four lines, black so far; fitted, it is a 61st colour. The player writes all 64 CRAM words, so keeping every line's pen 0 equal to it keeps the prediction honest.""" h, w, _ = rgb.shape cy, cx = h // TILE, w // TILE pix = rgb.reshape(-1, 3).astype(np.float64) cell_line = np.repeat(np.repeat(line_of, TILE, axis=0), TILE, axis=1).reshape(-1) cell_shade = np.repeat(np.repeat(shade_of, TILE, axis=0), TILE, axis=1).reshape(-1) key = (cell_line * 2 + cell_shade) * PENS + pens.reshape(-1).astype(np.int64) k = LINES * 2 * PENS n = np.bincount(key, minlength=k).astype(np.float64).reshape(LINES, 2, PENS) s = np.stack([np.bincount(key, weights=pix[:, c], minlength=k) for c in range(3)], axis=-1) s = s.reshape(LINES, 2, PENS, 3) lv_n = LEVELS[NORMAL].astype(np.float64) lv_s = LEVELS[SHADOW].astype(np.float64) # Per channel, per candidate level: n_N L_N^2 - 2 L_N s_N + n_S L_S^2 - 2 L_S s_S # (the pixels' own squares are constant). (LINES, PENS, 3, 8) cost = (n[:, NORMAL, :, None, None] * lv_n**2 - 2.0 * lv_n * s[:, NORMAL, :, :, None] + n[:, SHADOW, :, None, None] * lv_s**2 - 2.0 * lv_s * s[:, SHADOW, :, :, None]) # fmt: skip best = cost.argmin(axis=-1).astype(np.uint8) used = n.sum(axis=1) > 0 # (LINES, PENS) used[:, 0] = False # pen 0 is the backdrop: one entry, not four new = lines.copy() new[used] = best[used] if shared_pen0 and n[:, :, 0].sum() > 0: new[:, 0] = cost[:, 0].sum(axis=0).argmin(axis=-1).astype(np.uint8) return new, used def reseed(rgb: np.ndarray, lines: np.ndarray, used: np.ndarray, line_of: np.ndarray, shade_of: np.ndarray, pens: np.ndarray) -> np.ndarray: # fmt: skip """Give every unused pen (and every duplicate, which the next E-step would leave unused) the worst-fitted pixel of its line, so it earns its keep next round. A line with no cells gets the worst pixels of the whole picture.""" h, w, _ = rgb.shape cells = _cells(rgb) # (cy, cx, 8, 8, 3) cy, cx = cells.shape[:2] pix = cells.reshape(cy * cx, TILE * TILE, 3).astype(np.float64) cell_pens = pens.reshape(cy, TILE, cx, TILE).transpose(0, 2, 1, 3).reshape(cy * cx, TILE * TILE) flat_line, flat_shade = line_of.reshape(-1), shade_of.reshape(-1) shown = np.empty_like(pix) for line in range(LINES): for shade in _SHADES: m = (flat_line == line) & (flat_shade == shade) if m.any(): shown[m] = LEVELS[shade][lines[line].astype(np.int64)][cell_pens[m]] err = np.sum((pix - shown) ** 2 * LUMA_W, axis=-1) # (cells, 64) new = lines.copy() for line in range(LINES): taken: set[tuple[int, int, int]] = set() free: list[int] = [] for pen in range(1, PENS): key = tuple(int(v) for v in new[line, pen]) if not used[line, pen] or key in taken: free.append(pen) else: taken.add(key) if not free: continue m = flat_line == line if not m.any(): m = np.ones(cy * cx, dtype=bool) cand_err = np.where(m[:, None], err, -1.0).reshape(-1) order = np.argsort(cand_err)[::-1] for pen, flat_i in zip(free, order): ci, pi = divmod(int(flat_i), TILE * TILE) shade = int(flat_shade[ci]) if m[ci] else NORMAL p = pix[ci, pi] raw = np.argmin(np.abs(p[:, None] - LEVELS[shade][None, :]), axis=1).astype(np.uint8) new[line, pen] = raw # the next pick must not be a near-copy: mark its error spent cand_err[flat_i] = -1.0 return new def refine(rgb: np.ndarray, lines: np.ndarray, max_rounds: int = MAX_ROUNDS, shared_pen0: bool = False) -> tuple[np.ndarray, list[float]]: # fmt: skip """Lloyd rounds from ``lines`` until the error stops falling. Returns the lines and the error history (the first entry is ``lines``' own error).""" _, _, _, err = assign(rgb, lines) history = [err] line_of, shade_of, pens, _ = assign(rgb, lines) for _ in range(max_rounds): new_lines, used = refit(rgb, lines, line_of, shade_of, pens, shared_pen0) new_lines = reseed(rgb, new_lines, used, line_of, shade_of, pens) l2, s2, p2, e2 = assign(rgb, new_lines) if e2 >= err: break gain = (err - e2) / err lines, line_of, shade_of, pens, err = new_lines, l2, s2, p2, e2 history.append(err) if gain < MIN_GAIN: break return lines, history def fit_lines_lloyd(rgb: np.ndarray) -> tuple[np.ndarray, list[float]]: """The fitter: median cut for a start, then Lloyd to convergence.""" lines, *_ = fit_region(rgb) return refine(rgb, lines)