Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(ui-kit): read the drawing with one exact judgment

Soohong Kim1b35c1c35e0c
diff --git a/sprite_gen/frames/ui_kit.py b/sprite_gen/frames/ui_kit.py
index f412a1f..92ba4c7 100644
--- a/sprite_gen/frames/ui_kit.py
+++ b/sprite_gen/frames/ui_kit.py
@@ -5,14 +5,15 @@ docs/ui-kit.md is the contract. One table (`LAYOUT`) is the layout: `gen --layou
draws it (`draw_guide`) and says it (`guide_text`), and the splitter cuts along it. A sheet's shape
says which part of the table it holds (`SHEETS`): a square sheet the seven frames, a 2:3 sheet the
same frames at the same places and the fills, slot, badge, pips and joystick below them. The sheet's
-alpha haze is cleared first (`alpha_floor.clear_haze`), parts are assigned to boxes by centroid
-(when a box is left empty or holds parts centred outside it, again to the layout fitted to the
-drawing within the drift a cut accepts, `_search` and `_fit_layout`), and each element's insets and
-content padding are measured on its own pixels; a fill is fitted to its bar frame's content area.
-The frames are required; an optional element whose box is empty is left out and named under
-`missing`. A drawing that drifted further than a cut accepts, a box whose parts are centred outside
-it, or a drawing that fits the layout as well under another drift that names its elements otherwise
-(`_ambiguity`) refuses the sheet: no element is cut under a name the drawing does not give it. The
+alpha haze is cleared first (`alpha_floor.clear_haze`). The drawing is then read once, exactly
+(`_judge`): the readings of its parts under the drifts the cut considers that keep the parts
+clearest of their boxes' edges, and the cut is the one reading within 1 px of the least, or the
+sheet is refused (`_decide`). Each element's insets and content padding are measured on its own
+pixels; a fill is fitted to its bar frame's content area. The frames are required; an optional
+element whose box is empty is left out and named under `missing`. A drawing that drifted further
+than a cut accepts, an empty frame box, a drawing that fits the layout as well in two ways, a box
+whose parts are centred outside it, or a drawing that lies on the layout under no drift refuses the
+sheet (`Refusal`): no element is cut under a name the drawing does not give it. The
report names each element PNG by its path from the report's own directory (`report_file`,
`element_path`). A kit is written whole into a new or empty output directory (`_write_kit`): staged
in a hidden directory beside it and renamed into place in one step. That rename, or with the report
@@ -25,8 +26,11 @@ from __future__ import annotations
import argparse
import contextlib
+import heapq
import io
+import itertools
import json
+import math
import os
import secrets
import shutil
@@ -50,21 +54,25 @@ PADDING_SPAN = 96
# A round part whose cut is more than this opaque outside the ellipse its bounding box holds was drawn on a
# square plate, not as a circle (docs/ui-kit.md "Layout").
ROUND_CORNER_FILL = 0.25
-# Fitting the layout to a drawing that drifted from it (docs/ui-kit.md "A drawing that drifted from the layout"). The
-# drift a cut accepts: along each axis a scale within DRIFT_SCALE of 1 and an offset within DRIFT_OFFSET px at 1024.
-# The fit starts from the best of DRIFT_STEPS scales by DRIFT_STEPS offsets per axis spread over that range, and runs at
-# most FIT_ROUNDS rounds of fit and assignment, from at least FIT_MIN_BOXES boxes that hold parts. A fit more than a
-# step of that grid outside the range is refused.
+# Reading the drawing (docs/ui-kit.md "Reading the drawing"). The drift a cut accepts: along each axis a scale within
+# DRIFT_SCALE of 1 and an offset within DRIFT_OFFSET px at 1024. The cut considers the drifts within that range and
+# DRIFT_MARGIN of it beyond either end (a scale from 0.875 to 1.125, an offset of at most 120 px at 1024), so that a
+# drawing drawn at the edge of the range is read under its own drift and a reading just beyond it is still a rival. A
+# part keeps clear of its box's edges, as the guide asks, when it lies CLEARANCE px inside them, and two readings whose
+# costs differ by no more than TIE px fit the drawing equally well. A least-squares fit is taken from FIT_MIN_BOXES or
+# more boxes that hold parts.
DRIFT_SCALE = 0.1
DRIFT_OFFSET = 2 * GAP
-DRIFT_STEPS = 9
-FIT_ROUNDS = 8
+DRIFT_MARGIN = 0.25
FIT_MIN_BOXES = 3
-# A drawing that fits the layout in two ways (docs/ui-kit.md "A drawing that fits the layout in two ways"): a part
-# keeps clear of its box's edges, as the guide asks, when it lies CLEARANCE px inside them, and two readings of a
-# drawing whose shortfalls from that differ by no more than TIE px fit it equally well.
CLEARANCE = 1.0
TIE = 1.0
+# The search (`_judge`) solves a span of drifts whole once its undecided parts can be read in at most LEAF_WAYS ways, or
+# once it moves no box more than LEAF_WIDTH px. Its work bound is SEARCH_NODES spans, well above what drawn sheets need:
+# past it, a sheet every reading of which is proven to cost more than TIE is refused as off the layout.
+LEAF_WAYS = 48
+LEAF_WIDTH = 1e-3
+SEARCH_NODES = 6000
GUIDE_BACKGROUND = (0xF6, 0xF6, 0xF6)
GUIDE_BOX = (0x2F, 0x80, 0xED)
STRETCHES = ("xy", "x", "none")
@@ -377,21 +385,6 @@ def _parts(mask: Any) -> list[dict[str, Any]]:
return parts
-def _assign(parts: list[dict[str, Any]], scaled: dict[str, tuple[float, float, float, float]],
- reach: tuple[float, float]) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, Any]]]:
- """Each part to the box, widened by ``reach`` along x and y, that holds its centroid (the first in layout
- order): the parts by box, and the parts in no box."""
- assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}
- loose = []
- rx, ry = reach
- for part in parts:
- cx, cy = part["centroid"]
- owner = next((name for name, (x, y, w, h) in scaled.items()
- if x - rx <= cx < x + w + rx and y - ry <= cy < y + h + ry), None)
- (assigned[owner] if owner is not None else loose).append(part)
- return assigned, loose
-
-
def _bbox(parts: list[dict[str, Any]]) -> tuple[int, int, int, int]:
"""The bounding box (x0, y0, x1, y1) of ``parts``."""
return (min(part["bbox"][0] for part in parts), min(part["bbox"][1] for part in parts),
@@ -413,9 +406,9 @@ def _off_centre(assigned: dict[str, list[dict[str, Any]]],
def _fit(assigned: dict[str, list[dict[str, Any]]],
- scaled: dict[str, tuple[float, float, float, float]]) -> tuple[tuple[float, float], ...] | None:
- """The scale and offset along x and y that move the layout's box centres closest (least squares) to the
- centres of what each box holds; None from fewer than FIT_MIN_BOXES boxes that hold parts."""
+ scaled: dict[str, tuple[float, float, float, float]]) -> tuple[float, float, float, float] | None:
+ """The drift (sx, tx, sy, ty) that moves the layout's box centres closest (least squares) to the centres of what
+ each box holds; None from fewer than FIT_MIN_BOXES boxes that hold parts."""
centres, drawn = [], []
for name, parts in assigned.items():
if parts:
@@ -426,302 +419,586 @@ def _fit(assigned: dict[str, list[dict[str, Any]]],
if len(centres) < FIT_MIN_BOXES:
return None
centres_array, drawn_array = np.asarray(centres), np.asarray(drawn)
- fit = []
+ fit: list[float] = []
for axis in (0, 1):
box, held = centres_array[:, axis], drawn_array[:, axis]
if np.ptp(box) < 1: # every box centred on one line along this axis: an offset alone
- fit.append((1.0, float(np.mean(held - box))))
+ fit += [1.0, float(np.mean(held - box))]
else:
scale, offset = np.polyfit(box, held, 1)
- fit.append((float(scale), float(offset)))
- return tuple(fit)
+ fit += [float(scale), float(offset)]
+ sx, tx, sy, ty = fit
+ return sx, tx, sy, ty
-def _same(one: dict[str, list[dict[str, Any]]], other: dict[str, list[dict[str, Any]]]) -> bool:
- """Whether two assignments give every box the same parts."""
- return all(list(map(id, one[name])) == list(map(id, other[name])) for name in one)
+def _drift_limits(unit: float) -> tuple[float, float]:
+ """How far the scale of a drift the cut considers may lie from 1, and its offset from 0, along each axis (``unit``
+ sheet pixels to a layout pixel at 1024): the range a cut accepts and DRIFT_MARGIN of it beyond either end."""
+ return DRIFT_SCALE * (1 + DRIFT_MARGIN), DRIFT_OFFSET * unit * (1 + DRIFT_MARGIN)
-def _search(parts: list[dict[str, Any]], scaled: dict[str, tuple[float, float, float, float]], reach: float,
- unit: float) -> dict[str, list[dict[str, Any]]] | None:
- """The assignment the fit starts from (docs/ui-kit.md "A drawing that drifted from the layout"). The layout's boxes
- are moved by each drift of a grid over the range a cut accepts (``unit`` sheet pixels to a layout pixel at 1024),
- the parts assigned to them as `_assign` assigns them, and each assignment fitted as `_fit` fits one; the one whose
- parts lie nearest the centres of their fitted boxes wins. A box scores 1 for parts centred on its fitted box, down
- to 0 for parts centred on its edge or outside it, so a box that holds a neighbour's element counts for nothing.
- None when no drift's boxes hold FIT_MIN_BOXES boxes."""
- if not parts:
- return None
- names = list(scaled)
- layout = np.asarray([scaled[name] for name in names], dtype=float) # per box: x, y, w, h
- centroid = np.asarray([part["centroid"] for part in parts], dtype=float)
- bbox = np.asarray([part["bbox"] for part in parts], dtype=float) # per part: x0, y0, x1, y1
- centre, half = layout[:, :2] + layout[:, 2:] / 2, layout[:, 2:] / 2
- steps = np.linspace(-1, 1, DRIFT_STEPS)
- scale = np.repeat(1 + DRIFT_SCALE * steps, DRIFT_STEPS) # the drifts along one axis
- offset = np.tile(DRIFT_OFFSET * unit * steps, DRIFT_STEPS)
- within = [] # per axis, [drift, part, box]: the part's centroid lies in the moved box, widened by the reach
- for axis in (0, 1):
- low = (layout[:, axis] - reach) * scale[:, None] + offset[:, None]
- high = (layout[:, axis] + layout[:, 2 + axis] + reach) * scale[:, None] + offset[:, None]
- at = centroid[None, :, axis, None]
- within.append((low[:, None, :] <= at) & (at < high[:, None, :]))
- best, best_score = None, -np.inf
- for along_x in within[0]: # each drift along x, with every drift along y: [drift along y, part, box]
- both = along_x[None] & within[1]
- owner = both & (np.cumsum(both, axis=2) == 1) # each part to the first box that takes it, in layout order
- held = owner.any(axis=1)
- count = held.sum(axis=1)
- valid = count >= FIT_MIN_BOXES
- off = np.zeros(held.shape)
- for axis in (0, 1):
- low = np.where(owner, bbox[None, :, axis, None], np.inf).min(axis=1)
- high = np.where(owner, bbox[None, :, 2 + axis, None], -np.inf).max(axis=1)
- drawn = (np.where(held, low, 0.0) + np.where(held, high, 0.0)) / 2
- box = np.broadcast_to(centre[:, axis], held.shape)
- n = np.maximum(count, 1)
- box_mean, drawn_mean = (held * box).sum(axis=1) / n, (held * drawn).sum(axis=1) / n
- du, dv = held * (box - box_mean[:, None]), held * (drawn - drawn_mean[:, None])
- spread = np.where(held, box, -np.inf).max(axis=1) - np.where(held, box, np.inf).min(axis=1)
- suu = (du * du).sum(axis=1)
- # least squares, or an offset alone when every box that holds parts is centred on one line (`_fit`)
- s = np.where(spread >= 1, (du * dv).sum(axis=1) / np.where(suu > 0, suu, 1), 1.0)
- t = drawn_mean - s * box_mean
- valid &= s > 0
- safe = np.where(s > 0, s, 1.0)
- off = np.maximum(off, np.abs(drawn - (safe[:, None] * box + t[:, None])) / (safe[:, None] * half[:, axis]))
- score = np.where(valid, (held * np.clip(1 - off, 0, None)).sum(axis=1), -np.inf)
- index = int(np.argmax(score))
- if score[index] > best_score:
- best, best_score = owner[index].copy(), score[index]
- if best is None:
- return None
- return {name: [parts[index] for index in np.flatnonzero(best[:, box])] for box, name in enumerate(names)}
-
-
-def _fit_layout(parts: list[dict[str, Any]], scaled: dict[str, tuple[float, float, float, float]], reach: float,
- start: dict[str, list[dict[str, Any]]]) -> tuple[Any, ...] | None:
- """Fit the layout to a drawing that drifted from it (docs/ui-kit.md "A drawing that drifted from the layout"),
- from the assignment ``start`` (`_search`): fit the boxes to what they hold, assign the parts to the fitted boxes,
- and again, until the assignment repeats. Returns the fit, the fitted boxes, and their assignment and loose
- parts; None when ``start`` cannot be fitted."""
- current, found = start, None
- for _ in range(FIT_ROUNDS):
- fit = _fit(current, scaled)
- if fit is None or min(fit[0][0], fit[1][0]) <= 0:
- break
- (sx, tx), (sy, ty) = fit
- moved = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in scaled.items()}
- following, loose = _assign(parts, moved, (reach * sx, reach * sy))
- found = (fit, moved, following, loose)
- if _same(following, current):
- break
- current = following
- return found
-
+def _considered(drift: tuple[float, float, float, float], unit: float) -> bool:
+ """Whether the cut considers ``drift`` (`_drift_limits`)."""
+ scale, offset = _drift_limits(unit)
+ sx, tx, sy, ty = drift
+ return max(abs(sx - 1), abs(sy - 1)) <= scale and max(abs(tx), abs(ty)) <= offset
-def _drift_limits(unit: float) -> tuple[float, float]:
- """How far a fit's scale may lie from 1 and its offset from 0 along each axis (``unit`` sheet pixels to a layout
- pixel at 1024). A drawing drawn at the edge of the range, its elements a little off their boxes' centres, is fitted
- a little to either side of it, so the limits lie a step of the search's grid outside the range."""
- step = 2 / (DRIFT_STEPS - 1) # a step of the grid, as a share of the range
- return DRIFT_SCALE * (1 + step), DRIFT_OFFSET * unit * (1 + step)
+@dataclass(frozen=True)
+class Reading:
+ """A reading of the drawing (docs/ui-kit.md "Reading the drawing"). ``drift`` (sx, tx, sy, ty) moves each layout
+ box (x, y, w, h) to (x sx + tx, y sy + ty, w sx, h sy). ``boxes`` names the box each part goes to (None for a part
+ in no box), in the order of the parts read. ``cost``, in sheet pixels, is the least cost of a reading that puts the
+ parts so; ``drift`` reads the drawing so, at that cost to within a millionth of a pixel."""
-def _drift_refusal(fit: tuple[tuple[float, float], ...], unit: float) -> str | None:
- """Why a fit lies outside the drift a cut accepts (`_drift_limits`), or None."""
- (sx, tx), (sy, ty) = fit
- scale, offset = _drift_limits(unit)
- if max(abs(sx - 1), abs(sy - 1)) <= scale and max(abs(tx), abs(ty)) <= offset:
- return None
- limit = DRIFT_OFFSET * unit
- return (f"the drawing drifted further from the layout than a cut accepts: fitted to it, the layout is scaled "
- f"{sx:.3f} along x and {sy:.3f} along y and offset {tx:.1f}, {ty:.1f} px, where a cut accepts a scale "
- f"from {1 - DRIFT_SCALE:g} to {1 + DRIFT_SCALE:g} and an offset of at most {limit:g} px along each axis; "
- "generate the sheet again")
+ drift: tuple[float, float, float, float]
+ boxes: tuple[str | None, ...]
+ cost: float
-def _least(bounds: Any, hinges: Any) -> float:
- """The least, over the drifts (s, t) along one axis with a s + b t <= c for each row (a, b, c) of ``bounds``, of
- the sum over the rows (p, q, r) of ``hinges`` of max(0, p s + q t + r); inf when no drift keeps every bound. The
- sum is linear between the lines on which a bound or a hinge turns, so it is least where two of them cross."""
- lines = np.concatenate((bounds, hinges * (1, 1, -1)))
+@dataclass(frozen=True)
+class Judgment:
+ """What the cut's search found in a drawing (`_judge`): the ``parts`` read; the least cost of any reading the cut
+ considers (``least``) and of one whose every required box holds a part (``least_valid``), exact when the search
+ ran to its end and otherwise proven lower bounds; the readings the cut is decided among (``candidates``), cheapest
+ first (for a drawing the search stopped on as ambiguous, those it had found); when the search stopped at its work
+ bound, the cost every reading is proven to exceed (``proven``); and the spans of drifts it took (``nodes``)."""
+
+ parts: list[dict[str, Any]]
+ least: float
+ least_valid: float
+ candidates: tuple[Reading, ...]
+ proven: float | None
+ nodes: int
+ drawing: _Drawing
+
+
+class Refusal(ValueError):
+ """A sheet `split_ui_kit` refuses (docs/ui-kit.md "Reading the drawing"): its message, its ``reason``
+ (``drifted``, ``required``, ``ambiguous``, ``off-centre`` or ``off-layout``), the ``parts`` read and the ``least``
+ cost of a reading (`Judgment`); a drawing that fits the layout in two ways also gives the two readings
+ (``witnesses``)."""
+
+ def __init__(self, message: str, reason: str, judgment: Judgment, witnesses: tuple[Reading, ...] = ()) -> None:
+ super().__init__(message)
+ self.reason = reason
+ self.parts = judgment.parts
+ self.least = judgment.least
+ self.witnesses = witnesses
+
+
+Row = tuple[float, float, float] # (a, b, c): a s + b t <= c, a half-plane of the drifts (s, t) along one axis
+Span = tuple[float, float, float, float] # (s0, s1, t0, t1): the drifts along one axis, s0 <= s <= s1, t0 <= t <= t1
+
+
+class _Axis:
+ """The layout's boxes and the parts along one axis: each box's edges (``e0``, ``e1``) and its edges widened by the
+ reach (``lo``, ``hi``), as a row of one value a box; each part's centroid (``c``) and its bounding box's edges
+ (``p0``, ``p1``, exclusive), as a column of one value a part."""
+
+ def __init__(self, low: Any, high: Any, reach: float, centre: Any, first: Any, last: Any) -> None:
+ self.e0, self.e1 = low[None, :], high[None, :]
+ self.lo, self.hi = self.e0 - reach, self.e1 + reach
+ self.c, self.p0, self.p1 = centre[:, None], first[:, None], last[:, None]
+ self.extent = float(self.hi.max(initial=1.0))
+
+ def held_at(self, s: float, t: float) -> Any:
+ """[part, box]: the box, moved by (s, t) and widened, holds the part's centroid (its low edge in, its high edge
+ out, as `_parts` gives a bounding box)."""
+ return (self.lo * s + t <= self.c) & (self.c < self.hi * s + t)
+
+ def short_at(self, s: float, t: float) -> Any:
+ """[part, box]: how far the part's two sides fall short of lying CLEARANCE inside the box moved by (s, t)."""
+ return (np.maximum(0, self.e0 * s + t + CLEARANCE - self.p0)
+ + np.maximum(0, self.p1 - (self.e1 * s + t) + CLEARANCE))
+
+ def status(self, span: Span, rows: Any) -> tuple[Any, Any]:
+ """[part, box] for the parts ``rows``: the widened box holds the centroid at every drift of ``span``, and at
+ none. Every box lies more than the reach in from the sheet's edges, so its widened edges are positive: least at
+ (s0, t0) and greatest at (s1, t1)."""
+ s0, s1, t0, t1 = span
+ c = self.c[rows]
+ return ((self.lo * s1 + t1 <= c) & (c < self.hi * s0 + t0),
+ (c < self.lo * s0 + t0) | (c >= self.hi * s1 + t1))
+
+ def least_short(self, span: Span, rows: Any, boxes: Any = None) -> Any:
+ """A lower bound, over the drifts of ``span``, of `short_at` (each side at its own corner): [part, box] for the
+ parts ``rows``, or, given each one's box (``boxes``), [part]."""
+ s0, s1, t0, t1 = span
+ if boxes is None:
+ e0, e1, p0, p1 = self.e0, self.e1, self.p0[rows], self.p1[rows]
+ else:
+ e0, e1, p0, p1 = self.e0[0, boxes], self.e1[0, boxes], self.p0[rows, 0], self.p1[rows, 0]
+ return np.maximum(0, e0 * s0 + t0 + CLEARANCE - p0) + np.maximum(0, p1 - (e1 * s1 + t1) + CLEARANCE)
+
+ def hinges(self, parts: Any, boxes: Any) -> Any:
+ """The rows (a, b, c) whose max(0, a s + b t + c) are the shortfalls of the sides of ``parts`` in ``boxes``."""
+ n = len(parts)
+ out = np.empty((2 * n, 3))
+ out[:n, 0], out[:n, 1], out[:n, 2] = self.e0[0, boxes], 1.0, CLEARANCE - self.p0[parts, 0]
+ out[n:, 0], out[n:, 1], out[n:, 2] = -self.e1[0, boxes], -1.0, self.p1[parts, 0] + CLEARANCE
+ return out
+
+ def within(self, part: int, box: int) -> list[Row]:
+ """The rows that keep the part's centroid in the widened box: both edges in, so that at an edge both readings
+ are admitted, each at the cost it reaches beside the edge."""
+ c = float(self.c[part, 0])
+ return [(float(self.lo[0, box]), 1.0, c), (-float(self.hi[0, box]), -1.0, -c)]
+
+ def beside(self, part: int, box: int, span: Span) -> list[Row]:
+ """The rows, one a way, that keep the part's centroid out of the widened box at some drift of ``span``: below
+ its low edge, or at or past its high edge."""
+ s0, s1, t0, t1 = span
+ c, lo, hi = float(self.c[part, 0]), float(self.lo[0, box]), float(self.hi[0, box])
+ return ([(-lo, -1.0, -c)] if lo * s1 + t1 >= c else []) + ([(hi, 1.0, c)] if hi * s0 + t0 <= c else [])
+
+
+def _least_on_axis(span: Span, rows: list[Row], hinges: Any) -> tuple[float, tuple[float, float] | None]:
+ """The least, over the drifts (s, t) of ``span`` that keep every row of ``rows``, of the sum over the rows (a, b,
+ c) of ``hinges`` of max(0, a s + b t + c), and a drift that reaches it; (inf, None) when no drift keeps the rows.
+ The sum is convex and linear between the lines on which a row binds or a hinge turns, so it is least where two of
+ them cross. A hinge that does not turn within ``span`` is linear there and draws no line."""
+ s0, s1, t0, t1 = span
+ bounds = np.array([(-1.0, 0.0, -s0), (1.0, 0.0, s1), (0.0, -1.0, -t0), (0.0, 1.0, t1), *rows])
+ at = hinges[:, :1] * np.array([s0, s0, s1, s1]) + hinges[:, 1:2] * np.array([t0, t1, t0, t1]) + hinges[:, 2:]
+ rising = at.min(axis=1, initial=np.inf) >= 0
+ turning = hinges[~rising & (at.max(axis=1, initial=-np.inf) > 0)]
+ linear = hinges[rising].sum(axis=0)
+ lines = np.concatenate((bounds, turning * (1, 1, -1)))
a, b, c = lines.T
i, j = np.triu_indices(len(lines), 1)
det = a[i] * b[j] - a[j] * b[i]
crossing = np.abs(det) > 1e-12
i, j, det = i[crossing], j[crossing], det[crossing]
s, t = (c[i] * b[j] - c[j] * b[i]) / det, (a[i] * c[j] - a[j] * c[i]) / det
- kept = (bounds[:, :1] * s + bounds[:, 1:2] * t <= bounds[:, 2:] + 1e-6).all(axis=0)
+ kept = (bounds[:, :1] * s + bounds[:, 1:2] * t <= bounds[:, 2:] + 1e-9 * (1 + np.abs(bounds[:, 2:]))).all(axis=0)
if not kept.any():
- return np.inf
- return float(np.maximum(0, hinges[:, :1] * s[kept] + hinges[:, 1:2] * t[kept] + hinges[:, 2:]).sum(axis=0).min())
-
-
-def _ambiguity(parts: list[dict[str, Any]], assigned: dict[str, list[dict[str, Any]]],
- layout: dict[str, tuple[int, int, int, int]], unit: float, reach: float,
- required: set[str]) -> str | None:
- """Why the drawing does not say which element is which, or None (docs/ui-kit.md "A drawing that fits the layout in
- two ways").
-
- A reading of the drawing puts parts in the layout's boxes moved by one drift within `_drift_limits`, each part's
- centroid in its box widened by ``reach`` (the widening moved with the box), and names each box that holds parts by
- the largest. Its shortfall is the least, over the drifts that keep every centroid so, of how far the sides of its
- parts are from lying CLEARANCE px inside their boxes, added up. The cut (``assigned``) names each box by its largest
- part, and the least shortfall of a reading that names the boxes so is that of those parts alone. A reading that
- names them otherwise (a box held in one and empty in the other, or held by another part) puts each part the cut
- names a box by in a box, empty or with a larger part, and leaves out any other part or makes it the largest part of
- a box. When one comes within TIE of the cut's shortfall, the drawing is refused.
-
- The search is exact. With the cut's largest parts in their boxes, the names differ only where another part is the
- largest of a box, an empty one or one whose largest part it outweighs: one bound for each such placement. Else one
- of the cut's largest parts, at most one a box, lies elsewhere: they are placed largest first, each placement kept
- while some drift keeps every centroid in its box within the shortfall, and the other parts stay out (leaving one out
- never adds to a shortfall), but where a box that must hold an element is left empty."""
- names = list(layout)
- scale, offset = _drift_limits(unit)
- limits = np.array([(-1, 0, scale - 1), (1, 0, 1 + scale), (0, -1, offset), (0, 1, offset)], dtype=float)
- order = sorted(range(len(parts)), key=lambda k: -parts[k]["pixels"]) # largest first, ties in part order
- rank = {k: n for n, k in enumerate(order)}
- box = np.asarray([layout[name] for name in names], dtype=float) # per box: x, y, w, h
- bbox = np.asarray([part["bbox"] for part in parts], dtype=float).reshape(-1, 4) # per part: x0, y0, x1, y1
- centroid = np.asarray([part["centroid"] for part in parts], dtype=float).reshape(-1, 2)
-
- def rows(a: Any, b: float, c: Any) -> Any:
- """A row (a, b, c) for each part and box, from values by box (a), and by part (c)."""
- return np.stack(np.broadcast_arrays(a, b, c), axis=-1)
-
- bounds, hinges, reachable = [], [], np.ones((len(parts), len(names)), dtype=bool)
- for axis in (0, 1):
- low, high = box[:, axis], box[:, axis] + box[:, 2 + axis]
- at, lo, hi = centroid[:, axis, None], bbox[:, axis, None], bbox[:, 2 + axis, None]
- # per part and box, the rows that keep the centroid in the box widened and moved by (s, t), a s + b t <= c,
- # and the shortfall of each side, max(0, p s + q t + r)
- bounds.append(np.stack((rows(low - reach, 1, at), rows(-(high + reach), -1, -at)), axis=2))
- hinges.append(np.stack((rows(low, 1, CLEARANCE - lo), rows(-high, -1, CLEARANCE + hi)), axis=2))
- # some drift within the limits keeps the centroid in the widened box: the scales from (at - offset) / (high +
- # reach) to (at + offset) / (low - reach) meet theirs (low > reach: every box lies a gap in from the edges)
- reachable &= (np.maximum(1 - scale, (at - offset) / (high + reach))
- <= np.minimum(1 + scale, (at + offset) / (low - reach)))
-
- def shortfall(placed: tuple[tuple[int, int], ...]) -> float:
- """The least shortfall of the (part, box) pairs ``placed``; inf when no drift keeps each centroid in its box."""
- pairs = ([k for k, _ in placed], [i for _, i in placed])
- return sum(_least(np.concatenate((limits, bounds[axis][pairs].reshape(-1, 3))),
- hinges[axis][pairs].reshape(-1, 3)) for axis in (0, 1))
-
- index = {id(part): k for k, part in enumerate(parts)}
- cut = {min((index[id(part)] for part in assigned[name]), key=rank.__getitem__): i
- for i, name in enumerate(names) if assigned[name]} # each box's largest part -> the box
- named = {i: k for k, i in cut.items()} # the box -> its largest part
- within = shortfall(tuple(cut.items())) + TIE
- needed = {names.index(name) for name in required}
- others = [k for k in order if k not in cut]
-
- def fill(placed: tuple[tuple[int, int], ...], largest: dict[int, int], empty: set[int]) -> dict[int, int] | None:
- """``largest`` with each box of ``empty`` the largest part of one of the other parts within the shortfall, or
- None."""
- if not empty:
- return largest
- i = min(empty)
- taken = {k for k, _ in placed}
- for k in others:
- if k not in taken and reachable[k, i] and shortfall(more := placed + ((k, i),)) <= within:
- filled = fill(more, {**largest, i: k}, empty - {i})
- if filled is not None:
- return filled
- return None
-
- def otherwise() -> dict[int, int] | None:
- """The largest part of each box under a reading within the shortfall that names the boxes otherwise, or None."""
- # The cut's largest parts in their boxes, and another part the largest of a box: an empty one, or one whose
- # largest part it outweighs.
- for k in others:
- for i in map(int, np.flatnonzero(reachable[k])):
- if (i not in named or rank[k] < rank[named[i]]) and shortfall((*cut.items(), (k, i))) <= within:
- return {**named, i: k}
- # One of the cut's largest parts elsewhere: in another box, or with a larger part. Those parts are placed
- # largest first, depth first, each in its own box first; the other parts stay out, but where a box that must
- # hold an element is left empty.
- mains = sorted(cut, key=rank.__getitem__)
- stack: list[tuple[int, tuple[tuple[int, int], ...], dict[int, int], bool]] = [(0, (), {}, False)]
- while stack:
- depth, placed, largest, differs = stack.pop()
- if depth == len(mains):
- filled = fill(placed, largest, needed - largest.keys()) if differs else None
- if filled is not None:
- return filled
+ return math.inf, None
+ s, t = s[kept], t[kept]
+ value = linear[0] * s + linear[1] * t + linear[2]
+ if len(turning):
+ value = value + np.maximum(0, turning[:, :1] * s + turning[:, 1:2] * t + turning[:, 2:]).sum(axis=0)
+ k = int(np.argmin(value))
+ return max(0.0, float(value[k])), (float(s[k]), float(t[k]))
+
+
+def _middle(span: Span, rows: list[Row]) -> tuple[float, float] | None:
+ """The mean of the corners of the drifts of ``span`` that keep every row: inside them all when they leave room."""
+ s0, s1, t0, t1 = span
+ lines = np.array([(-1.0, 0.0, -s0), (1.0, 0.0, s1), (0.0, -1.0, -t0), (0.0, 1.0, t1), *rows])
+ a, b, c = lines.T
+ i, j = np.triu_indices(len(lines), 1)
+ det = a[i] * b[j] - a[j] * b[i]
+ crossing = np.abs(det) > 1e-12
+ i, j, det = i[crossing], j[crossing], det[crossing]
+ s, t = (c[i] * b[j] - c[j] * b[i]) / det, (a[i] * c[j] - a[j] * c[i]) / det
+ kept = (lines[:, :1] * s + lines[:, 1:2] * t <= lines[:, 2:] + 1e-9 * (1 + np.abs(lines[:, 2:]))).all(axis=0)
+ return (float(s[kept].mean()), float(t[kept].mean())) if kept.any() else None
+
+
+class _Drawing:
+ """The parts and the layout's boxes of a sheet, as arrays: the reading at a drift, and the bounds the search takes
+ over a box of drifts (``span``: sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1)."""
+
+ def __init__(self, parts: list[dict[str, Any]], size: tuple[int, int]) -> None:
+ layout = boxes(size)
+ _, slots = sheet_layout(size)
+ self.parts, self.layout, self.names = parts, layout, list(layout)
+ self.required = frozenset(index for index, slot in enumerate(slots) if not slot.optional)
+ self.unit = size[0] / REFERENCE
+ reach = GAP / 2 * self.unit
+ box = np.asarray(list(layout.values()), dtype=float)
+ centroid = np.asarray([part["centroid"] for part in parts], dtype=float).reshape(-1, 2)
+ self.bbox = bbox = np.asarray([part["bbox"] for part in parts], dtype=float).reshape(-1, 4)
+ self.x = _Axis(box[:, 0], box[:, 0] + box[:, 2], reach, centroid[:, 0], bbox[:, 0], bbox[:, 2])
+ self.y = _Axis(box[:, 1], box[:, 1] + box[:, 3], reach, centroid[:, 1], bbox[:, 1], bbox[:, 3])
+ # A part in no box costs about the least a part of its size costs against a box whose widened box does not
+ # hold its centroid: the same under every drift, so it never pulls the reading, and more for a larger part, so
+ # that leaving a large element that overflows its box out of every box never costs less than keeping it.
+ self.loose = reach + CLEARANCE + np.minimum(bbox[:, 2] - bbox[:, 0], bbox[:, 3] - bbox[:, 1]) / 2
+ # Widened boxes overlap only where rounding a sheet's boxes narrowed a gap; a part in both goes to the first.
+ overlap = ((self.x.lo.T < self.x.hi) & (self.x.lo < self.x.hi.T)
+ & (self.y.lo.T < self.y.hi) & (self.y.lo < self.y.hi.T))
+ self.earlier = np.triu(overlap, 1) # [box, later box]
+
+ def read(self, drift: tuple[float, float, float, float]) -> tuple[float, tuple[int, ...]]:
+ """The reading at ``drift``: its cost, and each part's box (its index in layout order, -1 for none)."""
+ sx, tx, sy, ty = drift
+ held = self.x.held_at(sx, tx) & self.y.held_at(sy, ty)
+ placed = held.any(axis=1)
+ key = np.where(placed, held.argmax(axis=1), -1)
+ short = self.x.short_at(sx, tx) + self.y.short_at(sy, ty)
+ inside = np.take_along_axis(short, np.maximum(key, 0)[:, None], axis=1)[:, 0]
+ return float(np.where(placed, inside, self.loose).sum()), tuple(key.tolist())
+
+ def valid(self, key: tuple[int, ...]) -> bool:
+ """Whether every required box holds a part."""
+ return self.required <= set(key)
+
+ def named(self, key: tuple[int, ...]) -> tuple[str | None, ...]:
+ """Each part's box by name, None for none."""
+ return tuple(self.names[box] if box >= 0 else None for box in key)
+
+ def assigned(self, key: tuple[int, ...]) -> dict[str, list[dict[str, Any]]]:
+ """The parts by box, in layout order."""
+ assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in self.names}
+ for part, box in zip(self.parts, key):
+ if box >= 0:
+ assigned[self.names[box]].append(part)
+ return assigned
+
+ def bound(self, span: tuple[float, ...], open_: Any, fixed: Any) -> tuple[float, dict[str, Any]]:
+ """A lower bound of the cost of every reading at the drifts of ``span``, and what the span decides of the parts
+ still open (``open_``; ``fixed`` gives every other part's box, -1 for none and -2 for an open part). For each
+ open part, the least it can cost (``least``): in a box that may hold its centroid somewhere in the span, each of
+ its sides at its own corner, or in no box when no box holds it everywhere (``free``). A box after one that holds
+ it everywhere never holds it."""
+ sx, sy = span[:4], span[4:]
+ inx, outx = self.x.status(sx, open_)
+ iny, outy = self.y.status(sy, open_)
+ held = inx & iny
+ may = ~(outx | outy) & ~((np.cumsum(held, axis=1) - held) > 0)
+ free = ~held.any(axis=1)
+ short = self.x.least_short(sx, open_) + self.y.least_short(sy, open_)
+ least = np.where(may, short, np.inf).min(axis=1, initial=np.inf)
+ least = np.where(free, np.minimum(least, self.loose[open_]), least)
+ placed = np.flatnonzero(fixed >= 0)
+ settled = (self.x.least_short(sx, placed, fixed[placed]).sum()
+ + self.y.least_short(sy, placed, fixed[placed]).sum() + self.loose[fixed == -1].sum())
+ return float(least.sum() + settled), {"inx": inx, "iny": iny, "may": may, "free": free, "short": short,
+ "least": least}
+
+ def outcomes(self, span: tuple[float, ...], part: int, row: int,
+ info: dict[str, Any]) -> list[tuple[int, list[Row], list[Row]]]:
+ """The ways the span may read an undecided part (``row`` of the open parts `bound` gave ``info`` of): its box
+ (-1 for none) and the rows along x and along y that read it so. A part in a box is out of every earlier box
+ whose widened box overlaps it; a part in no box is out of every box that may hold it, along x or along y."""
+ sx, sy = span[:4], span[4:]
+ may = info["may"][row]
+
+ def apart(others: Any) -> list[tuple[list[Row], list[Row]]]:
+ """The ways the centroid lies out of each widened box of ``others``: along x or along y, at an edge each."""
+ choices = [[("x", way) for way in (self.x.beside(part, box, sx) if not info["inx"][row, box] else [])]
+ + [("y", way) for way in (self.y.beside(part, box, sy) if not info["iny"][row, box] else [])]
+ for box in others]
+ return [([way for axis, way in term if axis == "x"], [way for axis, way in term if axis == "y"])
+ for term in itertools.product(*choices)]
+
+ ways = []
+ for box in map(int, np.flatnonzero(may)):
+ rx = [] if info["inx"][row, box] else self.x.within(part, box)
+ ry = [] if info["iny"][row, box] else self.y.within(part, box)
+ for ex, ey in apart(np.flatnonzero(self.earlier[:box, box] & may[:box])):
+ ways.append((box, rx + ex, ry + ey))
+ if info["free"][row]:
+ ways += [(-1, ex, ey) for ex, ey in apart(np.flatnonzero(may))]
+ return ways
+
+
+def _split(span: tuple[float, ...], drawing: _Drawing) -> tuple[tuple[float, ...], tuple[float, ...], float]:
+ """The two halves of ``span`` across its widest side, measured in how far it moves the boxes, and that width."""
+ sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1 = span
+ widths = [(sx1 - sx0) * drawing.x.extent, tx1 - tx0, (sy1 - sy0) * drawing.y.extent, ty1 - ty0]
+ side = int(np.argmax(widths))
+ middle = (span[2 * side] + span[2 * side + 1]) / 2
+ low, high = list(span), list(span)
+ low[2 * side + 1], high[2 * side] = middle, middle
+ return tuple(low), tuple(high), max(widths)
+
+
+class _Search:
+ """The exact search for the least-cost readings of a drawing (`_judge`): best-first branch and bound over spans of
+ drifts."""
+
+ def __init__(self, drawing: _Drawing) -> None:
+ self.drawing = drawing
+ scale, offset = _drift_limits(drawing.unit)
+ self.region = (1 - scale, 1 + scale, -offset, offset) * 2
+ self.best = math.inf # the least cost found
+ self.exact = math.inf # the least cost of a span solved whole
+ # Every reading found within 2 TIE of the least cost, by its key (each part's box): its least cost, a drift
+ # that reaches it, and how it was solved (the spans and rows along x and y; None for a reading at one drift).
+ self.found: dict[tuple[int, ...], tuple[float, tuple[float, float, float, float], Any]] = {}
+ self.close: set[tuple[int, ...]] = set() # readings that hold every required box, at a cost of TIE or less
+ self.nodes = 0
+
+ def note(self, key: tuple[int, ...], cost: float, drift: tuple[float, float, float, float],
+ solved: Any = None) -> None:
+ self.best = min(self.best, cost)
+ if cost <= self.best + 2 * TIE and cost < self.found.get(key, (math.inf,))[0]:
+ self.found[key] = (cost, drift, solved)
+ if cost <= TIE and self.drawing.valid(key):
+ self.close.add(key)
+
+ def read(self, drift: tuple[float, float, float, float]) -> None:
+ cost, key = self.drawing.read(drift)
+ self.note(key, cost, drift)
+
+ def solve(self, span: tuple[float, ...], fixed: Any, undecided: Any,
+ ways: list[list[tuple[int, list[Row], list[Row]]]], floors: Any, rest: float) -> None:
+ """Every reading of a span solved whole: for each way of reading its undecided parts whose bound may still come
+ within 2 TIE of the least cost, its least cost along each axis (`_least_on_axis`)."""
+ drawing = self.drawing
+ sx, sy = span[:4], span[4:]
+ least: dict[Any, tuple[float, Any]] = {}
+ for choice in itertools.product(*ways):
+ if rest + sum(floor[box] for floor, (box, _, _) in zip(floors, choice)) > self.best + 2 * TIE:
continue
- k = mains[depth]
- own = cut[k] not in largest
- for i in sorted(map(int, np.flatnonzero(reachable[k])), key=lambda i: own and i == cut[k]): # own on top
- if shortfall(more := placed + ((k, i),)) <= within:
- stack.append((depth + 1, more, largest if i in largest else {**largest, i: k},
- differs or not (own and i == cut[k])))
- return None
-
- other = otherwise()
- if other is None:
+ key = fixed.copy()
+ rows_x: list[Row] = []
+ rows_y: list[Row] = []
+ for part, (box, rx, ry) in zip(undecided, choice):
+ key[part] = box
+ rows_x += rx
+ rows_y += ry
+ placed = np.flatnonzero(key >= 0)
+ places = key.tobytes()
+ point = []
+ cost = float(drawing.loose[key < 0].sum())
+ for axis, side, rows in ((drawing.x, sx, rows_x), (drawing.y, sy, rows_y)):
+ memo = (axis is drawing.x, places, tuple(rows))
+ if memo not in least:
+ least[memo] = _least_on_axis(side, rows, axis.hinges(placed, key[placed]))
+ value, at = least[memo]
+ if at is None:
+ break
+ cost += value
+ point += at
+ else:
+ self.exact = min(self.exact, cost)
+ self.note(tuple(key.tolist()), cost, tuple(point), (sx, rows_x, sy, rows_y))
+
+ def run(self) -> Judgment:
+ drawing = self.drawing
+ count = len(drawing.parts)
+ region = self.region
+ for drift in ((1.0, 0.0, 1.0, 0.0), _centre(region)):
+ self.read(drift)
+ open_, fixed = np.arange(count), np.full(count, -2)
+ tick = itertools.count()
+ heap = [(drawing.bound(region, open_, fixed)[0], 0, next(tick), region, open_, fixed)]
+ proven = None
+ while heap and len(self.close) < 2:
+ floor = min(heap[0][0], self.exact)
+ if self.nodes >= SEARCH_NODES and floor > TIE:
+ proven = floor # every reading costs more than TIE: the drawing does not lie on the layout
+ break
+ bound, depth, _, span, open_, fixed = heapq.heappop(heap)
+ if bound > self.best + 2 * TIE:
+ break
+ self.nodes += 1
+ bound, info = drawing.bound(span, open_, fixed)
+ may, free = info["may"], info["free"]
+ number = may.sum(axis=1)
+ decided = (number == 0) | ((number == 1) & ~free)
+ fixed = fixed.copy()
+ fixed[open_[decided]] = np.where(number[decided] == 0, -1, may[decided].argmax(axis=1))
+ rows = np.flatnonzero(~decided)
+ undecided = open_[rows]
+ ways = [drawing.outcomes(span, int(part), int(row), info) for part, row in zip(undecided, rows)]
+ low, high, width = _split(span, drawing)
+ if math.prod(len(each) for each in ways) <= LEAF_WAYS or width < LEAF_WIDTH:
+ # the bound of each way of reading a part: its least in each box, or in none
+ floors = [{**dict(zip(map(int, np.flatnonzero(may[row])), info["short"][row, may[row]].tolist())),
+ -1: float(drawing.loose[part])} for part, row in zip(undecided, rows)]
+ self.solve(span, fixed, undecided, ways, floors, bound - float(info["least"][rows].sum()))
+ continue
+ self.read(_centre(span))
+ for half in (low, high):
+ half_bound = drawing.bound(half, undecided, fixed)[0]
+ if half_bound <= self.best + 2 * TIE:
+ heapq.heappush(heap, (half_bound, depth - 1, next(tick), half, undecided, fixed))
+ lower = min(heap[0][0] if heap else math.inf, self.exact, self.best)
+ return self.judgment(proven, lower)
+
+ def judgment(self, proven: float | None, lower: float) -> Judgment:
+ """The judgment of what the search found (`Judgment`)."""
+ drawing = self.drawing
+ if proven is not None:
+ return Judgment(drawing.parts, proven, proven, (), proven, self.nodes, drawing)
+ found = {key: entry for key, entry in self.found.items() if entry[0] <= self.best + 2 * TIE}
+ if len(self.close) > 1:
+ # stopped early: two readings that hold every required box cost TIE or less, so both lie within TIE of
+ # the least cost of such a reading, which lies within TIE of the least cost, and neither is drifted
+ least = least_valid = lower
+ picked = sorted(self.close)
+ else:
+ least = self.best
+ least_valid = min((entry[0] for key, entry in found.items() if drawing.valid(key)), default=math.inf)
+ whole = least_valid <= least + TIE # the readings that hold every required box are the candidates
+ tier = least_valid if whole else least
+ picked = [key for key, entry in found.items()
+ if entry[0] <= tier + TIE and (drawing.valid(key) or not whole)]
+ picked.sort(key=lambda key: (found[key][0], key))
+ candidates = tuple(Reading(self.inside(key, *found[key][1:]), drawing.named(key), found[key][0])
+ for key in picked)
+ return Judgment(drawing.parts, least, least_valid, candidates, None, self.nodes, drawing)
+
+ def inside(self, key: tuple[int, ...], drift: tuple[float, float, float, float],
+ solved: Any) -> tuple[float, float, float, float]:
+ """A drift that reads the drawing as ``key`` says at its least cost, to within a millionth of a pixel. A span
+ solved whole reaches its least cost at a corner, which may lie on the edge of a widened box, where the drawing
+ reads otherwise: the corner is moved toward the middle of the drifts the reading's rows keep, by the smallest
+ step that reads it so."""
+ if solved is None or self.drawing.read(drift)[1] == key:
+ return drift
+ sx, rows_x, sy, rows_y = solved
+ middle_x, middle_y = _middle(sx, rows_x), _middle(sy, rows_y)
+ if middle_x is None or middle_y is None:
+ return drift
+ start = np.asarray(drift)
+ towards = np.array((*middle_x, *middle_y)) - start
+ for step in 10.0 ** np.arange(-12, -2):
+ sx_, tx_, sy_, ty_ = (float(value) for value in start + step * towards)
+ if self.drawing.read((sx_, tx_, sy_, ty_))[1] == key:
+ return sx_, tx_, sy_, ty_
+ return drift
+
+
+def _centre(span: tuple[float, ...]) -> tuple[float, float, float, float]:
+ sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1 = span
+ return (sx0 + sx1) / 2, (tx0 + tx1) / 2, (sy0 + sy1) / 2, (ty0 + ty1) / 2
+
+
+def _judge(parts: list[dict[str, Any]], size: tuple[int, int]) -> Judgment:
+ """Search the drawing for its least-cost readings (docs/ui-kit.md "Reading the drawing"). A reading at a drift puts
+ each part in the first box, in layout order, whose box moved by the drift and widened by half the gap holds its
+ centroid, or in none. Its cost adds, for each part in a box, how far each of its sides falls short of lying
+ CLEARANCE px inside the moved box, and for each part in no box `_Drawing.loose`. The search is exact: no grid, no
+ sampling. It is best-first branch and bound over the drifts the cut considers: a span of drifts is bounded below by
+ the least each part can cost in it, split across its widest side, and solved whole once its undecided parts can be
+ read in at most LEAF_WAYS ways, each then a convex piecewise-linear cost along each axis, least at a corner. A span
+ bounded above the least cost found plus 2 TIE is dropped: the readings the cut is decided among lie within it. The
+ search stops early once it has found two readings that hold every required box at a cost of TIE or less (the cut
+ then refuses the drawing as ambiguous, whatever else there is to find), and after SEARCH_NODES spans once every
+ reading is proven to cost more than TIE."""
+ return _Search(_Drawing(parts, size)).run()
+
+
+def _drifted(drift: tuple[float, float, float, float], unit: float) -> str:
+ sx, tx, sy, ty = drift
+ return (f"the drawing drifted further from the layout than a cut accepts: fitted to it, the layout is scaled "
+ f"{sx:.3f} along x and {sy:.3f} along y and offset {tx:.1f}, {ty:.1f} px, where a cut accepts a scale "
+ f"from {1 - DRIFT_SCALE:g} to {1 + DRIFT_SCALE:g} and an offset of at most {DRIFT_OFFSET * unit:g} px "
+ "along each axis; generate the sheet again")
+
+
+def _centred(drawing: _Drawing, key: tuple[int, ...], cost: float) -> tuple[float, float, float, float] | None:
+ """A drift whose cost is within TIE of ``cost``, that keeps the parts ``key`` places in their widened boxes and puts
+ the centre of each box's parts' bounding box inside the moved box; None when there is none."""
+ scale, offset = _drift_limits(drawing.unit)
+ held = np.asarray(key, dtype=int)
+ placed = np.flatnonzero(held >= 0)
+ found = []
+ for axis, index in ((drawing.x, 0), (drawing.y, 1)):
+ rows = [row for part in placed for row in axis.within(int(part), int(held[part]))]
+ for box in sorted(set(held[placed].tolist())):
+ members = np.flatnonzero(held == box)
+ middle = float(drawing.bbox[members, index].min() + drawing.bbox[members, index + 2].max()) / 2
+ rows += [(float(axis.e0[0, box]), 1.0, middle), (-float(axis.e1[0, box]), -1.0, -middle)]
+ found.append(_least_on_axis((1 - scale, 1 + scale, -offset, offset), rows, axis.hinges(placed, held[placed])))
+ (vx, px), (vy, py) = found
+ if px is None or py is None or vx + vy + float(drawing.loose[held < 0].sum()) > cost + TIE:
return None
- changed = [name for i, name in enumerate(names) if named.get(i) != other.get(i)]
- one = len(changed) == 1
- return (f"{', '.join(changed)}: under another drift the cut accepts, the drawing fits the layout at least as "
- f"well (to within {TIE:g} px) with {'this element' if one else 'these elements'} named differently, so "
- f"it does not say which {'element it is' if one else 'elements they are'}; generate the sheet again")
-
-
-def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,
- alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:
- """Cut ``image`` along the layout: element images by name, and the report as written to its default
- place, ``<out-dir>/ui-kit.json`` (each ``file`` is ``<element>.png``), without the sheet path."""
+ return px[0], px[1], py[0], py[1]
+
+
+def _decide(judgment: Judgment) -> Reading:
+ """The cut: the one candidate, at the drift its report gives; or the refusal the judgment calls for, in the order
+ docs/ui-kit.md "Reading the drawing" gives. The report's drift is the first of the layout's own boxes, the
+ least-squares fit of the cut's assignment (`_fit`), the centring drift and the cut's least-cost drift that reads
+ the cut at a cost within TIE of its own."""
+ drawing = judgment.drawing
+ if judgment.proven is not None:
+ raise Refusal("the drawing does not lie on the layout under any drift a cut accepts: every reading leaves its "
+ f"parts at least {math.floor(judgment.proven)} px across their boxes' edges or in no box; "
+ "generate the sheet again", "off-layout", judgment)
+ candidates = judgment.candidates
+ keys = [tuple(drawing.names.index(name) if name is not None else -1 for name in reading.boxes)
+ for reading in candidates]
+ first = candidates[0]
+ if first.cost > TIE:
+ fit = _fit(drawing.assigned(keys[0]), dict(drawing.layout))
+ if fit is not None and not _considered(fit, drawing.unit) and drawing.read(fit)[0] < first.cost - TIE:
+ raise Refusal(_drifted(fit, drawing.unit), "drifted", judgment)
+ if not drawing.valid(keys[0]):
+ empty = [drawing.names[box] for box in sorted(drawing.required) if all(box not in key for key in keys)]
+ if empty:
+ holds = "its box holds" if len(empty) == 1 else "their boxes hold"
+ raise Refusal(f"{', '.join(empty)}: {holds} no element; generate the sheet again", "required", judgment)
+ if len(candidates) > 1:
+ one, other = keys[0], keys[1]
+ changed = [drawing.names[box] for box in sorted(
+ {box for pair in zip(one, other) if pair[0] != pair[1] for box in pair} - {-1})]
+ single = len(changed) == 1
+ one_or_more = ("this element", "element it is") if single else ("these elements", "elements they are")
+ raise Refusal(f"{', '.join(changed)}: under another drift the cut accepts, the drawing fits the layout at "
+ f"least as well (to within {TIE:g} px) with {one_or_more[0]} named differently, so it does not "
+ f"say which {one_or_more[1]}; generate the sheet again", "ambiguous", judgment,
+ (candidates[0], candidates[1]))
+ cut, key = first, keys[0]
+ assigned = drawing.assigned(key)
+ centred = _centred(drawing, key, cut.cost)
+ if centred is None:
+ sx, tx, sy, ty = cut.drift
+ moved = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in drawing.layout.items()}
+ off = _off_centre(assigned, moved)
+ if off:
+ holds = ("its box holds a part centred outside it (in the gap beside it or further, so the drawing does "
+ "not say which element it is)" if len(off) == 1 else
+ "their boxes hold parts centred outside them (in the gap beside them or further, so the drawing "
+ "does not say which elements they are)")
+ raise Refusal(f"{', '.join(off)}: {holds}; generate the sheet again", "off-centre", judgment)
+ centred = cut.drift
+ for drift in ((1.0, 0.0, 1.0, 0.0), _fit(assigned, dict(drawing.layout)), centred, cut.drift):
+ if drift is not None:
+ cost, read = drawing.read(drift)
+ if read == key and cost <= cut.cost + TIE:
+ return Reading(drift, cut.boxes, cost)
+ return cut
+
+
+def _sheet_parts(image: Image.Image, alpha_floor: int, alpha_edge: int) -> tuple[Any, Any, list[dict[str, Any]], int]:
+ """The sheet's pixels after the alpha cleanup, the cleanup's report, the parts of MIN_PART px or more, and how many
+ smaller parts were dropped."""
rgba = image.convert("RGBA")
- width, height = rgba.size
- _, slots = sheet_layout((width, height))
+ sheet_layout(rgba.size)
cleanup = None
if alpha_floor:
rgba, cleanup = clear_haze(rgba, floor=alpha_floor, edge=alpha_edge)
pixels = np.asarray(rgba)
- layout = boxes((width, height))
- scaled: dict[str, tuple[float, float, float, float]] = dict(layout)
- unit = width / REFERENCE
- reach = GAP / 2 * unit
every = _parts(pixels[..., 3] > 0)
kept = [part for part in every if part["pixels"] >= MIN_PART]
- dropped = len(every) - len(kept)
- assigned, loose = _assign(kept, scaled, (reach, reach))
- required = {slot.name for slot in slots if not slot.optional}
- fitted = None
- if any(not held for held in assigned.values()) or _off_centre(assigned, scaled):
- start = _search(kept, scaled, reach, unit)
- fitted = None if start is None else _fit_layout(kept, scaled, reach, start)
- # the layout's own boxes stand when they assign every part as the fitted boxes do, each centred in its box
- if fitted is not None and _same(fitted[2], assigned) and not _off_centre(assigned, scaled):
- fitted = None
- if fitted is not None:
- fit, scaled, assigned, loose = fitted
- drifted = _drift_refusal(fit, unit)
- if drifted:
- raise ValueError(drifted)
+ return pixels, cleanup, kept, len(every) - len(kept)
+
+
+def _read(image: Image.Image, *, alpha_floor: int = 64, alpha_edge: int = 2) -> Judgment:
+ """The judgment `split_ui_kit` decides the sheet by: its least costs and the readings it is decided among."""
+ _, _, kept, _ = _sheet_parts(image, alpha_floor, alpha_edge)
+ return _judge(kept, image.size)
+
+
+def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,
+ alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:
+ """Cut ``image`` along the layout: element images by name, and the report as written to its default
+ place, ``<out-dir>/ui-kit.json`` (each ``file`` is ``<element>.png``), without the sheet path. A `Refusal`
+ for a sheet the cut refuses."""
+ width, height = image.size
+ _, slots = sheet_layout((width, height))
+ pixels, cleanup, kept, dropped = _sheet_parts(image, alpha_floor, alpha_edge)
+ cut = _decide(_judge(kept, (width, height)))
+ sx, tx, sy, ty = cut.drift
+ scaled = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in boxes((width, height)).items()}
+ assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}
+ loose = []
+ for part, name in zip(kept, cut.boxes):
+ (assigned[name] if name is not None else loose).append(part)
unassigned, reasons = [], []
for part in loose:
x0, y0, x1, y1 = part["bbox"]
unassigned.append({"rect": _rect(x0, y0, x1 - x0, y1 - y0), "pixels": part["pixels"]})
reasons.append(f"a part of {part['pixels']} pixels at ({x0}, {y0}) lies in no box")
missing = [slot.name for slot in slots if not assigned[slot.name]]
- refused = [name for name in missing if name in required]
- if refused:
- holds = "its box holds" if len(refused) == 1 else "their boxes hold"
- raise ValueError(f"{', '.join(refused)}: {holds} no element; generate the sheet again")
- off = _off_centre(assigned, scaled)
- if off:
- holds = ("its box holds a part centred outside it (in the gap beside it or further, so the drawing does "
- "not say which element it is)" if len(off) == 1 else
- "their boxes hold parts centred outside them (in the gap beside them or further, so the drawing "
- "does not say which elements they are)")
- raise ValueError(f"{', '.join(off)}: {holds}; generate the sheet again")
- ambiguous = _ambiguity(kept, assigned, layout, unit, reach, required)
- if ambiguous:
- raise ValueError(ambiguous)
elements: dict[str, Image.Image] = {}
records: dict[str, Any] = {}
for slot in slots:
@@ -729,11 +1006,11 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,
if not parts:
continue
x0, y0, x1, y1 = _bbox(parts)
- cut = np.zeros((y1 - y0, x1 - x0, 4), dtype=np.uint8)
+ cut_pixels = np.zeros((y1 - y0, x1 - x0, 4), dtype=np.uint8)
for part in parts:
for y, a, b in part["runs"]:
- cut[y - y0, a - x0:b - x0] = pixels[y, a:b]
- element = Image.fromarray(cut)
+ cut_pixels[y - y0, a - x0:b - x0] = pixels[y, a:b]
+ element = Image.fromarray(cut_pixels)
insets, inset_notes = measure_insets(element, slot.stretch)
padding, padding_notes = measure_padding(element) if slot.content else (dict.fromkeys(SIDES, 0), [])
round_notes = measure_round(element) if slot.round else []
@@ -766,8 +1043,7 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,
# a layout with optional elements always says which are missing; a square sheet's elements are all required
if any(slot.optional for slot in slots):
report["missing"] = missing
- if fitted is not None:
- (sx, tx), (sy, ty) = fit
+ if cut.drift != (1.0, 0.0, 1.0, 0.0):
# `+ 0.0`: an offset that rounds to zero is written 0.0, never -0.0
report["layout_fit"] = {"scale": {"x": round(sx, 4), "y": round(sy, 4)},
"offset": {"x": round(tx, 1) + 0.0, "y": round(ty, 1) + 0.0}}
diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.py
index e667921..43e964b 100644
--- a/tests/frames/test_ui_kit.py
+++ b/tests/frames/test_ui_kit.py
@@ -882,8 +882,8 @@ def scattered_sheet(seed):
def anchored_sheet(seed):
"""A 2:3 sheet drawn under a drift picked at random within the accepted range: the seven frames full size, as
`synthetic_sheet` draws them, and a random half of the band elements, each a rectangle a random share of its box
- across (from a twentieth to seven tenths) anywhere inside its moved box, at least 1 px clear of the edges. The sheet,
- and each element's rect by name."""
+ across (from a twentieth to seven tenths) anywhere inside its moved box, at least 1 px clear of the edges. The
+ sheet, and each element's rect by name."""
rng = np.random.default_rng(100_000 + seed)
drift = accepted_drift(rng)
sx, tx, sy, ty = drift