"""Geometry renderer — ``geometry_world_v1`` → four assets (``docs/02`` §9.4, P6). Lays out a constraint graph deterministically. Free points are variables in ``[0,1]^2``; each supported predicate becomes a residual function; a fixed 16-seed ``scipy.optimize.least_squares`` run finds a realization. The renderer keeps the solution only when the max normalized residual is ``< 1e-6`` and every pair of distinct points is separated by ``> 0.02``; among the survivors it picks the one with the canonical-smallest rounded coordinate tuple (§9.4 steps 3–4). Unsupported predicates, an infeasible layout (no survivor), and degenerate / ambiguous drawings (a single-vertex angle with a stated measure, a segment referencing an unknown point) are **rejected** via :class:`RenderError` — P6 never silently coerces an unrenderable world into assets and never re-derives a geometry theorem to "fix" one (§9.4: "renderer는 geometry theorem을 새로 추론해 world를 수정하지 않는다"). REDACT_SOLID_V1 (§10.1): a hidden point is not drawn as data — a fixed, content-independent solid patch is painted at its would-be location, owned by no node. A hidden segment/angle is simply omitted from the canvas and the node map (a content-independent patch is well-defined for a point token, not for a line). No raster is ever edited or inpainted. """ from __future__ import annotations import hashlib from typing import Any, cast from ..dsl.ast import parse_number from ..sources.base import World from ..sources.world_ops import hidden_nodes from .base import ( DrawCommand, GlyphRecord, RenderedAssets, RendererFamily, RendererKind, RenderError, _Layout, build_render_manifest, build_text_manifest, font_sha256, paint_text, rasterize, validate_rendered_assets, ) _NAME = "geometry_renderer" _VERSION = "1" _KIND: RendererKind = "geometry" # §9.4 acceptance thresholds. _MAX_RESIDUAL = 1e-6 _MIN_SEPARATION = 0.02 _SEEDS = 16 _ROUND = 6 # coordinate rounding for the canonical selection tuple # Predicates this renderer can turn into placement residuals. Anything else is # rejected (§9.4 step 6) rather than silently dropped or guessed. _SUPPORTED_PREDICATES = frozenset( {"IsMidpointOf", "MeasureOf", "Equals", "Parallel", "Perpendicular"} ) # Marginal padding so drawn geometry is not flush against the canvas edge. _MARGIN = 0.12 class GeometryRenderer: """Deterministic renderer for ``geometry_world_v1``.""" name = _NAME version = _VERSION kind = _KIND def render( self, world: World, *, renderer_id: str, seed: int, width: int, height: int, family: RendererFamily | None = None, ) -> RenderedAssets: if world.get("world_schema") != "geometry_world_v1": raise RenderError( f"geometry renderer expects geometry_world_v1, got {world.get('world_schema')!r}" ) family = family or _GEO_TRAIN_FAMILY if family.kind != self.kind: raise RenderError( f"renderer family {family.name!r} has kind {family.kind!r}, expected {self.kind!r}" ) if renderer_id != family.name: raise RenderError(f"renderer_id {renderer_id!r} does not match family {family.name!r}") layout = _build_layout(world, family, seed, renderer_id) rgba_png, node_map_png, counts = rasterize(layout, width=width, height=height, seed=seed) manifest = build_render_manifest( renderer_id=renderer_id, renderer_name=self.name, renderer_version=self.version, family=family, world=world, seed=seed, width=width, height=height, rgba_png=rgba_png, node_map_png=node_map_png, visible_node_ids=layout.visible_node_ids, owner_ids=layout.owner_ids, node_pixel_counts=counts, glyph_count=len(layout.glyphs), ) text_manifest = build_text_manifest(layout.glyphs, world=world) assets = RenderedAssets( rgba_png=rgba_png, node_map_png=node_map_png, render_manifest=manifest, text_manifest=text_manifest, ) validate_rendered_assets(assets) return assets # --- entity / point model --------------------------------------------------- def _point_label(entity_id: str) -> str | None: """``point:A`` → ``"A"``; non-point entities → ``None``.""" if entity_id.startswith("point:"): return entity_id.split(":", 1)[1] return None def _segment_endpoints(entity_id: str) -> tuple[str, str] | None: """``segment:A_B`` → ``("A", "B")``; non-segment → ``None``.""" if entity_id.startswith("segment:"): body = entity_id.split(":", 1)[1] parts = body.split("_") if len(parts) == 2 and parts[0] and parts[1]: return parts[0], parts[1] return None def _angle_points(entity_id: str) -> tuple[str, str, str] | None: """``angle:A_B_C`` → ``("A","B","C")`` (vertex B); single-vertex → ``None``.""" if entity_id.startswith("angle:"): body = entity_id.split(":", 1)[1] parts = body.split("_") if len(parts) == 3 and all(parts): return parts[0], parts[1], parts[2] return None def _collect_points(world: World) -> list[str]: """Sorted labels of every free point (declared or referenced by a segment/angle).""" labels: set[str] = set() for e in world.get("entities", []) or []: eid = str(e.get("id", "")) lab = _point_label(eid) if lab is not None: labels.add(lab) ends = _segment_endpoints(eid) if ends is not None: labels.update(ends) ang = _angle_points(eid) if ang is not None: labels.update(ang) return sorted(labels) # --- constraint → residual -------------------------------------------------- # # Each residual function takes the flat coordinate vector ``xy`` (length 2N for N # point labels in sorted order) and returns a 1-D array of residuals. Point # label → index lookup is closed over per constraint. def _residuals(world: World, index: dict[str, int]) -> list[Any]: import numpy as np def pt(xy: np.ndarray, label: str) -> np.ndarray: i = index[label] return np.array([xy[2 * i], xy[2 * i + 1]], dtype=float) residuals: list[Any] = [] for c in world.get("constraints", []) or []: pred = str(c.get("predicate", "")) args = [str(a) for a in (c.get("args") or [])] if pred not in _SUPPORTED_PREDICATES: raise RenderError(f"unsupported geometry predicate: {pred!r}") if pred == "IsMidpointOf": # args: [point:D, segment:A_B] — D == midpoint of AB. if len(args) != 2: raise RenderError(f"IsMidpointOf needs 2 args, got {args!r}") d = _require_point(args[0], index=index) ends = _segment_endpoints(args[1]) if ends is None: raise RenderError(f"IsMidpointOf target is not a segment: {args[1]!r}") a, b = ends a = _require_point(a, index=index) b = _require_point(b, index=index) def r_mid(xy: np.ndarray, a: str = a, b: str = b, d: str = d) -> np.ndarray: mid = 0.5 * (pt(xy, a) + pt(xy, b)) return cast(np.ndarray, pt(xy, d) - mid) residuals.append(r_mid) elif pred == "MeasureOf": # args: [angle:A_B_C, deg] — angle at vertex B between BA and BC == deg. if len(args) != 2: raise RenderError(f"MeasureOf needs 2 args, got {args!r}") ang = _angle_points(args[0]) if ang is None: raise RenderError( f"MeasureOf needs a 3-point angle (vertex ambiguous): {args[0]!r}" ) a, b, c = ang _require_point(a, index=index) _require_point(b, index=index) _require_point(c, index=index) target = float(parse_number(args[1])) def r_ang( xy: np.ndarray, a: str = a, b: str = b, c: str = c, target: float = target ) -> np.ndarray: v1 = pt(xy, a) - pt(xy, b) v2 = pt(xy, c) - pt(xy, b) n1 = float(np.hypot(*v1)) n2 = float(np.hypot(*v2)) if n1 == 0.0 or n2 == 0.0: return np.array([180.0], dtype=float) cos_t = float(np.dot(v1, v2) / (n1 * n2)) cos_t = max(-1.0, min(1.0, cos_t)) measured = float(np.degrees(np.arccos(cos_t))) return np.array([measured - target], dtype=float) residuals.append(r_ang) elif pred == "Equals": # Numeric equality between two literals, or equal-length of two # segments. Bare entity equality (no numeric) is not placeable. if len(args) != 2: raise RenderError(f"Equals needs 2 args, got {args!r}") if _looks_numeric(args[0]) and _looks_numeric(args[1]): # Pure numeric fact — no placement residual (already satisfied or # a feasibility concern, not a renderer concern). continue s1 = _segment_endpoints(args[0]) s2 = _segment_endpoints(args[1]) if s1 is not None and s2 is not None: a, b = s1 c, d = s2 for lbl in (a, b, c, d): _require_point(lbl, index=index) def r_eq_len( xy: np.ndarray, a: str = a, b: str = b, c: str = c, d: str = d ) -> np.ndarray: l1 = float(np.hypot(*(pt(xy, a) - pt(xy, b)))) l2 = float(np.hypot(*(pt(xy, c) - pt(xy, d)))) return np.array([l1 - l2], dtype=float) residuals.append(r_eq_len) else: raise RenderError(f"Equals is not a placeable fact: {args!r}") elif pred in ("Parallel", "Perpendicular"): if len(args) != 2: raise RenderError(f"{pred} needs 2 args, got {args!r}") s1 = _segment_endpoints(args[0]) s2 = _segment_endpoints(args[1]) if s1 is None or s2 is None: raise RenderError(f"{pred} operands must be segments: {args!r}") a, b = s1 c, d = s2 for lbl in (a, b, c, d): _require_point(lbl, index=index) want_perp = pred == "Perpendicular" def r_dir( xy: np.ndarray, a: str = a, b: str = b, c: str = c, d: str = d, want_perp: bool = want_perp, ) -> np.ndarray: v1 = pt(xy, a) - pt(xy, b) v2 = pt(xy, c) - pt(xy, d) cross = float(v1[0] * v2[1] - v1[1] * v2[0]) dot = float(np.dot(v1, v2)) if want_perp: # Perpendicular ⟂ → dot product 0. return np.array([dot], dtype=float) # Parallel ∥ → cross product 0 (directions aligned). return np.array([cross], dtype=float) residuals.append(r_dir) return residuals def _require_point(entity: str, *, index: dict[str, int] | None = None) -> str: """Validate that ``entity`` names a free point; return its bare label. ``entity`` may be a point entity id (``point:D``) or a bare label (``D``). The ``index`` guard (when passed) raises :class:`RenderError` for a dangling reference; without it the label is only syntax-checked. """ label = _point_label(entity) or entity if index is not None and label not in index: raise RenderError(f"geometry references unknown point {entity!r}") return label def _looks_numeric(text: str) -> bool: try: parse_number(text) return True except (ValueError, ZeroDivisionError): return False # --- layout solver (§9.4 steps 2–4) ----------------------------------------- def _solve_layout( world: World, labels: list[str], *, seed: int, renderer_id: str ) -> dict[str, tuple[float, float]]: """Return ``{point_label: (x, y)}`` realizing the constraints, or raise.""" import numpy as np from scipy.optimize import least_squares n = len(labels) if n == 0: return {} index = {lab: i for i, lab in enumerate(labels)} res_fns = _residuals(world, index) def residuals(xy: np.ndarray) -> np.ndarray: parts = [fn(xy) for fn in res_fns] if not parts: return np.zeros(0, dtype=float) return np.concatenate(parts) def subseed(k: int) -> int: h = hashlib.sha256(f"{seed}:{renderer_id}:{k}".encode()).digest() return int.from_bytes(h[:8], "little") best: tuple[Any, np.ndarray] | None = None # (canonical_key, xy) for k in range(_SEEDS): rng = np.random.default_rng(subseed(k)) # Deterministic initial guess: a jittered grid in the inner canvas. cols = int(np.ceil(np.sqrt(max(n, 1)))) x0 = np.zeros(2 * n, dtype=float) for i in range(n): r, c = divmod(i, cols) gx = _MARGIN + (c + 0.5) * (1 - 2 * _MARGIN) / max(cols, 1) gy = _MARGIN + (r + 0.5) * (1 - 2 * _MARGIN) / max(int(np.ceil(n / cols)), 1) jitter = rng.uniform(-0.03, 0.03, size=2) x0[2 * i] = float(np.clip(gx + jitter[0], 0.05, 0.95)) x0[2 * i + 1] = float(np.clip(gy + jitter[1], 0.05, 0.95)) if res_fns: sol = least_squares( residuals, x0, bounds=([0.0] * (2 * n), [1.0] * (2 * n)), method="trf", xtol=1e-15, ftol=1e-15, gtol=1e-15, max_nfev=20000, ) cand = sol.x cost = float(np.max(np.abs(residuals(cand)))) if cand.size else 0.0 else: # No placement residuals: the jittered grid is itself a realization; # only the separation / canonical-selection gates apply. cand = x0 cost = 0.0 if cost >= _MAX_RESIDUAL: continue if not _separated(cand, n): continue key = tuple(round(float(v), _ROUND) for v in cand) if best is None or key < best[0]: best = (key, cand) if best is None: raise RenderError("geometry layout infeasible (no seed met residual/separation gates)") xy = best[1] return {lab: (float(xy[2 * i]), float(xy[2 * i + 1])) for i, lab in enumerate(labels)} def _separated(xy: Any, n: int) -> bool: """Every pair of distinct points is farther apart than ``_MIN_SEPARATION``.""" import numpy as np if n < 2: return True pts = xy.reshape(n, 2) for i in range(n): for j in range(i + 1, n): if float(np.hypot(pts[i, 0] - pts[j, 0], pts[i, 1] - pts[j, 1])) <= _MIN_SEPARATION: return False return True # --- layout → draw plan ----------------------------------------------------- def _build_layout(world: World, family: RendererFamily, seed: int, renderer_id: str) -> _Layout: hidden = hidden_nodes(world) labels = _collect_points(world) coords = _solve_layout(world, labels, seed=seed, renderer_id=renderer_id) commands: list[DrawCommand] = [] glyphs: list[GlyphRecord] = [] owner_ids: list[str] = [] visible: list[str] = [] font = family.font_name def point_xy(label: str) -> tuple[float, float]: return coords[label] # Points first (markers + labels). for e in world.get("entities", []) or []: eid = str(e.get("id", "")) lab = _point_label(eid) if lab is None or lab not in coords: continue x, y = point_xy(lab) if eid in hidden: commands.append((None, _patch(x, y, family.palette.get("redact", "#000000")))) continue visible.append(eid) owner_ids.append(eid) commands.append((eid, _point_marker(x, y, family.palette.get("point", "#1f77b4")))) glyphs.append(_glyph(eid, lab, x + 0.015, y + 0.015, font)) # Segments (lines + midpoint labels). for e in world.get("entities", []) or []: eid = str(e.get("id", "")) ends = _segment_endpoints(eid) if ends is None: continue a, b = ends if a not in coords or b not in coords: raise RenderError(f"segment {eid!r} references an unplaced point") ax_, ay_ = point_xy(a) bx_, by_ = point_xy(b) if eid in hidden: continue # hidden segment omitted (no content-independent line patch) visible.append(eid) owner_ids.append(eid) commands.append((eid, _segment(ax_, ay_, bx_, by_, family.palette.get("line", "#444444")))) glyphs.append(_glyph(eid, eid.split(":", 1)[1], (ax_ + bx_) / 2, (ay_ + by_) / 2, font)) # Angles (3-point arcs + measure labels from a MeasureOf constraint). measure_of: dict[str, str] = {} for c in world.get("constraints", []) or []: if str(c.get("predicate")) == "MeasureOf": args = [str(a) for a in (c.get("args") or [])] if len(args) == 2: measure_of[args[0]] = args[1] for e in world.get("entities", []) or []: eid = str(e.get("id", "")) ang = _angle_points(eid) if ang is None: continue a, b, c = ang if a not in coords or b not in coords or c not in coords: raise RenderError(f"angle {eid!r} references an unplaced point") bx_, by_ = point_xy(b) if eid in hidden: continue visible.append(eid) owner_ids.append(eid) commands.append( ( eid, _angle_arc( point_xy(a), (bx_, by_), point_xy(c), family.palette.get("angle", "#b22222") ), ) ) text = measure_of.get(eid) if text is not None: glyphs.append(_glyph(eid, f"{text}°", bx_ + 0.02, by_ + 0.02, font)) # Paint every label glyph as owned text so each entity owns its label pixels # (§9.4 step 5); the GlyphRecord still drives the text manifest. for g in glyphs: commands.append((g.node_id, paint_text(g.text, g.x0, g.y0, family.font_name))) return _Layout( commands=tuple(commands), glyphs=tuple(glyphs), owner_ids=tuple(_dedup(owner_ids)), visible_node_ids=tuple(_dedup(visible)), family=family, ) # --- draw primitives (deterministic, family-coloured) ----------------------- def _point_marker(x: float, y: float, color: str) -> Any: from matplotlib.patches import Circle def draw(ax: Any) -> None: ax.add_patch(Circle((x, y), 0.012, facecolor=color, edgecolor="black", lw=0.5)) return draw def _patch(x: float, y: float, color: str) -> Any: from matplotlib.patches import Rectangle def draw(ax: Any) -> None: ax.add_patch(Rectangle((x - 0.02, y - 0.02), 0.04, 0.04, facecolor=color, edgecolor="none")) return draw def _segment(x0: float, y0: float, x1: float, y1: float, color: str) -> Any: def draw(ax: Any) -> None: ax.plot([x0, x1], [y0, y1], color=color, lw=1.5) return draw def _angle_arc( a: tuple[float, float], b: tuple[float, float], c: tuple[float, float], color: str ) -> Any: import numpy as np def draw(ax: Any) -> None: from matplotlib.patches import Arc # Angle at vertex b between rays b→a and b→c. v1 = np.array(a) - np.array(b) v2 = np.array(c) - np.array(b) theta1 = float(np.degrees(np.arctan2(v1[1], v1[0]))) theta2 = float(np.degrees(np.arctan2(v2[1], v2[0]))) ax.add_patch( Arc( b, 0.05, 0.05, angle=0.0, theta1=min(theta1, theta2), theta2=max(theta1, theta2), color=color, lw=1.5, ) ) return draw def _glyph(node_id: str, text: str, x: float, y: float, font_name: str) -> GlyphRecord: return GlyphRecord( node_id=node_id, text=text, x0=x, y0=y, x1=x + 0.03 * len(text), y1=y + 0.03, font_sha256=font_sha256(font_name), ) def _dedup(items: list[str]) -> list[str]: seen: set[str] = set() out: list[str] = [] for it in items: if it not in seen: seen.add(it) out.append(it) return out # --- families (train vs held-out: disjoint font + palette) ------------------ _GEO_TRAIN_FAMILY = RendererFamily( name="geometry_train_v1", kind="geometry", font_name="DejaVu Sans", palette={ "background": "#FFFFFF", "point": "#1f77b4", "line": "#444444", "angle": "#b22222", "redact": "#000000", }, layout={"margin": _MARGIN, "min_separation": _MIN_SEPARATION}, ) _GEO_HELDOUT_FAMILY = RendererFamily( name="geometry_heldout_v1", kind="geometry", font_name="DejaVu Serif", palette={ "background": "#F7F7F0", "point": "#2a9d8f", "line": "#333333", "angle": "#9d4edd", "redact": "#222222", }, layout={"margin": _MARGIN, "min_separation": _MIN_SEPARATION}, ) GEOMETRY_FAMILIES: dict[str, RendererFamily] = { "geometry_train_v1": _GEO_TRAIN_FAMILY, "geometry_heldout_v1": _GEO_HELDOUT_FAMILY, } __all__ = ["GEOMETRY_FAMILIES", "GeometryRenderer"]